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 2
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

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

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...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

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