How do I create a table with multiple header in iText 8?

In the following example we are going to create a table with multiple header. We will create table header with columns that spans in multiple columns and rows.

Here are the steps:

  1. Create a PdfWriter object called writer with the output filename.
  2. Create a PpdfDocument object called pdf, and pass the writer object as parameter.
  3. Using try-with-resource block, create a Document object with the pdf object as constructor argument.
  4. Instantiate a Table object. In this example we define it with five columns, and set the width of the table to take the full page width.
  5. Add table header cell using addHeaderCell() method. We add cell that spans multiple rows or multiple columns using the Cell constructor parameters rowspan and colspan.
  6. Add some rows of data to the table.
  7. Finally, we add the table object to the document.

And here is the full code snippet:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TableWithMultiHeader {
    public static void main(String[] args) {
        TableWithMultiHeader demo = new TableWithMultiHeader();
        demo.createTable();
    }

    private void createTable() {
        try {
            PdfWriter writer = new PdfWriter("multi_header_table.pdf");
            PdfDocument pdf = new PdfDocument(writer);

            try (Document document = new Document(pdf)) {
                Table table = new Table(5);
                table.setWidth(UnitValue.createPercentValue(100));

                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("No")));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Name")));
                table.addHeaderCell(new Cell(1, 2)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Date: " + LocalDate.now()
                                .format(DateTimeFormatter.ofPattern("dd-MMM-yyyy")))));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Activity")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Start Time")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("End Time")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("1")));
                table.addCell(new Cell().add(new Paragraph("Alice")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("10:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell().add(new Paragraph("Learn ukulele basic")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("2")));
                table.addCell(new Cell().add(new Paragraph("Bob")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("09:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell()
                        .add(new Paragraph("Learn piano basic")));

                document.add(table);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Running the code will give you the result shown in the image below:

Multi-header Table

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.3</version>
    <type>pom</type>
</dependency>

Maven Central

How do I set the indentation of a Paragraph object in iText 8?

In iText 8, indentation of a Paragraph can be controlled using the setMarginLeft() and setMarginRight() method of the BlockElement class which is the super class of Paragraph.

Here is an example of how to indent a paragraph:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

public class ParagraphIndentation {
    public static void main(String[] args) throws Exception {
        PdfWriter writer = new PdfWriter("indentation.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {
            String first = """
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit, \
                    sed do eiusmod tempor incididunt ut labore et dolore magna \
                    aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
                    ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                    """;
            String second = """
                    Duis aute irure dolor in  reprehenderit in voluptate velit \
                    esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \
                    occaecat cupidatat non proident, sunt in culpa qui officia \
                    deserunt mollit anim id est laborum.
                    """;

            Paragraph firstParagraph = new Paragraph(first);
            firstParagraph.setFirstLineIndent(60);
            firstParagraph.setMarginLeft(50);
            firstParagraph.setMarginRight(50);
            document.add(firstParagraph);

            Paragraph secondParagraph = new Paragraph(second);
            secondParagraph.setFirstLineIndent(60);
            secondParagraph.setMarginLeft(50);
            secondParagraph.setMarginRight(50);
            document.add(secondParagraph);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, setMarginLeft() and setMarginRight() methods are used to set the left and right indentation of the paragraph. These methods accept a float value as the parameter for setting the left and right indentation respectively.

The setFirstLineIndent() method in the Paragraph class sets the indentation of the first line of a Paragraph in points. This option is commonly used in document formatting where the first line of a paragraph is typically indented more than the rest of the text in the paragraph.

For example, if you set paragraph.setFirstLineIndent(60);, the first line of the text in that paragraph would be indented 60 points from the left margin.

The generated PDF document looks like this:

Paragraph Indentation

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central

How do I display emojis in a PDF document using iText 8?

Displaying emojis using iText 8 requires you to use a font that supports the unicode characters for emojis. By default, the most common fonts don’t support colorful emojis, but you can use some fonts like Segoe UI Emoji (which comes with Windows 10), Apple Color Emoji, NotoColorEmoji or FreeSerif to display black and white outlined emoji characters.

Here is a simple example of how to add an emojis using Segoe UI Emoji font. You can find the font file in C:\Windows\Fonts\ directory, and the file name is seguiemj.ttf. You need to add the seguiemj.ttf file to your project’s resources, in a Maven project, under the src/main/resources directory. Then, modify your code as follows:

package org.kodejava.itext;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

import java.io.IOException;

public class DocumentWithEmoji {
    public static void main(String[] args) throws IOException {
        PdfWriter writer = new PdfWriter("emoji.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {
            PdfFont fontEmoji = PdfFontFactory.createFont("seguiemj.ttf", PdfEncodings.IDENTITY_H);

            Paragraph paragraph = new Paragraph()
                    .add(new Paragraph("Hello ").setFont(fontEmoji).setFontSize(20))
                    .add(new Paragraph("\uD83D\uDE00").setFont(fontEmoji).setFontSize(20)
                            .setFontColor(new DeviceRgb(243, 58, 106)));

            document.add(paragraph);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Hello Emoji

In this example, “\uD83D\uDE00” is the Unicode surrogate pair for the grinning face emoji (😀). This code will result in a PDF document containing the text “Hello 😀”.

To depict different emojis, you would need their respective unicode characters. You can get those from various online sources such as the official Unicode website.

Remember, though, for colored emojis, you might need to use specific emoji fonts like Apple Color Emoji or NotoColorEmoji, and even then, support can be limited, since colored font rendering is not a standard PDF feature and the display can depend heavily on the viewer software.

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central

How do I style some texts in the Paragraph object in iText 8?

In iText 8, if you want to style only part of the text inside a Paragraph object, you can use the Text object to encapsulate the text that needs separate styling.

Here’s an example:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.io.font.constants.StandardFonts;

public class ParagraphTextExample {
    public static void main(String[] args) throws Exception {
        PdfWriter writer = new PdfWriter("styled-text.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {

            PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);

            // Create a Text object and style it
            Text text1 = new Text("This text is green and super bold. ")
                    .setFont(font)
                    .setFontSize(15)
                    .setFontColor(new DeviceRgb(0, 255, 0))
                    .setBold();

            // Create another Text object and style it differently
            Text text2 = new Text("This text is blue and italic. ")
                    .setFont(font)
                    .setFontSize(12)
                    .setFontColor(new DeviceRgb(0, 0, 255))
                    .setItalic();

            // Create another Text object and style it differently
            final String text = """
                    What's in a name? \
                    That which we call a rose by any other name \
                    would smell just as sweet.
                    """;
            Text text3 = new Text(text)
                    .setFont(font)
                    .setFontSize(20)
                    .setFontColor(new DeviceRgb(243, 58, 106))
                    .setBold()
                    .setItalic();

            // Add Text objects to a single Paragraph
            Paragraph paragraph = new Paragraph().add(text1).add(text2).add(text3);

            document.add(paragraph);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, three Text objects, text1, text2, and text3, are created with different styles. The Text objects are then added to a Paragraph object. As a result, the paragraph will have mixed styles, depending on the individual text elements.

Notably, you can apply a rich variety of styling on the Text objects, including font, size, color, background color, underlines, strike-through, superscripts, subscripts, and nearly any other style applicable to text.

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central

How do I use the Paragraph class of iText 8?

The Paragraph class in iText 8 is a fundamental building block in the creation of a PDF document. It is used to add and format texts in your document.

Here’s a simple code snippet that demonstrates how to use Paragraph:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

public class ParagraphExample {
    public static void main(String[] args) throws Exception {
        PdfWriter writer = new PdfWriter("paragraph.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {
            Paragraph paragraph = new Paragraph("Hello, World!");
            document.add(paragraph);
        }
    }
}

In this example, a new Paragraph object is created with the text “Hello, World!” which is then added to the Document.

The Paragraph class also provides numerous methods to fine-tune the appearance of the text:

package org.kodejava.itext;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;

public class ParagraphSettingExample {
    public static void main(String[] args) throws Exception {
        PdfWriter writer = new PdfWriter("paragraph-setting.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {
            Paragraph paragraph = new Paragraph("Hello, World!")
                    .setFont(PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN))
                    .setFontSize(12)
                    .setBold()
                    .setItalic()
                    .setTextAlignment(TextAlignment.JUSTIFIED);

            document.add(paragraph);
        }
    }
}

In this snippet:

  • setFont() is used to set the desired font.
  • setFontSize() adjusts the text size.
  • setBold() and setItalic() can be called to apply bold and italics styles to the text.
  • setTextAlignment() can be used to align text left, right, centered, or justified.

It’s worth highlighting that the Paragraph also supports adding chunks, images, lists, and even other paragraphs, offering a wide variety of ways to customize the content and layout of your PDF documents.

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central