Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Generate PDF Documents from HTML Content in Java with FreeMarker and Flying Saucer

Tech May 12 24
package com.example.reporting.service;

import com.itextpdf.text.pdf.BaseFont;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HtmlToPdfConverter {

    private static final String FONT_FILENAME = "simhei.ttf";
    private static final String CHARSET = "UTF-8";
    public static final String STORAGE_DIRECTORY = "/opt/reporting/templates/";

    public static void convertHtmlTemplateToPdf(String rawTemplate, Map<String, Object> contextVariables, File outputPdfFile) {
        FileOutputStream fileOut = null;
        ITextRenderer pdfRenderer = new ITextRenderer();
        try {
            Configuration freemarkerConfig = new Configuration(Configuration.VERSION_2_3_31);
            StringTemplateLoader stringLoader = new StringTemplateLoader();
            stringLoader.putTemplate("reportTemplate", rawTemplate);
            freemarkerConfig.setTemplateLoader(stringLoader);
            freemarkerConfig.setDefaultEncoding(CHARSET);
            Template loadedTemplate = freemarkerConfig.getTemplate("reportTemplate");
            String renderedHtml = FreeMarkerTemplateUtils.processTemplateIntoString(loadedTemplate, contextVariables);
            fileOut = new FileOutputStream(outputPdfFile);
            ITextFontResolver fontHandler = pdfRenderer.getFontResolver();
            fontHandler.addFont(STORAGE_DIRECTORY + FONT_FILENAME, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            pdfRenderer.setDocumentFromString(renderedHtml);
            pdfRenderer.layout();
            pdfRenderer.createPDF(fileOut);
        } catch (Exception ex) {
            log.error("PDF conversion failed", ex);
        } finally {
            pdfRenderer.finishPDF();
            IOUtils.closeQuietly(fileOut);
        }
    }

    public static void main(String[] args) {
        Map<String, Object> reportContext = new HashMap<>(100);
        reportContext.put("invoiceTitle", "增值税普通发票");
        reportContext.put("transactionId", "TXN-789012");
        reportContext.put("orderId", "ORD-789012");
        reportContext.put("issueDate", "2024-10-05");
        reportContext.put("shipDate", "2024-10-05");
        reportContext.put("clientReference", "EXT-REF-789012");
        String pdfName = "invoice_export_" + System.currentTimeMillis() + ".pdf";
        String htmlTemplateInput = "";
        convertHtmlTemplateToPdf(htmlTemplateInput, reportContext, new File(STORAGE_DIRECTORY + pdfName));
        System.out.println("Generated PDF size (bytes): " + new File(STORAGE_DIRECTORY + pdfName).length());
    }
}

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.