I have the following code to print a text onto a PDF document using iTextSharp:
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)
However, only the first line ("Line1") is printed, the second line ("Line2") isn't.
Do I have to pass any flags to make that work?
As documented, the ShowTextAligned()
method can only be used to draw a single line. If you want to draw two lines, you have two options:
Option 1: use the method twice:
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)
Option 2: use ColumnText
in a different way:
ColumnText ct = new ColumnText(canvas);
ct.SetSimpleColumn(rect);
ct.AddElement(new Paragraph("line 1"));
ct.AddElement(new Paragraph("line 2"));
ct.Go();
In this code snippet, rect
is of type Rectangle
. It defines the area where you want to add the text. See How to add text in PdfContentByte rectangle using itextsharp?
ColumnText.ShowTextAligned
has been implemented as a short cut for the use case of adding a single line at a given position with given alignment. Confer the source code documentation:
/** 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)
For more generic use cases please instantiate a ColumnText
, set the content to draw and the outlines to draw in, and call Go()
.