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

How do I add a new page to a Document with iText 8?

In iText 8, you can use the AreaBreak class to add a new page to a Document. An AreaBreak is used to start a new area in the document. This can be compared to a page break in word processing software, but in iText, it’s a bit more flexible.

You can use AreaBreak to create different layout areas in the same page. For example, it can be used to separate a chapter or section in your document into two columns. You can also use an AreaBreak to create a new page, too.

Here’s an example of how to do it:

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.AreaBreak;
import com.itextpdf.layout.element.Paragraph;

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

        // Create a document object
        try (Document document = new Document(pdf)) {
            // Add a new paragraph to the document
            document.add(new Paragraph("This is some content on Page 1"));

            // Add an area break (the new page starts here)
            document.add(new AreaBreak());

            // Add another paragraph to the document (on a new page)
            document.add(new Paragraph("This is some content on Page 2"));
        }
    }
}

In this example, the AreaBreak creates a new page before adding the second paragraph. As a result, “This is some content on Page 1” appears on the first page, while “This is some content on Page 2” appears on the second page.

While both AreaBreak and PdfDocument‘s addNewPage() method can be used to add a new page in a PDF document, they work in slightly different ways.

  • AreaBreak: This is typically used in the context of the iText Document abstraction. When you insert an AreaBreak, it tells the layout mechanism that you want to start laying out new elements in a new region (which could be a new page, or a new column, for example). This is particularly useful when adding elements like texts, images, tables, etc. sequentially to a document, and you want control over page breaks.
  • addNewPage(): This is a lower-level operation that allows you to directly interact with the PdfDocument object. This method is used when you’re not using the Document abstraction and are working directly with the PdfDocument. It provides more control over creating and customizing pages, but requires a more detailed understanding of the PDF structure.

In short, AreaBreak is generally more high-level and is useful when laying out elements via the Document abstraction, while addNewPage() is a lower-level method that offers more control but requires more detailed knowledge about the structure of PDF files.

It’s important to note that the use of one over the other depends on the specific requirements and context of your project.

Maven Dependencies

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

Maven Central