1.工具类(下载到本地)
public class FreemarkerReportWriter {
/**
* 字体文件名称
*/
private final static String DEFAULT_FONT = "yahei.ttf";
/**
* templateContent ftl模版内容
* data ftl模版数据
* file 下载本地PDF文件
* classPath 文件路径
*/
public static void createPdf(String templateContent, Map<String, Object> data, File file, String classPath) {
FileOutputStream outputStream = null;
ITextRenderer renderer = new ITextRenderer();
try {
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate("myTemplate", templateContent);
cfg.setTemplateLoader(stringLoader);
Template template = cfg.getTemplate("myTemplate", "utf-8");
String htmlData = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
outputStream = new FileOutputStream(file);
ITextFontResolver fontResolver = renderer.getFontResolver();
// 解决中文乱码问题,fontPath为中文字体地址
fontResolver.addFont(classPath + DEFAULT_FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.setDocumentFromString(htmlData);
renderer.layout();
renderer.createPDF(outputStream);
} catch (Exception e) {
log.error("生成失败", e);
} finally {
renderer.finishPDF();
IOUtils.closeQuietly(outputStream);
}
}
public static void exportPdf(String templateContent, Map<String, Object> data, HttpServletResponse response) {
File file = null;
try {
String classPath = PdfExportUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
log.info("classPath路径:{}", classPath);
String fileName = System.currentTimeMillis() + ".pdf";
createPdf(templateContent, data, new File(classPath + fileName), classPath);
log.info("pdf长度:{}", new File(classPath + fileName).length());
file = new File(classPath + fileName);
ServletOutputStream outputStream = response.getOutputStrea