前言:生成pdf有很多种方法,本文使用itextpdf 7 生成

1、根据PDF的需求分为静态数据动态数据以及特殊数据

1).静态数据是数据固定,所以我们采用模板的方式进行生成-----itextpdf + Adobe Acrobat DC 填充模板生成

Adobe Acrobat DC可以在网上下载绿色版

(1).先将文件通过WPS生成PDF文件

(2).用Adobe Acrobat DC打开文件进行准备表单

(3).配置好对应字段的表单域

(4).传入数据进行打印

2).动态数据是数据不固定的,需要采用代码生成的方式进行---itext 7API 的官方地址iText 7 7.1.5 API

(1).添加依赖

<dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>7.1.5</version><type>pom</type>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>kernel</artifactId><version>7.1.5</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>io</artifactId><version>7.1.5</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>layout</artifactId><version>7.1.5</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>forms</artifactId><version>7.1.5</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>pdfa</artifactId><version>7.1.5</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>sign</artifactId><version>7.1.5</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>barcodes</artifactId><version>7.1.5</version>
</dependency>
<dependency><groupId>com.itextpdf</groupId><artifactId>hyph</artifactId><version>7.1.5</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>font-asian</artifactId><version>7.1.5</version>
</dependency>

最后附上是我写好的第一版万能打印模板

Util工具类

/*** @author f* @date 2021/9/28 16:56*/
public class PrintUtil {/*** 中文字体** @return* @throws IOException*/public static PdfFont typeface() throws IOException {return PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);}/*** 模板数据** @param map formFields*/public static void templateData(Map<String, String> map, Map<String, PdfFormField> formFields) throws IOException {for (Map.Entry<String, String> entry : map.entrySet()) {PdfFormField agreementId = formFields.get(entry.getKey());if (agreementId != null) {agreementId.setFont(typeface()).setFontSize(14);agreementId.setValue(String.valueOf(entry.getValue()));}}}/*** 模板数据集合** @param list formFields*/public static void templateDatas(List<Map<String, String>> list, Map<String, PdfFormField> formFields) throws IOException {int i = 0;for (Map<String, String> map : list) {i++;for (Map.Entry<String, String> entry : map.entrySet()) {PdfFormField agerrmentId = formFields.get(entry.getKey() + "_" + i);if (agerrmentId != null) {agerrmentId.setFont(typeface()).setFontSize(14);agerrmentId.setValue(String.valueOf(entry.getValue()));}}}}/*** 需要翻译好字段 与模板配置完成的相匹配** @param estimate formFields*/public static void estimate(Map<String, String> estimate, Map<String, PdfFormField> formFields) throws IOException {for (Map.Entry<String, String> entry : estimate.entrySet()) {PdfFormField agerrmentId1 = formFields.get(entry.getValue());if (StringUtils.isNotBlank(entry.getValue()) && agerrmentId1 != null) {agerrmentId1.setFont(typeface()).setFontSize(14);agerrmentId1.setValue("√");}}}/*** 表单标题** @param header* @throws IOException*/public static Paragraph header(String header) throws IOException {return new Paragraph(header)//设置字体.setFont(typeface())//设置字体大小.setFontSize(20)//字体加粗.setBold()//设置水平居中.setTextAlignment(TextAlignment.CENTER)//行高.setFixedLeading(80);}/*** 表单数据** @return* @throws IOException*/public static Table table(List<Map<String, String>> map, Map<String, String> biaotou) throws IOException {//4.创建一个 Table 对象int size = biaotou.entrySet().size();UnitValue[] percentArray = UnitValue.createPercentArray(size);Table table = new Table(percentArray).setFont(typeface())//垂直居中.setVerticalAlignment(VerticalAlignment.MIDDLE)//水平居中.setTextAlignment(TextAlignment.CENTER).setFontSize(18)//自动布局.setAutoLayout()//动态列表超出表的宽度 使用固定布局
//                .setFixedLayout()//100%.useAllAvailableWidth();//表头for (Map.Entry<String, String> entry : biaotou.entrySet()) {table.addCell(entry.getValue());}for (Map<String, String> map1 : map) {for (Map.Entry<String, String> entry : map1.entrySet()) {table.addCell(entry.getValue());}}return table;}/*** 返回文件流** @param newPDFPath* @param response* @throws IOException*/public static void file(String newPDFPath, HttpServletResponse response) throws IOException {//读取路径下面的文件File file = new File(newPDFPath);//读取指定路径下面的文件InputStream in = new FileInputStream(file);response.setContentType("application/pdf");OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());//创建存放文件内容的数组byte[] buff = new byte[1024];//所读取的内容使用n来接收int n;//当没有读取完时,继续读取,循环while ((n = in.read(buff)) != -1) {//将字节数组的数据全部写入到输出流中outputStream.write(buff, 0, n);}if ((n = in.read(buff)) == -1) {//强制将缓存区的数据进行输出outputStream.flush();//关流outputStream.close();in.close();}}
}

