打印RTF文件

请先打开CaseStyudy目录下的文件"PDFCreator示例.Table"再运行本节的示例代码。

既然PDFCreator可以绘制RTF格式的文本,那么也就可以绘制RTF文件,因为RTF文件本就是Text格式,将其读取进来后用DrawStringRtf绘制即可。

示例一

请在在命令窗口运行下面的代码,这个代码将一个RTF文件转成PDF格式:

Dim file As String = "c:\temp\test.pdf"
Dim
pdc As New PDFCreator()
Dim
fnt As New Font("Arial", 18)
Dim
txt As String = FileSys.ReadAllText(ProjectPath & "flow.rtf") '内容来自于一个rtf文件
Dim
nextChar As Integer '定义一个变量,用于记录开始绘制字符的位置,默认为0 ,也就是从第一个字符开始绘制
Dim
rect As RectangleF = pdc.PageRectangle()
rect.Inflate( - 72, - 72)
'设置页边距为72磅,也就是1英寸,2.54厘米
pdc.Pages.Clear()
'默认已经有一个页面,先清除掉
While
nextChar < txt.Length - 1 '如果还有剩余字符没有绘制
    pdc.NewPage()
    nextChar = pdc.DrawStringRtf(txt, fnt, Brushes.Black, rect, nextChar)
'注意DrawStringRtf返回的就是未绘制内容的第一个的位置
End
While
pdc.Save(file)

Process.Start(file)

生成的文档为:

示例二

你也可以分栏打印RTF文件,例如:

Dim file As String = "c:\temp\test.pdf"
Dim
pdc As New PDFCreator()
pdc.Landscape =
True '横向页面
Dim
rect As RectangleF = pdc.PageRectangle()
rect.Inflate( - 72, - 72)

'
计算出每一栏对应的RectangleF,也就是该栏内容绘制的矩形区域
Dim
cnt As Integer = 2 '分栏数,假定分2
Dim
widthCol As Double = (rect.Width - (cnt - 1) * 45) / cnt '计算栏宽,假定栏间距是45
Dim
rectCols(cnt - 1) As RectangleF
For
i As Integer = 0 To cnt - 1
    rectCols(i) = rect
    rectCols(i).Width = widthCol
'设置栏宽
    rectCols(i).X = rect.X + (widthCol + 45 ) * i
'设置栏的水平位置,假定栏间距是45
Next

'
开始绘制
Dim
fnt As New Font("Arial", 16)
Dim
txt As String = FileSys.ReadAllText(ProjectPath & "flow.rtf") '内容来自于一个rtf文件
Dim
nextChar As Integer '定义一个变量,用于记录开始绘制字符的位置,默认为0 ,也就是从第一个字符开始绘制
pdc.Pages.Clear()
'默认已经有一个页面,先清除掉
While
nextChar < txt.Length - 1 '如果还有剩余字符没有绘制
    pdc.NewPage()
'新增一页
   
For i As Integer = 0 To cnt - 1 '逐栏绘制
        nextChar = pdc.DrawStringRtf(txt, fnt, Brushes.Black, rectcols(i), nextChar)
'注意DrawStringRTf返回的就是未绘制内容的第一个字符的位置
       
If nextChar > txt.Length - 1 Then '如果已经绘制完全部内容,则退出循环
           
Exit For
       
End If
   
Next
End
While
pdc.Save(file)

Process.Start(file)

在命令窗口执行后,生成的文档为:


本页地址:http://www.foxtable.com/webhelp/topics/6073.htm