Itext 7 生成PDF总结
生活随笔
收集整理的這篇文章主要介紹了
Itext 7 生成PDF总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言:生成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 {@Overridepublic 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();}}}總結
以上是生活随笔為你收集整理的Itext 7 生成PDF总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: servlet原理及访问时序图
- 下一篇: Quartus II13.0的破解过程