当前位置:网站首页>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(); } } }
边栏推荐
- 1041 be unique (20 points (s)) (hash: find the first number that occurs once)
- NRF24L01 troubleshooting
- Meanings and differences of PV, UV, IP, VV, CV
- 服务未正常关闭导致端口被占用
- Halcon knowledge: gray_ Tophat transform and bottom cap transform
- rtklib单点定位spp使用抗差估计遇到的问题及解决
- Fairygui loop list
- 音乐播放(Toggle && PlayerPrefs)
- Unity3D基础入门之粒子系统(属性介绍+火焰粒子系统案例制作)
- (the first set of course design) sub task 1-5 317 (100 points) (dijkstra: heavy edge self loop)
猜你喜欢
Guided package method in idea
[Nodejs] 20. Koa2 onion ring model ----- code demonstration
Programming homework: educational administration management system (C language)
Office提示您的许可证不是正版弹框解决
RTKLIB: demo5 b34f.1 vs b33
2021.11.10 compilation examination
There is no red exclamation mark after SVN update
Fairygui character status Popup
(5) Introduction to R language bioinformatics -- ORF and sequence analysis
Mixed use of fairygui button dynamics
随机推荐
It has been solved by personal practice: MySQL row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT
Unity3D,阿里云服务器,平台配置
Combination of fairygui check box and progress bar
Naive Bayesian theory derivation
Fairygui gain buff value change display
Affichage du changement de valeur du Buff de gain de l'interface graphique de défaillance
C programming exercise
Easy to use shortcut keys in idea
idea中导包方法
[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组
(课设第一套)1-5 317号子任务 (100 分)(Dijkstra:重边自环)
[algorithm] sword finger offer2 golang interview question 5: maximum product of word length
Containers and Devops: container based Devops delivery pipeline
Theoretical derivation of support vector machine
[Offer29] 排序的循环链表
What are the functions and features of helm or terrain
How to add music playback function to Arduino project
Vulnhub target: hacknos_ PLAYER V1.1
1041 Be Unique (20 point(s))(哈希:找第一个出现一次的数)
Meanings and differences of PV, UV, IP, VV, CV