记录一下利用freemarker 将html转换pdf的教程
pom.xml引入包
com.itextpdf
itextpdf
5.5.11
com.itextpdf.tool
xmlworker
5.5.11
org.xhtmlrenderer
flying-saucer-pdf
9.1.5
org.xhtmlrenderer
flying-saucer-pdf-itext5
9.1.5
com.itextpdf
itext-asian
5.2.0
org.freemarker
freemarker
2.3.19
解决中文不显示问题
package com.express.excms.enroll.config;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.baseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
public class AsianFontProvider extends XMLWorkerFontProvider {
@Override
public Font getFont(String fontname, String encoding, float size, final int style) {
try {
baseFont bfChinese =baseFont.createFont( "STSong-Light", "UniGB-UCS2-H", baseFont.EMBEDDED);
return new Font(bfChinese, size, style);
} catch (Exception e) {
e.printStackTrace();
}
return super.getFont(fontname, encoding, size, style);
}
}
html转pdf
package com.express.excms.enroll.utils;
import com.express.excms.enroll.config.AsianFontProvider;
import com.itextpdf.text.document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
@Slf4j
public class PDFUtils {
public static ByteArrayOutputStream htmlToPdf(String htmlContent) throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
document document = new document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, output);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter,document,new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8)),null, StandardCharsets.UTF_8,new AsianFontProvider());
document.close();
return output;
}
public static void htmlToPdf(String htmlContent,String filePath) throws Exception {
document document = new document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter,document,new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8)),null, StandardCharsets.UTF_8,new AsianFontProvider());
document.close();
}
}
freemarker 解析并获取生成的html
@Autowired
private Configuration configuration;
......省略
Configuration cfg = (Configuration) configuration.clone();
cfg.clearTemplateCache();
Template t = new Template(templateInDB.getName(), new StringReader(未渲染的html), configuration);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, 要渲染的数据);
try {
ByteArrayOutputStream byteArrayOutputStream = PDFUtils.htmlToPdf(html);
//获取pdf的base64
byte[] bytes = byteArrayOutputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return ResponseResult.defaultFailed(e.getMessage());
}
效果图



