How do I create an ordered list in iText 8?

Creating an ordered list in iText 8 involves creating a List object and adding ListItem objects to it, similarly to creating an unordered list.

For automatic numbering or bullets in a list, you’ll have to use ListNumberingType with the appropriate configuration. For example, ListNumberingType.DECIMAL for Arabic number (1, 2, 3, etc.) and ListNumberingType.ENGLISH_LOWER for English lower case alphabet (a, b, c, etc.).

Here’s an example:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.properties.ListNumberingType;

public class OrderedListExample {
    public static void main(String[] args) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf"));
        try (Document doc = new Document(pdfDoc)) {
            // Create a List object and set numbering type
            List list = new List(ListNumberingType.DECIMAL);

            // Add ListItems
            list.add(new ListItem("First item"));
            list.add(new ListItem("Second item"));
            list.add(new ListItem("Third item"));
            list.add(new ListItem("Fourth item"));

            // Add the list to our document
            doc.add(list);
        }
    }
}

In this example, we’re passing ListNumberingType.DECIMAL to the List constructor. This will number our list items as follows: “1.”, “2.”, “3.”, etc.

Other options you’ll find in the ListNumberingType enum are:

  • DECIMAL_LEADING_ZERO
  • ENGLISH_LOWER
  • ENGLISH_UPPER
  • ROMAN_LOWER
  • ROMAN_UPPER
  • GREEK_LOWER
  • GREEK_UPPER
  • ZAPF_DINGBATS_1
  • ZAPF_DINGBATS_2
  • ZAPF_DINGBATS_3
  • ZAPF_DINGBATS_4

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 create an unordered list in iText 8?

Creating an unordered list in iText 8 involves creating a List object and adding ListItem objects to it.

Here is an example of how you can do this:

package org.kodejava.itext;

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

public class UnorderedListExample {
    public static void main(String[] args) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf"));
        try (Document doc = new Document(pdfDoc)) {
            // Create a List object
            List list = new List();
            list.setListSymbol("\u2022 ");

            // Add ListItems
            list.add(new ListItem("First item"));
            list.add(new ListItem("Second item"));
            list.add(new ListItem("Third item"));
            list.add(new ListItem("Fourth item"));

            // Add the list to our document
            doc.add(list);
        }
    }
}

In this code:

  • A PdfDocument object is created to write to a PDF file named “output.pdf”.
  • A Document object is created, which represents an actual PDF document.
  • A List object is created, representing the unordered list.
  • ListItem objects representing individual list items are added to the List.
  • Finally, the List is added to the Document, and the Document is automatically closed by the try-with-resource block, and flush any remaining content to the PDF.

You may put different things in your ListItem objects, and nest other List objects within them, if you wish.

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