ColumnText.ShowTextAligned()在换行后切断文本

时间:2016-09-30 12:35:00

标签: vb.net itext

我有以下代码使用iTextSharp将文本打印到PDF文档:

canvas = stamper.GetOverContent(i)
watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
watermarkFontColor = iTextSharp.text.BaseColor.RED
canvas.SetFontAndSize(watermarkFont, 11)
canvas.SetColorFill(watermarkFontColor)

Dim sText As String = "Line1" & vbCrLf & "Line2"
Dim nPhrase As New Phrase(sText)

ColumnText.ShowTextAligned(canvas, Element.ALIGN_TOP, nPhrase, 0, 50, 0)

但是,只打印第一行(“Line1”),第二行(“Line2”)不打印。

我是否必须通过任何标志才能使其发挥作用?

2 个答案:

答案 0 :(得分:1)

如上所述,ShowTextAligned()方法只能用于绘制单行。如果要绘制两行,则有两个选项:

选项1:使用该方法两次:

ColumnText.ShowTextAligned(canvas, Element.ALIGN_TOP, new Phrase("line 1"), 0, 50, 0)
ColumnText.ShowTextAligned(canvas, Element.ALIGN_TOP, new Phrase("line 2"), 0, 25, 0)

选项2:以不同的方式使用ColumnText

ColumnText ct = new ColumnText(canvas);
ct.SetSimpleColumn(rect);
ct.AddElement(new Paragraph("line 1"));
ct.AddElement(new Paragraph("line 2"));
ct.Go();

在此代码段中,rect的类型为Rectangle。它定义了要添加文本的区域。见How to add text in PdfContentByte rectangle using itextsharp?

答案 1 :(得分:0)

ColumnText.ShowTextAligned已被实现为在给定对齐的情况下在给定位置添加单行的用例的捷径。授予源代码文档:

/** Shows a line of text. Only the first line is written.
 * @param canvas where the text is to be written to
 * @param alignment the alignment
 * @param phrase the <CODE>Phrase</CODE> with the text
 * @param x the x reference position
 * @param y the y reference position
 * @param rotation the rotation to be applied in degrees counterclockwise
 */    
public static void ShowTextAligned(PdfContentByte canvas, int alignment, Phrase phrase, float x, float y, float rotation)

对于更多通用用例,请实例化ColumnText,设置要绘制的内容和要绘制的轮廓,然后调用Go()