分栏绘制
打开CaseStyudy目录下的文件"PDFCreator示例.Table"后运行本节的示例代码。
PDFCreator可以随意分栏绘制内容,参考代码:
Dim
file
As
String
=
"c:\temp\test.pdf"
Dim
pdc
As
New
PDFCreator()
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) * 30) / cnt
'计算栏宽,假定栏间距是30
Dim
rectCols(cnt - 1)
As
RectangleF
'定义一个RectangleF数组,表示每个分栏对应的矩形局域
For
i
As
Integer
= 0
To
cnt - 1
rectCols(i) = rect
rectCols(i).Width = widthCol
'设置栏宽
rectCols(i).X = rect.X + (widthCol + 30) * i
'设置栏的水平位置
,假定栏间距是30
Next
'开始绘制
Dim
fnt
As
New
Font("Arial",
16)
Dim
txt
As
String
= FileSys.ReadAllText(ProjectPath &
"flow.txt")
'内容来自于一个文本文件
Dim
nextChar
As
Integer
'定义一个变量,用于记录开始绘制字符的位置,默认为0
,也就是从第一个字符开始绘制
pdc.Pages.Clear()
'默认已经有一个页面,先清除掉
While
nextChar < txt.Length
'如果还有剩余字符没有绘制
pdc.NewPage()
'新增一页
For
i
As
Integer
= 0
To
cnt - 1
'逐栏绘制
nextChar = pdc.DrawString(txt, fnt, Brushes.Black, rectcols(i),
nextChar)
'注意DrawString返回的就是
剩余内容的起始位置
If
nextChar > txt.Length - 1
Then
'如果已经绘制完全部内容,则退出循环
Exit
For
End
If
Next
End
While
pdc.Save(file)
Process.Start(file)
在命令窗口执行后,生成的文档如下:
删除栏首空行
和上一节的页首空行一样,栏首空行也是没有意义的,例如上图中第二页第二栏的栏首空行除了影响美观,并无实际意义。
如果要删除栏首空行,可以将代码改为:
Dim
file
As
String
=
"c:\temp\test.pdf"
Dim
pdc
As
New
PDFCreator()
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) * 30) / cnt
'计算栏宽,假定栏间距是30
Dim
rectCols(cnt - 1)
As
RectangleF
'定义一个RectangleF数组,表示每个分栏对应的矩形局域
For
i
As
Integer
= 0
To
cnt - 1
rectCols(i) = rect
rectCols(i).Width = widthCol
'设置栏宽
rectCols(i).X = rect.X + (widthCol + 30) * i
'设置栏的水平位置,假定栏间距是30
Next
'开始绘制
Dim
fnt
As
New
Font("Arial",
16)
Dim
txt
As
String
= FileSys.ReadAllText(ProjectPath &
"flow.txt")
'内容来自于一个文本文件
Dim
nextChar
As
Integer
'定义一个变量,用于记录开始绘制字符的位置,默认为0
,也就是从第一个字符开始绘制
pdc.Pages.Clear()
'默认已经有一个页面,先清除掉
While
nextChar < txt.Length
'如果还有剩余字符没有绘制
pdc.NewPage()
'新增一页
For
i
As
Integer
= 0
To
cnt - 1
'逐栏绘制
nextChar = pdc.DrawString(txt, fnt, Brushes.Black, rectcols(i),
nextChar)
'注意DrawString返回的就是剩余内容的起始位置
If
nextChar > txt.Length - 1
Then
'如果已经绘制完全部内容,则退出循环
Exit
For
Else
'如果还有剩余内容没有绘制
Dim
content
As
String
= txt.Substring(nextChar)
nextChar = nextChar + (content.Length - content.TrimStart(vbcr,
vblf).Length)
'删除剩余内容开始位置的回车符和换行符
End
If
Next
End
While
pdc.Save(file)
Process.Start(file)
执行后,第二页第二栏的栏首空行就被去掉了: