Generate PDFs from Templates in Java (HTML-to-PDF Explained)

Java Generate PDFs from Templates

In many Java applications, you’ll need to generate PDF documents dynamically — for example, invoices, reports, or certificates. Creating PDFs from scratch can be time-consuming and error-prone, especially with complex layouts or changing content. Using templates with placeholders that are replaced at runtime is a more maintainable and flexible approach, ensuring consistent styling while separating layout from data.

In this article, we’ll explore how to generate PDFs from templates in Java using Spire.PDF for Java, including practical examples for both HTML and PDF templates. We’ll also highlight best practices, common challenges, and tips for creating professional, data-driven PDFs efficiently.

Table of Contents

Why Use Templates for PDF Generation

  • Maintainability : Designers or non-developers can edit templates (HTML, PDF, or Word) without touching code.
  • Separation of concerns : Your business logic is decoupled from document layout.
  • Consistency : Templates enforce consistent styling, branding, and layout across all generated documents.
  • Flexibility : You can switch or update templates without major code changes.

Choosing the Right Template Format (HTML, PDF, or Word)

Each template format has strengths and trade-offs. Understanding them helps you pick the best one for your use case.

Template Format Pros Cons / Considerations Ideal Use Cases
HTML Full control over layout via CSS, tables, responsive design; easy to iterate Needs an HTML-to-PDF conversion engine (e.g. Qt WebEngine, headless Chrome) Invoices, reports, documents with variable-length content, tables, images
PDF You can take an existing branded PDF and replace placeholders Only supports simple inline text replacements (no reflow for multiline content) Templates with fixed layout and limited dynamic fields (e.g. contracts, certificates)
Word (DOCX) Familiar to non-developers; supports rich editing Requires library (like Spire.Doc) to replace placeholders and convert to PDF Organizations with existing Word-based templates or documents maintained by non-technical staff

In practice, for documents with rich layout and dynamic content, HTML templates are often the best choice. For documents where layout must be rigid and placeholders are few, PDF templates can suffice. And if your stakeholders prefer Word-based templates, converting from Word to PDF may be the most comfortable workflow.

Setting Up the Environment

Before you begin coding, set up your project for Spire.PDF (and possibly Spire.Doc) usage:

  1. Download / add dependency
  2. To get started, download Spire.PDF for Java from our website and add the JAR files to your project's build path. If you’re using Maven, include the following dependency in your 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>11.10.3</version>
        </dependency>
    </dependencies>
    
  3. (If using HTML templates) Install HTML-to-PDF engine / plugin

    Spire.PDF needs an external engine or plugin (e.g. Qt WebEngine or a headless Chrome /Chromium) to render HTML + CSS to PDF.

    • Download the appropriate plugin for your platform (Windows x86, Windows x64, Linux, macOS).
    • Unzip to a local folder and locate the plugins directory, e.g.: C:\plugins-windows-x64\plugins
    • Configure the plugin path in code:
  4. HtmlConverter.setPluginPath("C:\\plugins-windows-x64\\plugins");
    
  5. Prepare your templates
  • For HTML: define placeholders (e.g. {{PLACEHOLDER}}) in your template HTML / CSS.
  • For PDF: build or procure a base PDF that includes placeholder text (e.g. {PROJECT_NAME}) in the spots you want replaced.

Generating PDFs from Templates in Java

From an HTML Template

Here’s how you can use Spire.PDF to convert an HTML template into a PDF document, replacing placeholders with actual data.

Sample Code (HTML → 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;
    }
}

How it work:

  1. Design an HTML file using CSS, tables, images, etc., with placeholders (e.g. {{NAME}}).
  2. Store data values in a Map<String, String>.
  3. Replace placeholders with actual values at runtime.
  4. Use HtmlConverter.convert to generate a styled PDF.

This approach works well when your content may grow or shrink (tables, paragraphs), because HTML rendering handles flow and wrapping.

Output:

Generate PDF from HTML template in Java

From a PDF Template

If you already have a branded PDF template with placeholder text, you can open it and replace inline text within.

Sample Code (PDF placeholder replacement)

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();
    }
}

How it works:

  1. Load an existing PDF template .
  2. Use PdfTextReplacer to find and replace placeholder text.
  3. Save the updated file as a new PDF.

This method works only for inline, simple text replacement . It does not reflow or adjust layout if the replacement text is longer or shorter.

Output:

Generate PDF files based on a PDF template

Best Practices for Template-Based PDF Generation

Here are some tips and guidelines to ensure reliability, maintainability, and quality of your generated PDFs:

  • Use HTML templates for rich content : If your document includes tables, variable-length sections, images, or requires responsive layouts, HTML templates offer more flexibility.
  • Use PDF templates for stable, fixed layouts : When your document layout is tightly controlled and only a few placeholders change, PDF templates can save you the effort of converting HTML.
  • Support Word templates if your team relies on them : If your design team uses Word, use Spire.Doc for Java to replace placeholders in DOCX and export to PDF.
  • Unique placeholder markers : Use distinct delimiters (e.g. {FIELD_NAME}, or {FIELD_DATE}) to avoid accidental partial replacements.
  • Keep templates external and versioned : Don’t embed template strings in code. Store them in resource files or external directories.
  • Test with real data sets : Use realistic data to validate layout — e.g. long names, large tables, multilingual text.

Final Thoughts

Generating PDFs from templates is a powerful, maintainable approach — especially in Java applications. Depending on your needs:

  • Use HTML templates when you require dynamic layout, variable-length content, and rich styling.
  • Use PDF templates when your layout is fixed and you only need to swap a few fields.
  • Leverage Word templates (via Spire.Doc) if your team already operates in that environment.

By combining a clean template system with Spire.PDF (and optionally Spire.Doc), you can produce high-quality, data-driven PDFs in a maintainable, scalable way.

FAQs

Q1. Can I use Word templates (DOCX) in Java for PDF generation?

Yes. Use Spire.Doc for Java to load a Word document, replace placeholders, and export to PDF. This workflow is convenient if your organization already maintains templates in Word.

Q2. Can I insert images or charts into templates?

Yes. Whether you generate PDFs from HTML templates or modify PDF templates, you can embed images, charts, shapes, etc. Just ensure your placeholders or template structure allow space for them.

Q3. Why do I need Qt WebEngine or Chrome for HTML-to-PDF conversion?

The HTML-to-PDF conversion must render CSS, fonts, and layout precisely. Spire.PDF delegates the heavy lifting to an external engine (e.g. Qt WebEngine or Chrome). Without a plugin, styles may not render correctly.

Q4. Does Spire.PDF support multiple languages / international text in templates?

Yes. Spire.PDF supports Unicode and can render multilingual content (English, Chinese, Arabic, etc.) without losing formatting.

Get a Free License

To fully experience the capabilities of Spire.PDF for Java without any evaluation limitations, you can request a free 30-day trial license.