两端对齐文本
PDFCreator可以设置文本在水平方向靠左、居中、靠右对齐,但没有办法像Word或者HTML文件一样,让文本在水平方向实现两端对齐。
我们可以借助RTF格式实现文本两端对齐。
RTF指定文本水平对齐对齐的控制符为:
\ql 左对齐
\qr 右对齐
\qc 居中对齐
\qj 两端对齐
此外"\par "用于标记段落结束,"\pard"用于 清除之前的段落样式 。
不单单是文本对齐,你可以使用任何RTF格式控制符,更多的控制符可通过互联网搜索。
示例一
在命令窗口执行下面的代码:
Dim
text
As
String
=
"THE ORIGINS OF THE Portable Document Format and the Adobe
Acrobat product family date to early 1990."
text = text & text & text
Dim
file
As
String
=
"c:\temp\test.pdf"
Dim
pdc
As
New
PDFCreator()
Dim
sf
As
New
StringFormat()
Dim
rect
As
RectangleF = pdc.PageRectangle()
rect.Inflate( - 72, - 72)
Dim
fnt
As
New
Font("微软雅黑",
12)
pdc.DrawString("靠左对齐
"
& text , fnt, Brushes.Black, rect)
rect.Offset(0, 100)
sf.Alignment = StringAlignment.Center
pdc.DrawString("居中对齐
"
& text, fnt, Brushes.Black, rect, sf)
rect.Offset(0, 100)
sf.Alignment = StringAlignment.Far
pdc.DrawString("靠右对齐
"
& text, fnt, Brushes.Black, rect, sf)
'两端对齐可以通过RTF格式实现
rect.Offset(0, 100)
sf.Alignment = StringAlignment.Far
pdc.DrawStringRtf("{\qj两端对齐
"
& text &
"\par}",
fnt, Brushes.Black, rect)
pdc.Save(file)
'保存文件
Process.Start(file)
'打开文件
生成的文档为:
示例二
以前我们介绍过如何将一个文本文件转换为PDF格式,参考:绘制长文本
现在我们增加一个要求,就是转换成PDF格式后,文本必须两端对齐,参考代码如下:
Dim
text
As
String
= FileSys.ReadAllText(ProjectPath &
"flow.txt")
Dim
file
As
String
=
"c:\temp\test.pdf"
Dim
pdc
As
New
PDFCreator()
Dim
rect
As
RectangleF = pdc.PageRectangle()
rect.Inflate( - 72, - 72)
Dim
fnt
As
New
Font("微软雅黑",
14)
text =
"{\qj "
& text &
"\par}"
'加上RTF文本对齐控制符
Dim
nextChar
As
Integer
= 0
pdc.Pages.Clear()
While
nextChar < text.Length - 1
pdc.NewPage()
nextChar = pdc.DrawStringRTF(text, fnt, Brushes.Black, rect, nextChar)
'用DrawStringRTF绘制
End
While
pdc.Save(file)
Process.Start(file)