当前位置: 首页 > news >正文

(最新)itext7 freemarker动态模板转pdf

1.引入依赖

<!--PDF导出POM-->
<dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>8.0.3</version><type>pom</type>
</dependency>
<dependency><groupId>com.itextpdf</groupId><artifactId>html2pdf</artifactId><version>5.0.3</version>
</dependency>
<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version>
</dependency>

2.编写FTL文件

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title></title>
</head><style>.pic {width: 100%;height: 100%;}
</style><body>
<div id="app"><#--封面图--><#if show><img class="pic" src="${coverImageFile!''}"/></#if>
</div>
</body>
</html>

3.后台代码

@Resource
Configuration configuration;
/*** 导出*/@Overridepublic void export(HttpServletResponse response){//获取文件byte[]byte[] pdfBytes=getPdfBytes();try{//输出pdf文件String chineseName="中文文件名";response.setCharacterEncoding("utf-8");String fileName=URLEncoder.encode(chineseName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".pdf");//设置响应头(导出为pdf文件)response.setContentType("application/pdf");//设置响应头(返回流给前端预览使用)//response.setContentType("application/octet-stream;charset=UTF-8");// 获取HttpServletResponse的OutputStreamOutputStream os=response.getOutputStream();// 写入字节流数组os.write(pdfBytes);os.flush();os.close();}catch(IOException e){throw new InvalidCmdException(e.getMessage());}}
private byte[] getPdfBytes(){//获取模板替换数据Map<String, Object> map=new HashMap<>();map.put("show", true);map.put("coverImageFile", "base64图片");try{//读取freemarker模板Template template=configuration.getTemplate("FTL文件路径");StringWriter out=new StringWriter();// 将数据模型合并到模板中生成HTMLtemplate.process(map, out);String htmlContent=out.toString();// 初始化字节输出流用于保存PDFByteArrayOutputStream pdfOutput=new ByteArrayOutputStream();// 设置中文字体ConverterProperties converterProperties=new ConverterProperties();FontProvider fontProvider=new DefaultFontProvider(true, true, false);PdfDocument pdfDoc;FontProgram fontProgram=FontProgramFactory.createFont("static/simhei.ttf");// 添加中文字体到字体提供者fontProvider.addFont(fontProgram);converterProperties.setFontProvider(fontProvider);// 转换HTML到PDFtry(ByteArrayOutputStream outputStream=pdfOutput){// 初始化文档PdfWriter writer=new PdfWriter(outputStream);pdfDoc=new PdfDocument(writer);//设置pdf纸张大小pdfDoc.setDefaultPageSize(PageSize.A4);// 将HTML转换为PDFHtmlConverter.convertToPdf(htmlContent, pdfDoc, converterProperties);}// 从字节输出流中获取PDF的字节数组byte[] pdfBytes=pdfOutput.toByteArray();// 关闭流pdfOutput.close();pdfDoc.close();out.close();return pdfBytes;}catch(IOException e){throw new InvalidCmdException("读取候选人freemarker模板错误");}catch(TemplateException e){throw new InvalidCmdException("替换模板值错误");}}

4.注意事项

itext7本身不支持中文 所以需要在项目中引入字体文件。

freemarker图片需要使用base64格式图片

byte[] 数组转base64

 /*** 图片转base64*/private String convertBase64(String ossFileId){if(String2Utils.isNotBlank(ossFileId)){//这里使用的是阿里的oss查询OssUrlDto ossUrlDto=ossFileService.findDfsById(ossFileId).orElse(null);try{byte[] adviserBytes=ossClientService.getContentByteByKey(ossUrlDto.getBucketName(), ossUrlDto.getPath());return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(adviserBytes);}catch(Exception e){throw new InvalidCmdException("图片转base64失败");}}return "";}

给导出的PDF设置页面边距,网上搜索了很多中办法,只有一种成功了

再FTL页面中添加

<style>@page {size: A4;margin: 10mm;}
</style>

http://www.lryc.cn/news/338910.html

相关文章:

  • solidworks electrical 2D和3D有什么区别
  • 4.2、ipex-llm(原bigdl-llm)进行语音识别
  • 上海亚商投顾:创业板指低开低走 黄金、家电股逆势大涨
  • AIGC革新浪潮:大语言模型如何优化企业运营
  • Golang基础-12
  • python递归统计文件夹下pdf文件的数量
  • Kafka 硬件和操作系统
  • Kolla-ansible部署OpenStack集群
  • SHARE 203S PRO:倾斜摄影相机在地灾救援中的应用
  • MATLAB算法实战应用案例精讲-【数模应用】中介效应分析(补充篇)(附R语言和python代码实现)
  • Day96:云上攻防-云原生篇Docker安全系统内核版本漏洞CDK自动利用容器逃逸
  • python botos s3 aws
  • python画神经网络图
  • Bash 编程精粹:从新手到高手的全面指南之逻辑控制
  • 自动化运维(三十)Ansible 实战之自定义插件
  • 实习僧网站的实习岗位信息分析
  • C语言中局部变量和全局变量是否可以重名?为什么?
  • 小程序中配置scss
  • ZYNQ-Vitis(SDK)裸机开发之(四)PS端MIO和EMIO的使用
  • 聊聊jvm中内存模型的坑
  • DevOps已死?2024年的DevOps将如何发展
  • appium控制手机一直从下往上滑动
  • 为什么光伏探勘测绘需要无人机?
  • day10 | 栈与队列 part-2 (Go) | 20 有效的括号、1047 删除字符串中的所有相邻重复项、150 逆波兰表达式求值
  • 深入解析Tomcat的工作流程
  • 【web网页制作】html+css旅游家乡山西主题网页制作(3页面)【附源码】
  • 系统参数指标:QPS、TPS、PV、UV等
  • 一入鸿蒙深似海,从此Spring是路人:鸿蒙开发面试题
  • 【Python】使用OPC UA创建数据服务器
  • JavaScript(六)-高级篇