SoFunction
Updated on 2025-04-14

Two super practical libraries for Java generating PDF documents (iText and Apache PDFBox)

Two super practical libraries for Java generating PDF documents (iText and Apache PDFBox)

Updated: February 11, 2025 09:33:01 Author: Five Elements Stars
This article mainly introduces two super practical libraries for Java generating PDF documents, namely using the iText library and Apache PDFBox library to generate PDFs. The code introduction in the article is very detailed. Friends who need it can refer to it.

Preface

Implementing PDF document generation in Java is really interesting. Let’s talk about this carefully today. We have many useful libraries to choose from. Let me tell you in detail about two of the super practical libraries, one is iText and the other is Apache PDFBox.

Generate PDF using iText library

Ideas

  • First introduce the iText library, which is like installing a "magic tool" to generate PDFs on our Java project.

  • Create aDocumentObject, this object is like a piece of white paper, on which we want to draw the content of the PDF.

  • Open this "white paper" and set the fonts and other things at the same time, just like preparing the brush and paint.

  • PastDocumentAdding various contents, such as paragraphs and tables, is like drawing on white paper.

  • Finally, close the "white paper" and the PDF will be generated.

Code Example

import ;
import ;
import ;
import ;
import ;
import ;

public class ITextPdfGenerator {
    public static void main(String[] args) {
        // Create a Document object, like preparing a piece of white paper        Document document = new Document();
        try {
            // Associate this "white paper" with a file output stream and specify the path of the generated PDF file            (document, new FileOutputStream("itext_example.pdf"));
            // Open this "white paper" and prepare to draw            ();
            // Add a paragraph on "white paper"            (new Paragraph("Hey, this is a PDF document generated using iText, isn't it amazing!"));
        } catch (DocumentException | FileNotFoundException e) {
            ();
        } finally {
            // Close the "white paper" and complete PDF generation            if (()) {
                ();
            }
        }
    }
}

Code explanation and instructions

  • First we created oneDocumentObject, it represents the entire PDF document, like a piece of white paper.

  • useMethodDocumentAssociated with a file output stream, the PDF file specified here is calleditext_example.pdf

  • Call()Open the "white paper" so that you can add content to it.

  • use(new Paragraph("..."))Adding a paragraph to the document is like writing a sentence on a blank paper.

  • Finally atfinallyCalled in block()Close the "white paper" to ensure that all resources are released correctly.

Maven dependencies

<dependency>
    <groupId></groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Generate PDF using the Apache PDFBox library

Ideas

  • First introduce the Apache PDFBox library, which is also a powerful tool for generating PDFs.

  • Create aPDDocumentObject, this object is like a PDF container.

  • Create aPDPageRepresent the page and add it toPDDocumentIt's like putting a piece of paper in a container.

  • GetPDPageContentStreamTo draw content is like picking up a pen to draw on paper.

  • Finally closedPDPageContentStreamandPDDocument, PDF will be generated.

Code Example

import ;
import ;
import ;
import .PDType1Font;

import ;

public class PdfBoxPdfGenerator {
    public static void main(String[] args) {
        // Creating a PDDocument object is like preparing a PDF container        PDDocument document = new PDDocument();
        try {
            // Create a page, like preparing a piece of paper            PDPage page = new PDPage();
            // Put this paper in a PDF container            (page);

            // Getting the page content stream is like picking up a pen to prepare to draw            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            // Set the font and font size, just like choosing the thickness and style of the brush            (PDType1Font.HELVETICA_BOLD, 12);
            // Start a new line and prepare to write            ();
            // Setting the text position is like determining the position of writing on paper            (100, 700);
            // Write text and write content on paper            ("Hey, this is a PDF document generated with Apache PDFBox, it's cool!");
            // End the text operation and finished writing            ();
            // Put down the pen and close the content stream            ();

            // Save this PDF document            ("pdfbox_example.pdf");
        } catch (IOException e) {
            ();
        } finally {
            // Close the PDF container and complete the operation            try {
                if (document != null) {
                    ();
                }
            } catch (IOException e) {
                ();
            }
        }
    }
}

Code explanation and instructions

  • CreatePDDocumentObject, which represents the entire PDF document, is like a container.

  • CreatePDPageRepresent a page, use(page)Adding pages to documents is like putting paper into a container.

  • usePDPageContentStreamCome to draw content on the page, throughsetFontMethod to set the font and font size,beginTextStart text operation,newLineAtOffsetSet the text location,showTextWrite text,endTextEnd the text operation.

  • Call()Close the content stream is like putting a pen down.

  • Last call("pdfbox_example.pdf")Save the document, infinallyClose in the blockPDDocument, close the container.

Maven dependencies

<dependency>
    <groupId></groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>

Hey, friend, now you know how to generate PDF documents in Java! Both libraries are very useful, you can choose according to your needs. Hurry up and try it!

Summarize

This is the end of this article about Java generating PDF documents. For more related contents of Java generating PDF documents, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • java
  • generate
  • pdf document

Related Articles

  • Deeply understand the object Object class in the JAVA basic class library

    The Object class is a special class and is the parent class of all classes. If a class does not explicitly indicate that it inherits from a certain class with extends, then it inherits the Object class by default. Here we mainly summarize two of the Object class: toString() and equals() methods
    2021-09-09
  • Example generation of dynamic routing loading pages using SpringBoot + Redis + Vue

    In modern web application development, dynamic routing loading can significantly improve the flexibility and security of the application. This article will conduct in-depth discussion on how to use Spring Boot, Redis, Element UI and Vue technology stack to achieve dynamic routing loading, and generate and verify valid links through Redis to achieve page access control. Friends who need it can refer to it
    2024-09-09
  • JAVA's practical guide to generate pdf files

    Recently, the project needs to implement the PDF download function. Since I don’t have this experience, it took me a long time to find relevant information from the Internet. The following article mainly introduces relevant information about JAVA generation of PDF files. The article introduces the example code in detail. Friends who need it can refer to it.
    2022-10-10
  • How to upload files to the server side of Java

    This article mainly introduces in detail the method of uploading files to the server side of Java, which has certain reference value. Interested friends can refer to it.
    2018-01-01
  • Comprehensive interpretation of the Profile configuration system in Spring Boot

    The configuration system is the basis for developing applications based on the Spring Boot framework, and automatic configuration is also one of the core functions of the framework. This article sorts out the relevant knowledge of the Profile configuration system in Spring Boot. Interested friends follow the editor to take a look.
    2021-05-05
  • Analysis of the usage of Mongodb management tools implemented by SpringBoot

    This article mainly introduces the use analysis of the Mongodb management tool implemented by SpringBoot. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.
    2019-09-09
  • Simple understanding of the nature of java generics (non-type erasure)

    Generics play a very important role in Java and are widely used in object-oriented programming and various design patterns. Generics are parametric types applications. The data types of operations are not limited to specific types. Different data types can be set according to actual needs to achieve code reuse. Let me briefly talk about generics
    2019-05-05
  • The very useful data structure in Java EnumSet

    This article mainly introduces the very useful data structure in Java EnumSet. EnumMap belongs to a map. The following details are covered around the topic. If you need it, please refer to it.
    2022-05-05
  • JavaCV implements the decimation of video in frames

    This article mainly introduces in detail to JavaCV to extract videos in frames. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2019-07-07
  • Completely understand Java multithreading (I)

    This article mainly introduces relevant materials about the multi-threading and high concurrency of Java interview questions. The article introduces the example code in detail, which has certain reference learning value for everyone to learn or use Java. If you need it, let’s learn together.
    2021-07-07

Latest Comments