DEV Community

lu liu
lu liu

Posted on

Create PDF from Template in Java

In modern Java web applications, dynamic PDF generation for reports and invoices faces challenges from rigid libraries amid no-code trends demanding flexible templating. Developers struggle with layout consistency and data integration. Spire.PDF for Java provides an efficient solution for creating PDFs from templates in Java with high fidelity.

This tutorial details installation, HTML to PDF Java conversion from templates, and PDF template Java filling. Reproducible steps enable scalable workflows.

Introducing Spire.PDF for Java and Installation

Spire.PDF for Java handles creating PDFs from templates in Java via HTML to PDF Java conversion, form fields, text replacement, and templates without watermarks in licensed versions. It supports CSS3, images, JavaScript, and JDK 8+, fitting modern apps needing dynamic reports.

Key features include precise rendering, no external dependencies, and API for placeholders.

Prerequisites

  • JDK 8 or higher
  • Build tool (Maven/Gradle) or JAR

Installation Steps

  1. Maven: Add to pom.xml:
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>12.2.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode
  1. JAR Download: Get from the official site, and add spire.pdf.jar and libs to the classpath.

Creating PDF from HTML Template

HTML to PDF Java suits dynamic PDF creation from templates in Java, ideal for invoices with data-driven placeholders. Addresses pain points like CSS styling in web apps transitioning from no-code tools.

Steps

  1. Prepare HTML Template
  2. Load and Replace Placeholders
  3. Convert to PDF
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.LoadHtmlType;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class GeneratePdfFromHtmlTemplate {

    public static void main(String[] args) throws Exception {

        // Path to the HTML template file
        String htmlFilePath = "template/invoice_template.html";

        // Read HTML content from file
        String htmlTemplate = new String(Files.readAllBytes(Paths.get(htmlFilePath)));

        // Sample data for invoice
        Map invoiceData = new HashMap<>();
        invoiceData.put("INVOICE_NUMBER", "12345");
        invoiceData.put("INVOICE_DATE", "2025-08-25");
        invoiceData.put("BILLER_NAME", "John Doe");
        invoiceData.put("BILLER_ADDRESS", "123 Main St, Anytown, USA");
        invoiceData.put("BILLER_EMAIL", "johndoe@example.com");
        invoiceData.put("ITEM_DESCRIPTION", "Consulting Services");
        invoiceData.put("ITEM_QUANTITY", "10");
        invoiceData.put("ITEM_UNIT_PRICE", "$100");
        invoiceData.put("ITEM_TOTAL", "$1000");
        invoiceData.put("SUBTOTAL", "$1000");
        invoiceData.put("TAX_RATE", "5");
        invoiceData.put("TAX", "$50");
        invoiceData.put("TOTAL", "$1050");

        // Replace placeholders with actual values
        String populatedHtml = populateTemplate(htmlTemplate, invoiceData);

        // Output PDF file
        String outputFile = "output/Invoice.pdf";

        // Set the QT plugin path for HTML conversion
        HtmlConverter.setPluginPath("C:\\plugins-windows-x64\\plugins");

        // Convert HTML string to PDF
        HtmlConverter.convert(
                populatedHtml,
                outputFile,
                true,                       // Enable JavaScript
                100000,                     // Timeout (ms)
                new Size(595, 842),         // A4 size
                new PdfMargins(20),         // Margins
                LoadHtmlType.Source_Code    // Load HTML from string
        );

        System.out.println("PDF generated successfully: " + outputFile);
    }

    /**
     * Replace placeholders in HTML template with actual values.
     */
    private static String populateTemplate(String template, Map data) {
        String result = template;
        for (Map.Entry entry : data.entrySet()) {
            result = result.replace("{{" + entry.getKey() + "}}", entry.getValue());
        }
        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Tips:

  • Embed images as base64 for portability.
  • CSS: Full support for flex/grid; limit animations.
  • Scale for reports: Loop data into HTML tables.

This yields professional PDFs from responsive templates.

Creating PDF from PDF Template

PDF template Java offers exact fidelity for forms like contracts, outperforming HTML to PDF Java in positioning. Solves enterprise pain points with AcroForms and text edits.

Steps

  1. Load Template
  2. Fill Forms and Replace Text
  3. Add/Edit Fields if Needed
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

public class GeneratePdfFromPdfTemplate {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Template.pdf");

        // Create a PdfTextReplaceOptions object and specify the options
        PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));

        // Get a specific page
        PdfPageBase page = doc.getPages().get(0);

        // Create a PdfTextReplacer object based on the page
        PdfTextReplacer textReplacer = new PdfTextReplacer(page);
        textReplacer.setOptions(textReplaceOptions);

        // Dictionary for old and new strings
        Map<String, String> replacements = new HashMap<>();
        replacements.put("{PROJECT_NAME}", "New Website Development");
        replacements.put("{PROJECT_NO}", "2023-001");
        replacements.put("{PROJECT MANAGER}", "Alice Johnson");
        replacements.put("{PERIOD}", "Q3 2023");
        replacements.put("{PERIOD}", "Q3 2023");
        replacements.put("{START_DATE}", "Jul 1, 2023");
        replacements.put("{END_DATE}", "Sep 30, 2023");

        // Loop through the dictionary to replace text
        for (Map.Entry<String, String> pair : replacements.entrySet()) {
            textReplacer.replaceText(pair.getKey(), pair.getValue());
        }

        // Save the document to a different PDF file
        doc.saveToFile("output/FromPdfTemplate.pdf");
        doc.dispose();
    }
}

Enter fullscreen mode Exit fullscreen mode

Edge Cases:

  • Fonts: PdfTrueTypeFont font = new PdfTrueTypeFont(...);
  • Positioning: Use Rectangle2D.Float(x,y,w,h).
  • Multi-page: Iterate doc.getPages().

Enables precise dynamic generation.

Conclusion

Spire.PDF for Java streamlines create PDF from template in Java through HTML to PDF Java for flexibility and PDF template Java for accuracy. Install via Maven, replace placeholders in HTML or fill PDF forms/text.

Addresses current needs for scalable PDFs in Java apps. Implement these steps in your project today.

Top comments (0)