Search code examples
javapdfitextfooter

iText PDF - How to add multiline footer?


I am able to add a single line footer to the generated PDF using iText PDF but I need to add a multiline footer.

I have tried that concatenating two strings with the new line character of Java (\n) but no chance (see Code #1). Also, have tried to set the multiline footer through the float x, float y parameters of onEndPage method of the class PdfPageEventHelper. Did not work too (see Code #2).

Here is what I have tried so far:

Code #1

Phrase phrase = new Phrase("line1" + "\n" + "line2", fontNormal10);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, phrase, 40, 30, 0);

Code #2

Phrase phrase = new Phrase("line1", fontNormal10);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, phrase, 40, 30, 0);
Phrase phrase2 = new Phrase("line2", fontNormal10);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, phrase2, 40, 0, 0);

Solution

  • You are using ColumnText.showTextAligned(). That is a method that you can use to add a single line of text. You shouldn't expect it to work to add multiple lines of text.

    If you want to add more than one line, you have to define a Rectangle, and you have to use ColumnText to add the content inside this rectangle. This is (of course) explained in the official documentation, more specifically in the section Absolute positioning of text (iText 5) where you will find the question How to add text inside a rectangle?

    The code in the answer to that question is C# code, but it's easy to convert it to Java:

    Rectangle rect = new Rectangle(x1, y1, x2, y2);
    ColumnText ct = new ColumnText(writer.getDirectContent());
    ct.SetSimpleColumn(rect);
    ct.addElement(new Paragraph("This is the text added in the rectangle"));
    ct.go();
    

    Define the values of x1, y1, x2, and y2 in such a way that all the text fits into the rectangle (text that doesn't fit will be omitted), and in such a way that it is positioned at the bottom of the page.