实体类

/*** pdf模板视图实体类** @author f* @since 2021-09-17*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "PrintVO对象", description = "pdf模板")
public class PrintVO extends Print {private static final long serialVersionUID = -5917961640607855978L;@ApiModelProperty(value = "模板数据")private Map<String, String> map;@ApiModelProperty(value = "模板数据集合")private List<Map<String, String>> list;@ApiModelProperty(value = "特殊数据")private Map<String, String> estimate;@ApiModelProperty(value = "表题")private String header;@ApiModelProperty(value = "表单表头")private Map<String, String> biaotou;@ApiModelProperty(value = "表单数据")private List<Map<String, String>> table;@ApiModelProperty(value = "表题1")private String header1;@ApiModelProperty(value = "表单表头")private Map<String, String> biaotou1;@ApiModelProperty(value = "表单数据")private List<Map<String, String>> table1;}

controller层

/*** 打印*/
@PostMapping("/template")
@ApiOperationSupport(order = 9)
@ApiOperation(value = "打印", notes = "PDF模板")
public void template(@RequestBody PrintVO print, HttpServletResponse response, @RequestParam String id) {printService.template(print, response, id);
}

service层

/*** PDF模板 服务实现类** @author f* @since 2021-09-17*/
@Service
public class PrintServiceImpl extends ServiceImpl<PrintMapper, Print> implements IPrintService {@Overridepublic void template(PrintVO print, HttpServletResponse response, String id) {// 模板路径Print print1 = new Print();print1.setId(Long.valueOf(id));Print detail = this.getOne(Condition.getQueryWrapper(print1));String templatePath = detail.getFileName();if (templatePath == null) {throw new ServiceException("模板不存在");}// 生成的新文件路径String newPDFPath = "\\模板.pdf";try {PdfDocument pdfDoc = new PdfDocument(new PdfReader(templatePath), new PdfWriter(newPDFPath));PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields();//模板数据Map<String, String> map = print.getMap();if (map != null) {PrintUtil.templateData(map, formFields);}//模板数据集合List<Map<String, String>> list = print.getList();if (list != null) {PrintUtil.templateDatas(list, formFields);}//特殊判断数据Map<String, String> estimate = print.getEstimate();if (estimate != null) {PrintUtil.estimate(estimate, formFields);}//设置生成表单不可编辑pdfAcroForm.flattenFields();//生成表单标题String ti = print.getHeader();Document document = new Document(pdfDoc);//表头数据Map<String, String> biaotou = print.getBiaotou();//表单数据List<Map<String, String>> biaodan = print.getTable();if (biaodan != null && biaotou != null) {if (map != null || list != null || estimate != null) {document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));}Paragraph header = PrintUtil.header(ti);document.add(header);document.add(PrintUtil.table(biaodan, biaotou));}//第二个动态表单生成String ti2 = print.getHeader();if (ti2 != null) {//表头数据Map<String, String> biaotou1 = print.getBiaotou1();//表单数据List<Map<String, String>> biaodan1 = print.getTable1();if (biaodan1 != null && biaotou1 != null) {document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));Paragraph header = PrintUtil.header(ti2);document.add(header);document.add(PrintUtil.table(biaodan1, biaotou1));}}//关闭pdfDoc.close();document.close();PrintUtil.file(newPDFPath, response);} catch (IOException e) {e.printStackTrace();}}}

Itext 7 生成PDF总结相关推荐

  1. iText+freemarker 生成PDF 使用ftl模板

