当前位置:网站首页>IText 7 generate PDF summary
IText 7 generate PDF summary
2022-07-06 12:52:00 【Demon Lord】
Preface : Generate pdf There are many ways , This article USES the itextpdf 7 Generate
1、 according to PDF The requirements of are divided into static data, dynamic data and special data
1). Static data is data fixed , So we use template to generate -----itextpdf + Adobe Acrobat DC Fill template generation
Adobe Acrobat DC You can download the green version online
(1). Pass the file first WPS Generate PDF file
(2). use Adobe Acrobat DC Open the file for Prepare the form
(3). Configure the form field of the corresponding field
(4). Incoming data for printing
2). Dynamic data is not fixed , Code generation is required ---itext 7API Official address of iText 7 7.1.5 API
(1). Add dependency
<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>
Attached at last is the first universal printing template I have written
Util Tool class
/** * @author f * @date 2021/9/28 16:56 */ public class PrintUtil { /** * Chinese Fonts * * @return * @throws IOException */ public static PdfFont typeface() throws IOException { return PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true); } /** * Template data * * @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())); } } } /** * Template data set * * @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())); } } } } /** * Need to translate fields Match the template configuration * * @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("√"); } } } /** * Form title * * @param header * @throws IOException */ public static Paragraph header(String header) throws IOException { return new Paragraph(header) // Set the font .setFont(typeface()) // Set font size .setFontSize(20) // Bold font .setBold() // Set horizontal center .setTextAlignment(TextAlignment.CENTER) // Row height .setFixedLeading(80); } /** * The form data * * @return * @throws IOException */ public static Table table(List<Map<String, String>> map, Map<String, String> biaotou) throws IOException { //4. Create a Table object int size = biaotou.entrySet().size(); UnitValue[] percentArray = UnitValue.createPercentArray(size); Table table = new Table(percentArray) .setFont(typeface()) // Vertical center .setVerticalAlignment(VerticalAlignment.MIDDLE) // Horizontal center .setTextAlignment(TextAlignment.CENTER) .setFontSize(18) // Automatic layout .setAutoLayout() // The dynamic list exceeds the width of the table Use fixed layout // .setFixedLayout() //100% .useAllAvailableWidth(); // Header 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; } /** * Return file stream * * @param newPDFPath * @param response * @throws IOException */ public static void file(String newPDFPath, HttpServletResponse response) throws IOException { // Read the file under the path File file = new File(newPDFPath); // Read the file under the specified path InputStream in = new FileInputStream(file); response.setContentType("application/pdf"); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); // Create an array of file contents byte[] buff = new byte[1024]; // The read content uses n To receive int n; // When not finished reading , Continue reading , loop while ((n = in.read(buff)) != -1) { // Write all the data of the byte array to the output stream outputStream.write(buff, 0, n); } if ((n = in.read(buff)) == -1) { // Force the data in the cache to be output outputStream.flush(); // Shut off flow outputStream.close(); in.close(); } } }
Entity class
/** * pdf Template view entity class * * @author f * @since 2021-09-17 */ @Data @EqualsAndHashCode(callSuper = true) @ApiModel(value = "PrintVO object ", description = "pdf Templates ") public class PrintVO extends Print { private static final long serialVersionUID = -5917961640607855978L; @ApiModelProperty(value = " Template data ") private Map<String, String> map; @ApiModelProperty(value = " Template data set ") private List<Map<String, String>> list; @ApiModelProperty(value = " Special data ") private Map<String, String> estimate; @ApiModelProperty(value = " Table title ") private String header; @ApiModelProperty(value = " Form header ") private Map<String, String> biaotou; @ApiModelProperty(value = " The form data ") private List<Map<String, String>> table; @ApiModelProperty(value = " Table title 1") private String header1; @ApiModelProperty(value = " Form header ") private Map<String, String> biaotou1; @ApiModelProperty(value = " The form data ") private List<Map<String, String>> table1; }
controller layer
/** * Print */ @PostMapping("/template") @ApiOperationSupport(order = 9) @ApiOperation(value = " Print ", notes = "PDF Templates ") public void template(@RequestBody PrintVO print, HttpServletResponse response, @RequestParam String id) { printService.template(print, response, id); }
service layer
/** * PDF Templates Service implementation class * * @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) { // Template path 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(" Template does not exist "); } // New file path generated String newPDFPath = "\\ Templates .pdf"; try { PdfDocument pdfDoc = new PdfDocument(new PdfReader(templatePath), new PdfWriter(newPDFPath)); PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true); Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields(); // Template data Map<String, String> map = print.getMap(); if (map != null) { PrintUtil.templateData(map, formFields); } // Template data set List<Map<String, String>> list = print.getList(); if (list != null) { PrintUtil.templateDatas(list, formFields); } // Special judgment data Map<String, String> estimate = print.getEstimate(); if (estimate != null) { PrintUtil.estimate(estimate, formFields); } // Set the generated form to be non editable pdfAcroForm.flattenFields(); // Generate form title String ti = print.getHeader(); Document document = new Document(pdfDoc); // Header data Map<String, String> biaotou = print.getBiaotou(); // The form data 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)); } // The second dynamic form generation String ti2 = print.getHeader(); if (ti2 != null) { // Header data Map<String, String> biaotou1 = print.getBiaotou1(); // The form data 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)); } } // close pdfDoc.close(); document.close(); PrintUtil.file(newPDFPath, response); } catch (IOException e) { e.printStackTrace(); } } }
边栏推荐
猜你喜欢
[Nodejs] 20. Koa2 onion ring model ----- code demonstration
FairyGUI简单背包的制作
There is no red exclamation mark after SVN update
[算法] 剑指offer2 golang 面试题12:左右两边子数组的和相等
Unity scene jump and exit
FairyGUI条子家族(滚动条,滑动条,进度条)
基本Dos命令
[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组
Unity场景跳转及退出
3月15号 Go 1.18 正式版发布 了解最新特色以及使用方法
随机推荐
(core focus of software engineering review) Chapter V detailed design exercises
FairyGUI简单背包的制作
[算法] 劍指offer2 golang 面試題2:二進制加法
(课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
Unity3D制作注册登录界面,并实现场景跳转
Derivation of logistic regression theory
燕山大学校园网自动登录问题解决方案
[offer9] implement queues with two stacks
[algorithm] sword finger offer2 golang interview question 3: the number of 1 in the binary form of the first n numbers
Matlab读取GNSS 观测值o文件代码示例
Easy to use shortcut keys in idea
SVN更新后不出现红色感叹号
wsl常用命令
(3) Introduction to bioinformatics of R language - function, data Frame, simple DNA reading and analysis
Database table splitting strategy
Idea problem record
2022国赛Re1 baby_tree
Prove the time complexity of heap sorting
Fairygui character status Popup
[algorithm] sword finger offer2 golang interview question 2: binary addition