当前位置:网站首页>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(); } } }
边栏推荐
- [899]有序队列
- FairyGUI循環列錶
- Mysql database index
- Introduction to the daily practice column of the Blue Bridge Cup
- CUDA C programming authoritative guide Grossman Chapter 4 global memory
- GNSS定位精度指标计算
- (三)R语言的生物信息学入门——Function, data.frame, 简单DNA读取与分析
- Gateway 根据服务名路由失败,报错 Service Unavailable, status=503
- (the first set of course design) 1-4 message passing interface (100 points) (simulation: thread)
- [Nodejs] 20. Koa2 onion ring model ----- code demonstration
猜你喜欢
Derivation of logistic regression theory
Easy to use shortcut keys in idea
Theoretical derivation of support vector machine
2021.11.10 compilation examination
Unity3D,阿里云服务器,平台配置
Conditional probability
(4) Data visualization of R language -- matrix chart, histogram, pie chart, scatter chart, linear regression and strip chart
MySQL time, time zone, auto fill 0
Fairygui character status Popup
Database course design: college educational administration management system (including code)
随机推荐
C programming exercise
NRF24L01 troubleshooting
Liste des boucles de l'interface graphique de défaillance
Teach you to release a DeNO module hand in hand
NovAtel 板卡OEM617D配置步骤记录
Unity3d, Alibaba cloud server, platform configuration
[offer78] merge multiple ordered linked lists
Halcon knowledge: gray_ Tophat transform and bottom cap transform
Detailed explanation of truncate usage
MySQL error warning: a long semaphore wait
Fairygui loop list
RTKLIB: demo5 b34f.1 vs b33
Database table splitting strategy
(1) Introduction Guide to R language - the first step of data analysis
Mixed use of fairygui button dynamics
Mysql database index
[Clickhouse kernel principle graphic explanation] about the collaborative work of partitioning, indexing, marking and compressed data
(the first set of course design) sub task 1-5 317 (100 points) (dijkstra: heavy edge self loop)
How to add music playback function to Arduino project
MySQL time, time zone, auto fill 0