package com.yqboots.web.thymeleaf.support;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.file.Path;
import java.util.Map;

import com.lowagie.text.pdf.BaseFont;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

@Component
public class Html2PdfGenerator {
	@Autowired
	private TemplateEngine templateEngine;

	public void generate(String template, Map<String, Object> variables, Path output) throws Exception {
		try (StringWriter writer = new StringWriter();
		     BufferedWriter bw = new BufferedWriter(writer)) {
			// get context
			Context ctx = new Context();
			ctx.setVariables(variables);
			templateEngine.process(template, ctx, bw);

			// output html
			bw.flush();
			writer.flush();

			toPDF(writer.toString(), output);
		}
	}

	private void toPDF(String inputHtml, Path output) throws Exception {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(inputHtml.getBytes("UTF-8")));
		ITextRenderer renderer = new ITextRenderer();

		ITextFontResolver fontResolver = renderer.getFontResolver();
		fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		fontResolver.addFont("C:/Windows/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

		renderer.setDocument(doc, null);
		renderer.layout();
		renderer.createPDF(new FileOutputStream(output.toString()));
	}
}

@@ -1803,11 +1803,824 @@
 );%0D%0A%09%7D%0D%0A
+%09%0D%0A%09private void toPDF(String inputHtmls%5B%5D, Path output) throws Exception %7B%0D%0A%09%09DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();%0D%0A%09%09ITextRenderer renderer = new ITextRenderer();%0D%0A%0D%0A%09%09ITextFontResolver fontResolver = renderer.getFontResolver();%0D%0A%09%09fontResolver.addFont(%22C:/Windows/Fonts/simsun.ttc%22, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);%0D%0A%09%09fontResolver.addFont(%22C:/Windows/Fonts/simhei.ttf%22, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);%0D%0A%09%09%0D%0A%09%09renderer.createPDF(new FileOutputStream(output.toString()));%0D%0A%09%09for(int i=1; i%3C inputHtmls.length; i++) %7B%0D%0A%09%09%09Document doc = builder.parse(new ByteArrayInputStream(inputHtml%5Bi%5D.getBytes(%22UTF-8%22)));%0D%0A%09%09%09renderer.setDocument(doc, null);%0D%0A%09%09%09renderer.layout();%0D%0A%09%09%09renderer.writeNextDocument();%0D%0A%09%09%7D%0D%0A%09%09renderer.finishPDF();%0D%0A%09%7D%0D%0A
 %7D%0D%0A

Update Html2PdfGenerator.java