共计 7668 个字符,预计需要花费 20 分钟才能阅读完成。
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 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 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.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, len);
}
fileInputStream.close();
outputStream.flush();
outputStream.close();} catch (Exception e) {log.error("生成 PDF 失败", e);
} finally {
// 清理文件
file.delete();}
}
public static void exportZip(String templateContent, List
2. 工具类(浏览器预览)
public class FreemarkerReportWriter {
/**
* 字体文件名称
*/
private final static String DEFAULT_FONT_PATH = "fonts/simsun.ttf";
private final static String DEFAULT_FONT = "SimSun";
private final static String DEFAULT_PDF = ".pdf";
private final static String TEMPLATE_NAME = "myTemplate";
/**
* fileName 文件名称
* templateContent ftl 模版内容
* data ftl 模版数据
* attachment 是否以下载附件的方式查看报表,否则以在线方式查看报表
* response HttpServletResponse
*/
public static void exportPdf(String fileName, String templateContent, Map data, boolean attachment, HttpServletResponse response) {Assert.hasLength(fileName, "The parameter `fileName` can not be empty.");
Assert.hasLength(templateContent, "The parameter `templateContent` can not be empty.");
if (!fileName.toLowerCase().endsWith(DEFAULT_PDF)) {fileName += ".pdf";}
ServletOutputStream outputStream = null;
// 设置响应头
response.setContentType("application/pdf");
MimeDispositionType mimeDispositionType = attachment ? MimeDispositionType.attachment : MimeDispositionType.inline;
response.setHeader("Content-Disposition", FileUtil.getContentDisposition(fileName, mimeDispositionType));
try {byte[] bytes = createPdf(templateContent, data);
log.debug("pdf file length:{}", bytes.length);
outputStream = response.getOutputStream();
outputStream.write(bytes);
} catch (Exception e) {log.error("create pdf file failed:", e);
} finally {IoUtil.close(outputStream);
}
}
/**
* templateContent ftl 模版内容
* mapList ftl 模版数据
* response HttpServletResponse
*/
public static void exportZip(String templateContent, List
3.controller 接口
@GetMapping("/exportPdf")
@ApiOperation("导出 PDF")
public UnifyResponse exportPdf(@RequestParam("principalId") String principalId, HttpServletResponse response) {PrincipalInstrumentVO instrumentVO = principalInstrumentService.detail(principalId);
if (BeanUtil.isNotEmpty(instrumentVO)) {
// 设置响应头
response.setContentType("application/pdf");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "inline; filename="pdf.pdf"");
PdfExportUtil.exportPdf(instrumentVO.getHtmlContent(), new HashMap(8), response);
}
return null;
}
@GetMapping("/exportZip")
@ApiOperation("导出 ZIP")
public UnifyResponse exportZip(@RequestParam("principalId") String principalId, HttpServletResponse response) {List
4. 说明
templateContent 为 FreeMarker 模板的 HTML 内容
原文地址: HTML 生成下载 PDF 文件或 ZIP 压缩包文件
正文完