    iText+freemarker 生成PDF 生成样式图片 模板地址 maven PDF生成工具类 PDF生成辅助类 base64编码工具类 service方法调用 总结 生成样式图片 模板地址 ma ...

  2. [itext]Java生成PDF文件

    一.前言 最近在做也导出试卷的功能,刚开始是导出为doc,可是导出来格式都有变化,最后说直接将word转为pdf,可是各种不稳定,各种报错.最后想到直接将文件写入pdf(参考:http://www.c ...

  3. HTML生成PDF模板(Java iText+FreeMarker生成PDF(HTML转PDF))

    Java iText+FreeMarker生成PDF(HTML转PDF) 1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中转账的电子回单,签约的电子合同等.方便用户查看,下载,打 ...

  4. Itext 7 生成pdf带有背景图

    Itext 7 生成pdf带有背景图并下载PDF到本地 引入jar包 <dependency><groupId>com.itextpdf</groupId>< ...

  5. 使用iText来生成PDF

    首先导入pom依赖 <!-- itext--><dependency><groupId>com.itextpdf</groupId><artifa ...

  6. [itext] java生成pdf

    iText简介 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转 ...

  7. Itext生成pdf文件,itext+Freemarker生成pdf,(中文空白解决)

    来源:https://my.oschina.net/lujianing/blog/894365 1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中转账的电子回单,签约的电子合同等. ...

  8. Velocity+IText+Flying-saucer生成pdf文件

    这篇文章比较长,包括三个模块的内容: 用到的相关jar包及其版本号 根据velocity模板生成html文件方法 根据html文件生成pdf文件方法 如果你是其它方法已经生成了html模板,则直接参考 ...

  9. 使用iText动态生成pdf,并用pdf.js在线预览

    Java有很多生成pdf的工具库,常用的有Apache PdfBox,iText,POI.我的项目里用的是iText. 下面说下详细步骤: 后台引入依赖: <!--pdf生成类库-->&l ...

  10. 2021-11-11 itext html生成pdf 内容过长分页问题

    项目场景: 在公司用itext 生成html 并保存为PDF,html中有个div很长很长,导致生成完PDF之后,页面有大量空白 html样式: 生成PDF之后: 解决方案: 计算好一整页有多少行数据 ...

最新文章

  1. 【Socket网络编程】6.两个既能收也能发的udp客户端进行通信的原理
  2. Hadoop之HDFS(一)HDFS入门及基本Shell命令操作
  3. 详解单链表经典OJ题
  4. redis的安装和测试
  5. laravel 内部验证码
  6. Codeforces Round #593 (Div. 2) D. Alice and the Doll 暴力 + 二分
  7. postfix邮件服务器
  8. 死锁问题------------------------INSERT ... ON DUPLICATE KEY UPDATE*(转)
  9. python模拟B-S期权定价模型
  10. 微信小程序位置授权被取消再授权
  11. Equalize Them All
  12. Python 3语法小记(四)字典 dictionary
  13. python中str.center()的功能是什么_Python str内部功能介绍
  14. 国内哪个域名注册商比较好?怎样选择域名注册商?
  15. python智慧树章节答案_智慧树_Python程序设计基础_章节答案
  16. Python基金数据实战分析:偏债混合基金篇
  17. S7-200SMART PLC如何使用MicroSD存储卡来进行程序传输和固件更新?
  18. 【NLP模型笔记】Intro || Word2vec词向量模型
  19. deepin安装问题总结
  20. 练习使用Python post请求爬取数据,并用mySQL数据库进行存储

热门文章

  1. linux下录音识别成文字软件下载,如何将录音转换成文字,这个方法你需要知道...
  2. JS动态加载JSON文件并读取数据
  3. Android 常用抓包工具介绍之Charles
  4. 程序员必备的网站推荐
  5. 大数据技术原理与应用学习笔记(五)
  6. java jaas_JAAS 参考指南
  7. ubuntu18.04安装虚拟显示器,不接显示器可远程桌面
  8. IntelliJ IDEA导出jar包
  9. 【LeetCode】题解合集(JavaScript版)
  10. vs2015安装python3.6.8,windows下安装caffe (cuda10.0,anaconda3,python3.6→python2.7,vs2015→vs2013)...