当前位置:网站首页>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(); } } }
边栏推荐
- Fabrication d'un sac à dos simple fairygui
- There is no red exclamation mark after SVN update
- Halcon knowledge: gray_ Tophat transform and bottom cap transform
- [Clickhouse kernel principle graphic explanation] about the collaborative work of partitioning, indexing, marking and compressed data
- Unity scene jump and exit
- 堆排序【手写小根堆】
- Unity3D摄像机,键盘控制前后左右上下移动,鼠标控制旋转、放缩
- [offer18] delete the node of the linked list
- 服务未正常关闭导致端口被占用
- FairyGUI按钮动效的混用
猜你喜欢
FairyGUI循環列錶
FairyGUI复选框与进度条的组合使用
Compilation principle: preprocessing of source program and design and implementation of lexical analysis program (including code)
NovAtel 板卡OEM617D配置步骤记录
Fairygui loop list
Unity scene jump and exit
第一人称视角的角色移动
Derivation of logistic regression theory
【无标题】
Design and implementation of general interface open platform - (39) simple and crude implementation of API services
随机推荐
idea问题记录
[算法] 剑指offer2 golang 面试题3:前n个数字二进制形式中1的个数
[Yu Yue education] guide business reference materials of Wuxi Vocational and Technical College of Commerce
Special palindromes of daily practice of Blue Bridge Cup
Guided package method in idea
FairyGUI复选框与进度条的组合使用
FairyGUI簡單背包的制作
How to add music playback function to Arduino project
Containers and Devops: container based Devops delivery pipeline
Latex learning
Theoretical derivation of support vector machine
[算法] 剑指offer2 golang 面试题9:乘积小于k的子数组
dosbox第一次使用
[Chongqing Guangdong education] Shandong University College Physics reference materials
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
Fairygui joystick
服务未正常关闭导致端口被占用
FairyGUI循环列表
Unity场景跳转及退出
(the first set of course design) 1-4 message passing interface (100 points) (simulation: thread)