当前位置:网站首页>Itext 7 生成PDF总结
Itext 7 生成PDF总结
2022-07-06 09:18:00 【Demon Lord(大魔王)】
前言:生成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 { @Override public 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(); } } }
边栏推荐
- [offer78]合并多个有序链表
- Design and implementation of general interface open platform - (39) simple and crude implementation of API services
- Programming homework: educational administration management system (C language)
- Meanings and differences of PV, UV, IP, VV, CV
- JUC forkjoin and completable future
- Single chip Bluetooth wireless burning
- Servlet
- About using @controller in gateway
- Unity scene jump and exit
- Unity场景跳转及退出
猜你喜欢
随机推荐
Minio文件下载问题——inputstream:closed
1041 be unique (20 points (s)) (hash: find the first number that occurs once)
Agile development helps me
MySQL error warning: a long semaphore wait
Talking about the startup of Oracle Database
@The difference between Autowired and @resource
Database table splitting strategy
Guided package method in idea
FairyGUI摇杆
JS function promotion and declaration promotion of VaR variable
Gravure sans fil Bluetooth sur micro - ordinateur à puce unique
[Offer29] 排序的循环链表
Fairygui loop list
Mysql database index
MySQL performance tuning - dirty page refresh
Expected value (EV)
Force buckle 1189 Maximum number of "balloons"
Single chip Bluetooth wireless burning
idea问题记录
Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)