ColumnText.ShowTextAligned()切断后的文本断行

问题描述:

我有以下代码以打印一个文本到使用iTextSharp的PDF文档:ColumnText.ShowTextAligned()切断后的文本断行

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) 

然而,仅在第一行(“线路1”)被印刷,第二行(“Line2”)不是。

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

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()

如文档所述,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?