table of content
Table Of Content

    Generating PDF From Template With Apache PDFBox

    Share

    Apache PDFBox is a widely-used open-source Java library highly regarded for its extensive capabilities in manipulating PDF files. This powerful tool provides developers with a range of functionalities, such as reading and writing PDFs, extracting text and images, managing fonts, accessing metadata, and encrypting and decrypting PDF files. With Apache PDFBox, developers can efficiently handle various tasks related to PDF document processing within their Java applications.

    I. Create Interactive or Fillable PDF Form

    First and foremost, we will clarify the distinction between interactive or fillable PDF forms and standard PDFs, highlighting key differences between them.

    1. Interactive or fillable PDF forms allow users to input data directly into the form fields within the PDF document. These forms typically include text fields, checkboxes, radio buttons, drop-down menus, and other interactive elements that enable users to enter information, make selections, and interact with the form electronically. Once the user fills out the form, they can save or print the completed document.
    2. Standard PDFs contain static content such as text, images, and graphics but does not include interactive form fields. Users cannot input data directly into a normal PDF document; instead, they can only view or print the content.

    So the next question pops up here, how can we create interactive or fillable PDF forms. Which provides user-friendly interface for designing and adding form fields to PDF documents. It allows you to easily create text fields, checkboxes, radio buttons, dropdown menus, and other interactive elements within your PDF forms.

    You can also consider checking out some other popular alternatives besides Adobe Acrobat for creating interactive or fillable PDF forms.

    • PDFescape
    • Nitro Pro
    • Foxit PhantomPDF
    • PDFelement
    • LibreOffice Draw

    Let us try using the PDFescape online website, which supports free PDF creation. Then, you can create a sample as described below:

    Next, click the `Download` button to obtain your modified interactive PDF forms, which you can then open using Foxit PDF Reader or web browser.

    In the following section, we will use the capabilities of Apache PDFBox to perform basic tasks such as writing to PDF files, reading PDF templates (including interactive or fillable PDFs), and dynamically populating data onto interactive PDF forms.

    II. Use Apache PDFBox to Generate PDF file

    First, install and set up Maven on your local machine. Maven allows us to generate Java projects easily and run commands to install dependencies from `pom.xml` file. After installing Maven successfully, proceed to check the version of the tool.

    mvn -v
    

    Creating new Java project using Maven involves running the following command in your terminal or command prompt:

    mvn archetype:generate -DgroupId=com.app.flagtick -DartifactId=samplepdfproj -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    

    Then, update the `maven.compiler.source` and `maven.compiler.target` properties to version that is supported by your JDK installation. For example:

    » pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.app.flagtick</groupId>
      <artifactId>samplepdfproj</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>samplepdfproj</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
      <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
    </project>
    

    Update the `pom.xml` file to include all dependencies needed for using Apache PDFBox.

    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.29</version>
    </dependency>
    

    Note: Run `mvn clean install` to clean and install these dependencies. Besides, use IntelliJ IDEA to reload the project by navigating to Maven » Reload Project.

    Here is a breakdown of the structure in the `com.app.flagtick` package for implementing PDF service.

    ~/sourcecode/
        |--- com/
            |--- app/
                |--- flagtick/
                    |--- App.java
                    |--- exception/
                    |------- PDFGenerationException.java
                    |--- services/
                        |--- PDFService.java
                        |--- impl/
                                PDFServiceImpl.java
    

    » PDFService.java

    package com.app.flagtick.services;
    
    import com.app.flagtick.exception.PDFGenerationException;
    
    public interface PDFService {
        void generatePDF(String filename, String text) throws PDFGenerationException;
    }
    

    » PDFServiceImpl.java

    package com.app.flagtick.services.impl;
    
    import com.app.flagtick.exception.PDFGenerationException;
    import com.app.flagtick.services.PDFService;
    import org.apache.pdfbox.pdmodel.PDDocument;
    import org.apache.pdfbox.pdmodel.PDPage;
    import org.apache.pdfbox.pdmodel.PDPageContentStream;
    import org.apache.pdfbox.pdmodel.font.PDType1Font;
    
    import java.io.IOException;
    
    public class PDFServiceImpl implements PDFService {
    
        @Override
        public void generatePDF(String filename, String text) throws PDFGenerationException {
            try {
                PDDocument document = new PDDocument();
                PDPage page = new PDPage();
                document.addPage(page);
    
                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
                contentStream.beginText();
                contentStream.newLineAtOffset(100, 700);
                contentStream.showText(text);
                contentStream.endText();
                contentStream.close();
    
                document.save(filename);
                document.close();
    
                System.out.println("PDF generated successfully.");
            } catch (IOException e) {
                throw new PDFGenerationException("Failed to generate PDF", e);
            }
        }
    }
    

    » App.java

    public class App 
    {
        private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
    
        public static void main( String[] args )
        {
            PDFService pdfService = new PDFServiceImpl();
            try {
                pdfService.generatePDF("generated_sample.pdf", "Hello, World");
            } catch (PDFGenerationException e) {
                LOGGER.error("Failed to generate PDF", e);
            }
        }
    }
    

    Visit this link to see additional code that supports appending dynamic data into interactive or fillable PDF templates.


    Flagtick Group
    Flagtick Group The individual is sociable and enjoys making friends, often sharing knowledge across various fields. |1 second ago
    Flagtick Group The individual is sociable and enjoys making friends, often sharing knowledge across various fields. 1 second ago
    You need to login to do this manipulation!