Java用itextpdf導(dǎo)出PDF方法(通俗易懂)
前言
在java開(kāi)發(fā)的過(guò)程中會(huì)遇到太多太多文檔pdf導(dǎo)出,excle導(dǎo)出等業(yè)務(wù)場(chǎng)景,時(shí)隔三個(gè)月或半年來(lái)一次每一次遇到這樣的業(yè)務(wù)場(chǎng)景對(duì)我都是非常痛苦的過(guò)程,本文旨在記錄工具類使用方法和技術(shù)分享。
一、itextpdf是什么?
itextpdf是一個(gè)開(kāi)源的Java庫(kù),用于創(chuàng)建和操作PDF文檔。使用itextpdf,您可以創(chuàng)建新的PDF文檔或修改現(xiàn)有文檔,添加文本和圖像,創(chuàng)建表單等等。該庫(kù)提供了廣泛的功能,并經(jīng)常用于企業(yè)級(jí)應(yīng)用程序中根據(jù)用戶輸入動(dòng)態(tài)生成復(fù)雜的PDF文檔。它具有各種許可證選項(xiàng),具體取決于您的用例,范圍從AGPL到商業(yè)許可證。
itextpdf庫(kù)提供了大量的方法和功能,以下是一些常用的方法:
- 創(chuàng)建PDF文檔和頁(yè)面:使用PdfWriter和Document對(duì)象可以創(chuàng)建一個(gè)新的PDF文檔并添加頁(yè)面。
- 添加內(nèi)容到PDF文檔:使用Paragraph、Phrase和Chunk對(duì)象可以向PDF文檔中添加文本內(nèi)容。同時(shí),也可以添加圖片、表格等其它類型的內(nèi)容。
- 創(chuàng)建表格:使用PdfPTable對(duì)象可以創(chuàng)建表格,并向其中添加行和單元格。
- 設(shè)置頁(yè)眉頁(yè)腳:使用HeaderFooter對(duì)象可以設(shè)置PDF文檔的頁(yè)眉和頁(yè)腳,以及頁(yè)碼等信息。
- 創(chuàng)建書(shū)簽:使用PdfOutline對(duì)象可以創(chuàng)建PDF文檔的書(shū)簽,方便用戶在瀏覽器中導(dǎo)航。
- 導(dǎo)出PDF文檔:使用PdfWriter對(duì)象可以將PDF文檔導(dǎo)出為文件或流。
二、快速開(kāi)始
1.廢話不多說(shuō),效果先上一波
下列數(shù)據(jù)均為測(cè)試虛擬數(shù)據(jù),不具有任何真實(shí)性
2.依賴引入
<!--itext5--> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.11</version> </dependency>
3.模版加載
rescources-templates-創(chuàng)建一個(gè)pdf模版,如果沒(méi)有定制內(nèi)容,直接為空白即可
3.1模版加載工具類PDF
/** * 字體對(duì)象 */ public static BaseFont bfChinese; /** * 定義全局的字體靜態(tài)變量 */ public static Font titlefont; public static Font titleSecondFont; public static Font headfont; public static Font secondHeadfont; public static Font textfont; public static Font secondTitleFont; public static Font itemFont; public static Font paragraphFont; public static Font tableCellFont; public static Font accessoryFont; /** * 間距 */ public static String shortSpacing = " "; public static String mediumSpacing = " "; public static String longSpacing = " "; public static String maxLongSpacing = " "; public static String shortSlash = " / "; public static String mediumSlash = " / "; public static String longSlash = " / "; public static String maxLongSlash = " / "; /** * 模版 */ public static String ht; public static String scan; public static String htScan; public static String over; public static String htSign; public static String signatureHt; public static File htFile; public static File overFile; public static File htSignFile; /** * 初始化字體及勾選、未勾選圖標(biāo) */ static { try { // 不同字體(這里定義為同一種字體:包含不同字號(hào)、不同style) bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); titlefont = new Font(bfChinese, 16, Font.NORMAL); titleSecondFont = new Font(bfChinese, 14, Font.NORMAL); headfont = new Font(bfChinese, 14, Font.BOLD); secondHeadfont = new Font(bfChinese, 15, Font.BOLD); textfont = new Font(bfChinese, 16, Font.NORMAL); secondTitleFont = new Font(bfChinese,18,Font.BOLD); itemFont = new Font(bfChinese,16,Font.BOLD); paragraphFont = new Font(bfChinese,11,Font.NORMAL); accessoryFont = new Font(bfChinese,13,Font.NORMAL); tableCellFont = new Font(bfChinese,9,Font.NORMAL); /** * 判斷當(dāng)前環(huán)境 */ String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("win")||osName.contains("mac")) { ht = getResourceBasePath() + "\\templates\\ht.pdf"; htFile = new File(ht); } else { //todo: linux或unbunt ht = "/mnt/jar/spring-cloud/ht.pdf"; htFile = new File(ht); } } catch (Exception e) { e.printStackTrace(); } } /** * 獲取項(xiàng)目根路徑 * * @return */ public static String getResourceBasePath() { // 獲取根目錄 File path = null; try { path = new File(ResourceUtils.getURL("classpath:").getPath()); } catch (FileNotFoundException e) { } if (path == null || !path.exists()) { path = new File(""); } //todo: 就獲取第三步中模版所在的位置,請(qǐng)看上列中 “3.模版加載里的內(nèi)容” File file = new File(path.getAbsolutePath() + "\\templates"); if (!file.exists()){ return path.getAbsolutePath().replace("xx","xx"); } return path.getAbsolutePath(); }
4.PDF操作工具類方法
public static PdfPTable createTable() throws DocumentException { PdfPTable table = new PdfPTable(2); // 設(shè)置總寬度 table.setTotalWidth(490); table.setLockedWidth(true); // 設(shè)置每一列寬度 table.setTotalWidth(new float[] {240,240}); table.setLockedWidth(true); return table; } public PdfPTable createTable(int numColumns) { PdfPTable table = new PdfPTable(numColumns); // 設(shè)置總寬度 table.setTotalWidth(490); table.setLockedWidth(true); return table; } public static PdfPTable createTitleTable(int numColumns,Font font, String ... titles) { PdfPTable table = new PdfPTable(numColumns); // 設(shè)置總寬度 table.setTotalWidth(490); table.setLockedWidth(true); for (String title : titles) { addTitleCell(table,title,1,font); } return table; } /** * 添加居中 title * @param document * @param text * @throws DocumentException * todo: 字體大小16px */ public static void addTitle(Document document, String text, int alignment) throws DocumentException { Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 16, Font.NORMAL)); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(0); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(0); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(0); //設(shè)置首行縮進(jìn) paragraph.setLeading(10f); //行間距 paragraph.setSpacingBefore(10f); //設(shè)置段落上空白 paragraph.setSpacingAfter(10f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加一級(jí)標(biāo)題 * @param document * @param text * @throws DocumentException */ public static void addFirstTitle(Document document,String text,int alignment) throws DocumentException { Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 14, Font.NORMAL)); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(0); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(0); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(0); //設(shè)置首行縮進(jìn) paragraph.setLeading(7f); //行間距 paragraph.setSpacingBefore(20f); //設(shè)置段落上空白 paragraph.setSpacingAfter(7f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加二級(jí)標(biāo)題 * @param document * @param text * @throws DocumentException */ public static void addSecondTitle(Document document,String text,Font font,int alignment) throws DocumentException { Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 12, Font.NORMAL)); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(9); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(0); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(9); //設(shè)置首行縮進(jìn) paragraph.setLeading(15f); //行間距 paragraph.setSpacingBefore(10f); //設(shè)置段落上空白 paragraph.setSpacingAfter(5f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加分割線 * @param document * @throws DocumentException */ public static void addLine(Document document) throws DocumentException { LineSeparator ls = new LineSeparator(); ls.setLineWidth(1); ls.setLineColor(new BaseColor(179,180,164)); Chunk chunk = new Chunk(ls); document.add(chunk); } public static void addNoBorderCell(PdfPTable table,String text) { PdfPCell cell = new PdfPCell(new Paragraph(text,paragraphFont)); cell.setBorderWidth(0); cell.setLeading(24,0); //行間距 table.addCell(cell); } public static void addTitleCell(PdfPTable table,String text,float borderWidth,Font font) { Paragraph paragraph = new Paragraph(text, font); paragraph.setAlignment(1); paragraph.setLeading(5f); PdfPCell cell = new PdfPCell(paragraph); cell.setBorderWidth(borderWidth); cell.setBackgroundColor(new BaseColor(245,247,251)); cell.setHorizontalAlignment(1); cell.setVerticalAlignment(1); table.addCell(cell); } public static void addCell(PdfPTable table,String text,float borderWidth,Font font) { if (StringUtils.isBlank(text)) { text = " "; } Paragraph paragraph = new Paragraph(text, font); paragraph.setAlignment(1); PdfPCell cell = new PdfPCell(paragraph); //水平居中和垂直居中 cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setUseAscender(true); table.addCell(cell); } public static void addCell(PdfPTable table, BigDecimal amount, float borderWidth, Font font) { Paragraph paragraph = null; if (Objects.isNull(amount)) { paragraph = new Paragraph(" ",font); } else { paragraph = new Paragraph(amount.toString(),font); } paragraph.setAlignment(1); PdfPCell cell = new PdfPCell(paragraph); cell.setBorderWidth(borderWidth); //水平居中和垂直居中 cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setUseAscender(true); table.addCell(cell); } /** * 添加二級(jí)標(biāo)題 * @param document * @param text * @throws DocumentException */ public void addSecondTitle(Document document,String text,int alignment,float spacingBefore,float spacingAfter) throws DocumentException { Paragraph paragraph10 = new Paragraph(text, secondTitleFont); paragraph10.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph10.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph10.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph10.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph10.setLeading(30f); //行間距 paragraph10.setSpacingBefore(1f); //設(shè)置段落上空白 paragraph10.setSpacingAfter(15f); //設(shè)置段落下空白 document.add(paragraph10); } /** * 添加子項(xiàng)標(biāo)題 * @param document * @param text * @throws DocumentException */ public void addItemTitle(Document document,String text) throws DocumentException { Paragraph paragraph = new Paragraph(text, itemFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 paragraph.setSpacingBefore(1f); //設(shè)置段落上空白 paragraph.setSpacingAfter(1f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加段落 自動(dòng)換行 */ public void addTextParagraph(Document document,String text) throws DocumentException { Paragraph paragraph = new Paragraph(text,paragraphFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 document.add(paragraph); } /** * 添加段落 自動(dòng)換行 */ public Paragraph createTextParagraph() throws DocumentException { Paragraph paragraph = new Paragraph("",paragraphFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 return paragraph; } /** * 添加段落 自動(dòng)換行 */ public Paragraph createTextParagraph(String text) throws DocumentException { Paragraph paragraph = new Paragraph(text,paragraphFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 return paragraph; } /** * 創(chuàng)建段落 自動(dòng)換行 */ public Paragraph createTextParagraph(String text,int alignment) { Paragraph paragraph = new Paragraph(text,paragraphFont); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 return paragraph; } public void appendParagraph(Document document,Paragraph paragraph,String text) throws DocumentException { paragraph.add(text); document.add(paragraph); } /** * 添加下劃線 */ public Paragraph addUnderLine(Paragraph paragraph,String text){ if (StringUtils.isBlank(text)){ text = shortSpacing; } else { text = StringUtils.join(" ",text," "); } Chunk sigUnderline = new Chunk(text); sigUnderline.setUnderline(0.1f, -2f); paragraph.add(sigUnderline); return paragraph; } /** * 添加下劃線 */ public void addUnderLine(Document document,Paragraph paragraph,String text) throws DocumentException { if (StringUtils.isBlank(text)){ text = shortSpacing; } Chunk sigUnderline = new Chunk(StringUtils.join(" ",text," ")); sigUnderline.setUnderline(0.1f, -2f); paragraph.add(sigUnderline); document.add(paragraph); } /**objStmMark = null * 追加簽名 */ public File mergePdf(String [] files,String savePath){ PdfReader pdfReader = null; Document document = null; try { //創(chuàng)建一個(gè)與a.pdf相同紙張大小的document pdfReader = new PdfReader(files[0]); document = new Document(pdfReader.getPageSize(1)); PdfCopy copy = new PdfCopy(document, new FileOutputStream(savePath)); document.open(); for (int i = 0; i < files.length; i++) { //一個(gè)一個(gè)的遍歷現(xiàn)有的PDF PdfReader reader = new PdfReader(files[i]); int n = reader.getNumberOfPages();//PDF文件總共頁(yè)數(shù) System.out.println("n:"+n); for (int j = 1; j <= n; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } reader.close(); } document.close(); pdfReader.close(); return new File(savePath); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } finally { document.close(); pdfReader.close(); } return null; } /** * 添加下劃線 */ public Paragraph addUnderLine(Boolean check,Paragraph paragraph,String text1,String text2){ Chunk sigUnderline = null; if (check){ if (Objects.isNull(text1)){ text1 = shortSpacing; } else { text1 = StringUtils.join(" ",text1," "); } sigUnderline = new Chunk(text1); } else { if (Objects.isNull(text2)){ text2 = shortSpacing; } else { text2 = StringUtils.join(" ",text2," "); } sigUnderline = new Chunk(text2); } sigUnderline.setUnderline(0.1f, -2f); paragraph.add(sigUnderline); return paragraph; } /** * 添加下劃線 */ public void addUnderLine(Document document,Boolean check,Paragraph paragraph,String text1,String text2) throws DocumentException { Chunk sigUnderline = null; if (check){ if (Objects.isNull(text1)){ text1 = shortSpacing; } else { text1 = StringUtils.join(" ",text1," "); } sigUnderline = new Chunk(text1); } else { if (Objects.isNull(text2)){ text2 = shortSpacing; } else { text2 = StringUtils.join(" ",text2," "); } sigUnderline = new Chunk(text2); } sigUnderline.setUnderline(0.1F, -2.0F); paragraph.add(sigUnderline); document.add(paragraph); } /** * 添加下劃線 Chunk */ public Chunk createUnderLineChunk(String text) { if (Objects.isNull(text)){ text = shortSpacing; } else { text = StringUtils.join(" ",text," "); } Chunk sigUnderline = new Chunk(text); sigUnderline.setUnderline(0.1f, -2f); return sigUnderline; } private Document createDocument() throws IOException { // 1.新建document對(duì)象 建立一個(gè)Document對(duì)象 Document document = new Document(PageSize.A4); // PdfUtils.htFile.createNewFile(); // 3.打開(kāi)文檔 document.open(); document.addTitle("銷售合同");// 標(biāo)題 document.addAuthor("chuz");// 作者 document.addSubject("Subject@iText pdf sample");// 主題 document.addKeywords("Keywords@iTextpdf");// 關(guān)鍵字 document.addCreator("chuz develop");// 創(chuàng)建者 return document; } /** * 添加下劃線 Chunk */ public Chunk createUnderLineChunk(Boolean check,String text1,String text2) throws DocumentException { Chunk sigUnderline = null; if (check){ if (Objects.isNull(text1)){ text1 = shortSpacing; } else { text1 = StringUtils.join(" ",text1," "); } sigUnderline = new Chunk(text1); } else { if (Objects.isNull(text2)){ text2 = shortSpacing; } else { text2 = StringUtils.join(" ",text2," "); } sigUnderline = new Chunk(text2); } sigUnderline.setUnderline(0.1f, -2f); return sigUnderline; } /** * 添加下劃線 Chunk */ public Chunk createChunk(String text) throws DocumentException { if (StringUtils.isBlank(text)){ text = shortSpacing; } text = StringUtils.join(" ",text," "); return new Chunk(text); } /** * 添加帶選擇框文本 */ // public void addCheck(Document document,Boolean check,String text) throws Exception { // Paragraph paragraph = createTextParagraph(""); // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // document.add(paragraph); // } /** * 添加帶選擇框文本 */ // public void addCheck(Paragraph paragraph,Boolean check,String text) throws Exception { // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // } /** * 添加帶選擇框文本 */ // public Paragraph addCheck(Boolean check,String text) throws Exception { // Paragraph paragraph = createTextParagraph(""); // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // return paragraph; // } /** * 添加帶選擇框文本 */ // public Paragraph appendCheck(Paragraph paragraph,Boolean check,String text) throws Exception { // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // return paragraph; // } public void packageDateParagraph(Document document, Paragraph paragraph, Date date) throws DocumentException { if (Objects.nonNull(date)){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); addUnderLine(paragraph,StringUtils.join(year)); paragraph.add("年"); addUnderLine(paragraph,StringUtils.join(month)); paragraph.add("月"); addUnderLine(paragraph,StringUtils.join(day)); paragraph.add("日"); } else { addUnderLine(paragraph,StringUtils.join(shortSlash)); paragraph.add("年"); addUnderLine(paragraph,StringUtils.join(shortSlash)); paragraph.add("月"); addUnderLine(paragraph,StringUtils.join(shortSlash)); paragraph.add("日"); } document.add(paragraph); } public MultipartFile fileToMultipartFile(File file) { FileItem fileItem = createFileItem(file); MultipartFile multipartFile = new CommonsMultipartFile(fileItem); return multipartFile; } public static FileItem createFileItem(File file) { FileItemFactory factory = new DiskFileItemFactory(16, null); FileItem item = factory.createItem("textField", "text/plain", true, file.getName()); int bytesRead = 0; byte[] buffer = new byte[8192]; try { FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream(); while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } return item; } public String precision(BigDecimal number){ if (Objects.nonNull(number)){ return number.setScale(0,BigDecimal.ROUND_DOWN).toString(); } return null; }
5.完整代碼
5.1前端代碼-Vue
downloadPdf(){ api.downloadPdf({ fileName: this.data.contractName+'.pdf', params: {type:'0',contractId:this.data.id} }) },
5.2控制層代碼
@GetMapping(value = "create") public void create(@ApiParam(value = "0:銷售合同,1:第三方合同") @RequestParam(name = "type") String type, @RequestParam(name = "contractId") String contractId, HttpServletResponse response) throws IOException { File pdfFile = null; if ("0".equals(type)) { /* 合同條款 */ //到業(yè)務(wù)方法 xx代替,這里主要是根據(jù)條件查詢從表信息 List<xxx> 1 =getXXX(); //設(shè)計(jì)到業(yè)務(wù)方法 xx代替,這里主要是根據(jù)條件查詢從表信息 List<xxx> 1 =getXXX(); // 儀表經(jīng)驗(yàn)計(jì)費(fèi)條款 List<xxx> 1 =getXXX(); /* 其它費(fèi)用 */ List<xxx> 1 =getXXX(); //導(dǎo)出方法 pdfFile = contractPdfService.createContractInfo(createContractInfo); } response.setContentType("application/pdf"); if (pdfFile.exists()) { FileInputStream in = new FileInputStream(pdfFile); OutputStream out = response.getOutputStream(); byte[] b = new byte[1024 * 5]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } out.flush(); in.close(); out.close(); } }
5.3業(yè)務(wù)層代碼
public File createContractInfo(CreateContractInfo contractInfo){ try { // 1.新建document對(duì)象 建立一個(gè)Document對(duì)象 Document document = new Document(PageSize.A4); PdfUtils.htFile.createNewFile(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PdfUtils.htFile)); // 3.打開(kāi)文檔 document.open(); document.addTitle(contractInfo.getContractName());// 標(biāo)題 document.addAuthor("chuz");// 作者 document.addSubject("Subject@iText pdf sample");// 主題 document.addKeywords("Keywords@iTextpdf");// 關(guān)鍵字 document.addCreator("chuz develop");// 創(chuàng)建者 // 4.向文檔中添加內(nèi)容 generatePDF(document,contractInfo); // 5.關(guān)閉文檔 document.close(); writer.close(); return PdfUtils.htFile; } catch (Exception e) { e.printStackTrace(); } return PdfUtils.htFile; } // 生成PDF文件 public void generatePDF(Document document,CreateContractInfo contractInfo) throws Exception { //添加總標(biāo)題, PdfUtils.addTitle(document,contractInfo.getContractName(),1); // 基本信息-一級(jí)標(biāo)題 PdfUtils.addFirstTitle(document,"(一)基本信息",0); PdfPTable table = PdfUtils.createTable(); PdfUtils.addNoBorderCell(table,StringUtils.join("合同編號(hào):",contractInfo.getContractNo())); PdfUtils.addNoBorderCell(table,StringUtils.join("出租方:",contractInfo.getFirstPartyName())); PdfUtils.addNoBorderCell(table,StringUtils.join("出租方:",contractInfo.getFirstPartyName())); PdfUtils.addNoBorderCell(table,StringUtils.join("租賃方:",contractInfo.getPartyBName())); PdfUtils.addNoBorderCell(table,StringUtils.join("經(jīng)辦人:",contractInfo.getHandledByName())); PdfUtils.addNoBorderCell(table,StringUtils.join("簽訂日期:", DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,contractInfo.getSigningTime()))); PdfUtils.addNoBorderCell(table,StringUtils.join("業(yè)態(tài):",contractInfo.getContractTypeName())); PdfUtils.addNoBorderCell(table,StringUtils.join("意向來(lái)源:",dictTrans("customer_source",contractInfo.getContractSource()))); PdfUtils.addNoBorderCell(table,StringUtils.join("合同標(biāo)簽:",contractInfo.getContractLabel())); PdfUtils.addNoBorderCell(table,StringUtils.join("租賃日期:",StringUtils.join( DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,contractInfo.getStartTime()), "~", DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,contractInfo.getEndTime())))); document.add(table); PdfUtils.addLine(document); // 合同條款-一級(jí)標(biāo)題 PdfUtils.addFirstTitle(document,"(二)合同條款",0); PdfUtils.addSecondTitle(document,"合同計(jì)費(fèi)條款",PdfUtils.titleSecondFont,0); PdfPTable itemTable = PdfUtils.createTitleTable(5,PdfUtils.tableCellFont,"資源","收費(fèi)項(xiàng)","計(jì)費(fèi)方式","計(jì)費(fèi)周期","計(jì)算方式"); for (FreeContractClauseDto contractClauseDto : contractInfo.getContractClauseDtos()) { PdfUtils.addCell(itemTable,contractClauseDto.getHouseName(),1,PdfUtils.tableCellFont); PdfUtils.addCell(itemTable,contractClauseDto.getSetName(),1,PdfUtils.tableCellFont); PdfUtils.addCell(itemTable,dictTrans("free_calculate_way",contractClauseDto.getCalculateWay()),1,PdfUtils.tableCellFont); PdfUtils.addCell(itemTable,dictTrans("charging_cycle",contractClauseDto.getChargingCycle()),1,PdfUtils.tableCellFont); PdfUtils.addCell(itemTable,contractClauseDto.getFreeRemarks(),1,PdfUtils.tableCellFont); } document.add(itemTable); PdfUtils.addSecondTitle(document,"儀表/經(jīng)營(yíng)計(jì)費(fèi)條款",PdfUtils.titleSecondFont,0); PdfPTable deviceTable = PdfUtils.createTitleTable(4,PdfUtils.tableCellFont,"資源","收費(fèi)項(xiàng)","計(jì)費(fèi)方式","儀表/錄數(shù)項(xiàng)"); for (FreeContractClauseDto deviceContractClauseDto : contractInfo.getDeviceContractClauseDtos()) { PdfUtils.addCell(deviceTable,deviceContractClauseDto.getHouseName(),1,PdfUtils.tableCellFont); PdfUtils.addCell(deviceTable,deviceContractClauseDto.getSetName(),1,PdfUtils.tableCellFont); PdfUtils.addCell(deviceTable,deviceContractClauseDto.getChargeStandard(),1,PdfUtils.tableCellFont); PdfUtils.addCell(deviceTable,deviceContractClauseDto.getMeterNo(),1,PdfUtils.tableCellFont); } document.add(deviceTable); PdfUtils.addSecondTitle(document,"其他費(fèi)用添加",PdfUtils.titleSecondFont,0); PdfPTable elseFreeTable = PdfUtils.createTitleTable(8,PdfUtils.tableCellFont,"資源","收費(fèi)項(xiàng)","應(yīng)收(元)","實(shí)收(元)","欠收(元)","應(yīng)收日期","賬期","備注"); for (FreeBillDetailVo elseFreeBillDetailVo : contractInfo.getElseFreeBillDetailVos()) { PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getHouseName(),1,PdfUtils.tableCellFont); PdfUtils.addCell(elseFreeTable,"收費(fèi)項(xiàng)",1,PdfUtils.tableCellFont); PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getOughtAmount(),1,PdfUtils.tableCellFont); PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getPracticalAmount(),1,PdfUtils.tableCellFont); PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getOweAmount(),1,PdfUtils.tableCellFont); PdfUtils.addCell(elseFreeTable,DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,elseFreeBillDetailVo.getOughtDate()),1,PdfUtils.tableCellFont); PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getPeriod(),1,PdfUtils.tableCellFont); PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getRemarks(),1,PdfUtils.tableCellFont); } document.add(elseFreeTable); PdfUtils.addLine(document); // 其它約定 PdfUtils.addFirstTitle(document,"(三)其它約定",0); PdfPTable elseTable = PdfUtils.createTable(); PdfUtils.addNoBorderCell(elseTable,"設(shè)施/服務(wù):設(shè)施/服務(wù)"); PdfUtils.addNoBorderCell(elseTable,"特殊約定:特殊約定"); PdfUtils.addNoBorderCell(elseTable,"違約說(shuō)明:違約說(shuō)明"); PdfUtils.addNoBorderCell(elseTable,""); document.add(elseTable); PdfUtils.addLine(document); // 合同賬單-自定義 Paragraph paragraph = new Paragraph("(四)合同賬單", new Font(PdfUtils.bfChinese, 14, Font.NORMAL)); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(0); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(0); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(0); //設(shè)置首行縮進(jìn) paragraph.setLeading(7f); //行間距 paragraph.setSpacingBefore(20f); //設(shè)置段落上空白 paragraph.setSpacingAfter(25f); //設(shè)置段落下空白 document.add(paragraph); PdfPTable billTable = PdfUtils.createTitleTable(10,PdfUtils.tableCellFont,"費(fèi)用項(xiàng)目","費(fèi)用類型","費(fèi)用標(biāo)識(shí)","賬期","起止時(shí)間","應(yīng)收金額(元)","實(shí)收金額(元)","欠費(fèi)金額(元)","繳費(fèi)時(shí)間","狀態(tài)"); List<FreeBillDetailVo> freeBillDetailVos = contractInfo.getFreeBillDetailVos(); for (FreeBillDetailVo freeBillDetailVo : freeBillDetailVos) { PdfUtils.addCell(billTable,"租金",1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,"租金",1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,"周期性收費(fèi)",1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,freeBillDetailVo.getPeriod(),1,PdfUtils.tableCellFont); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dateTime=sdf.format(freeBillDetailVo.getBeginTime())+"~"+sdf.format(freeBillDetailVo.getEndTime()); PdfUtils.addCell(billTable,dateTime,1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,freeBillDetailVo.getPracticalAmount(),1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,freeBillDetailVo.getOughtAmount(),1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,freeBillDetailVo.getOweAmount(),1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd_HHmmss,freeBillDetailVo.getPayTime()),1,PdfUtils.tableCellFont); PdfUtils.addCell(billTable,"未結(jié)清",1,PdfUtils.tableCellFont); } document.add(billTable); }
5.4PDF工具類完整代碼
public class PdfUtils { public static BaseFont bfChinese; /** * 定義全局的字體靜態(tài)變量 */ public static Font titlefont; public static Font titleSecondFont; public static Font headfont; public static Font secondHeadfont; public static Font textfont; public static Font secondTitleFont; public static Font itemFont; public static Font paragraphFont; public static Font tableCellFont; public static Font accessoryFont; /** * 圖標(biāo) */ // public static Image checkPng; // public static Image unCheckPng; /** * 間距 */ public static String shortSpacing = " "; public static String mediumSpacing = " "; public static String longSpacing = " "; public static String maxLongSpacing = " "; public static String shortSlash = " / "; public static String mediumSlash = " / "; public static String longSlash = " / "; public static String maxLongSlash = " / "; /** * 模版 */ public static String ht; public static String scan; public static String htScan; public static String over; public static String htSign; public static String signatureHt; public static File htFile; public static File overFile; public static File htSignFile; /** * 初始化字體及勾選、未勾選圖標(biāo) */ static { try { // 不同字體(這里定義為同一種字體:包含不同字號(hào)、不同style) bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); titlefont = new Font(bfChinese, 16, Font.NORMAL); titleSecondFont = new Font(bfChinese, 14, Font.NORMAL); headfont = new Font(bfChinese, 14, Font.BOLD); secondHeadfont = new Font(bfChinese, 15, Font.BOLD); textfont = new Font(bfChinese, 16, Font.NORMAL); secondTitleFont = new Font(bfChinese,18,Font.BOLD); itemFont = new Font(bfChinese,16,Font.BOLD); paragraphFont = new Font(bfChinese,11,Font.NORMAL); accessoryFont = new Font(bfChinese,13,Font.NORMAL); tableCellFont = new Font(bfChinese,9,Font.NORMAL); /** * 判斷當(dāng)前環(huán)境 */ String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("win")||osName.contains("mac")) { // checkPng = Image.getInstance(getResourceBasePath() + "\\templates\\check.png"); // checkPng.scaleAbsolute(14,12); // unCheckPng = Image.getInstance(getResourceBasePath() + "\\templates\\unCheck.png"); // unCheckPng.scaleAbsolute(14,12); ht = getResourceBasePath() + "\\templates\\ht.pdf"; scan = getResourceBasePath() + "\\templates\\scan.pdf"; htScan = getResourceBasePath() + "\\templates\\htScan.pdf"; over = getResourceBasePath() + "\\templates\\over.pdf"; htSign = getResourceBasePath() + "\\templates\\htSign.pdf"; htFile = new File(ht); overFile = new File(over); htSignFile = new File(htSign); } else { //todo: linux或unbunt // checkPng = Image.getInstance("/mnt/jar/chuz-cloud-school/check.png"); // checkPng.scaleAbsolute(14,12); // unCheckPng = Image.getInstance("/mnt/jar/chuz-cloud-school/unCheck.png"); // unCheckPng.scaleAbsolute(14,12); ht = "/mnt/jar/chuz-cloud-school/ht.pdf"; scan = "/mnt/jar/chuz-cloud-school/scan.pdf"; htScan = "/mnt/jar/chuz-cloud-school/htScan.pdf"; over = "/mnt/jar/chuz-cloud-school/over.pdf"; htSign = "/mnt/jar/chuz-cloud-school/htSign.pdf"; htFile = new File(ht); overFile = new File(over); htSignFile = new File(htSign); } } catch (Exception e) { e.printStackTrace(); } } /** * 獲取項(xiàng)目根路徑 * * @return */ public static String getResourceBasePath() { // 獲取根目錄 File path = null; try { path = new File(ResourceUtils.getURL("classpath:").getPath()); } catch (FileNotFoundException e) { } if (path == null || !path.exists()) { path = new File(""); } File file = new File(path.getAbsolutePath() + "\\templates"); if (!file.exists()){ return path.getAbsolutePath().replace("chuz-cloud-module\\chuz-cloud-school-start","chuz-boot-module-school"); } return path.getAbsolutePath(); } public static PdfPTable createTable() throws DocumentException { PdfPTable table = new PdfPTable(2); // 設(shè)置總寬度 table.setTotalWidth(490); table.setLockedWidth(true); // 設(shè)置每一列寬度 table.setTotalWidth(new float[] {240,240}); table.setLockedWidth(true); return table; } public PdfPTable createTable(int numColumns) { PdfPTable table = new PdfPTable(numColumns); // 設(shè)置總寬度 table.setTotalWidth(490); table.setLockedWidth(true); return table; } public static PdfPTable createTitleTable(int numColumns,Font font, String ... titles) { PdfPTable table = new PdfPTable(numColumns); // 設(shè)置總寬度 table.setTotalWidth(490); table.setLockedWidth(true); for (String title : titles) { addTitleCell(table,title,1,font); } return table; } /** * 添加居中 title * @param document * @param text * @throws DocumentException * todo: 字體大小16px */ public static void addTitle(Document document, String text, int alignment) throws DocumentException { Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 16, Font.NORMAL)); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(0); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(0); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(0); //設(shè)置首行縮進(jìn) paragraph.setLeading(10f); //行間距 paragraph.setSpacingBefore(10f); //設(shè)置段落上空白 paragraph.setSpacingAfter(10f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加一級(jí)標(biāo)題 * @param document * @param text * @throws DocumentException */ public static void addFirstTitle(Document document,String text,int alignment) throws DocumentException { Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 14, Font.NORMAL)); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(0); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(0); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(0); //設(shè)置首行縮進(jìn) paragraph.setLeading(7f); //行間距 paragraph.setSpacingBefore(20f); //設(shè)置段落上空白 paragraph.setSpacingAfter(7f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加二級(jí)標(biāo)題 * @param document * @param text * @throws DocumentException */ public static void addSecondTitle(Document document,String text,Font font,int alignment) throws DocumentException { Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 12, Font.NORMAL)); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(9); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(0); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(9); //設(shè)置首行縮進(jìn) paragraph.setLeading(15f); //行間距 paragraph.setSpacingBefore(10f); //設(shè)置段落上空白 paragraph.setSpacingAfter(5f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加分割線 * @param document * @throws DocumentException */ public static void addLine(Document document) throws DocumentException { LineSeparator ls = new LineSeparator(); ls.setLineWidth(1); ls.setLineColor(new BaseColor(179,180,164)); Chunk chunk = new Chunk(ls); document.add(chunk); } public static void addNoBorderCell(PdfPTable table,String text) { PdfPCell cell = new PdfPCell(new Paragraph(text,paragraphFont)); cell.setBorderWidth(0); cell.setLeading(24,0); //行間距 table.addCell(cell); } public static void addTitleCell(PdfPTable table,String text,float borderWidth,Font font) { Paragraph paragraph = new Paragraph(text, font); paragraph.setAlignment(1); paragraph.setLeading(5f); PdfPCell cell = new PdfPCell(paragraph); cell.setBorderWidth(borderWidth); cell.setBackgroundColor(new BaseColor(245,247,251)); cell.setHorizontalAlignment(1); cell.setVerticalAlignment(1); table.addCell(cell); } public static void addCell(PdfPTable table,String text,float borderWidth,Font font) { if (StringUtils.isBlank(text)) { text = " "; } Paragraph paragraph = new Paragraph(text, font); paragraph.setAlignment(1); PdfPCell cell = new PdfPCell(paragraph); //水平居中和垂直居中 cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setUseAscender(true); table.addCell(cell); } public static void addCell(PdfPTable table, BigDecimal amount, float borderWidth, Font font) { Paragraph paragraph = null; if (Objects.isNull(amount)) { paragraph = new Paragraph(" ",font); } else { paragraph = new Paragraph(amount.toString(),font); } paragraph.setAlignment(1); PdfPCell cell = new PdfPCell(paragraph); cell.setBorderWidth(borderWidth); //水平居中和垂直居中 cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setUseAscender(true); table.addCell(cell); } /** * 添加二級(jí)標(biāo)題 * @param document * @param text * @throws DocumentException */ public void addSecondTitle(Document document,String text,int alignment,float spacingBefore,float spacingAfter) throws DocumentException { Paragraph paragraph10 = new Paragraph(text, secondTitleFont); paragraph10.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph10.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph10.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph10.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph10.setLeading(30f); //行間距 paragraph10.setSpacingBefore(1f); //設(shè)置段落上空白 paragraph10.setSpacingAfter(15f); //設(shè)置段落下空白 document.add(paragraph10); } /** * 添加子項(xiàng)標(biāo)題 * @param document * @param text * @throws DocumentException */ public void addItemTitle(Document document,String text) throws DocumentException { Paragraph paragraph = new Paragraph(text, itemFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 paragraph.setSpacingBefore(1f); //設(shè)置段落上空白 paragraph.setSpacingAfter(1f); //設(shè)置段落下空白 document.add(paragraph); } /** * 添加段落 自動(dòng)換行 */ public void addTextParagraph(Document document,String text) throws DocumentException { Paragraph paragraph = new Paragraph(text,paragraphFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 document.add(paragraph); } /** * 添加段落 自動(dòng)換行 */ public Paragraph createTextParagraph() throws DocumentException { Paragraph paragraph = new Paragraph("",paragraphFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 return paragraph; } /** * 添加段落 自動(dòng)換行 */ public Paragraph createTextParagraph(String text) throws DocumentException { Paragraph paragraph = new Paragraph(text,paragraphFont); paragraph.setAlignment(0); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 return paragraph; } /** * 創(chuàng)建段落 自動(dòng)換行 */ public Paragraph createTextParagraph(String text,int alignment) { Paragraph paragraph = new Paragraph(text,paragraphFont); paragraph.setAlignment(alignment); //設(shè)置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設(shè)置左縮進(jìn) paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn) paragraph.setFirstLineIndent(32); //設(shè)置首行縮進(jìn) paragraph.setLeading(30f); //行間距 return paragraph; } public void appendParagraph(Document document,Paragraph paragraph,String text) throws DocumentException { paragraph.add(text); document.add(paragraph); } /** * 添加下劃線 */ public Paragraph addUnderLine(Paragraph paragraph,String text){ if (StringUtils.isBlank(text)){ text = shortSpacing; } else { text = StringUtils.join(" ",text," "); } Chunk sigUnderline = new Chunk(text); sigUnderline.setUnderline(0.1f, -2f); paragraph.add(sigUnderline); return paragraph; } /** * 添加下劃線 */ public void addUnderLine(Document document,Paragraph paragraph,String text) throws DocumentException { if (StringUtils.isBlank(text)){ text = shortSpacing; } Chunk sigUnderline = new Chunk(StringUtils.join(" ",text," ")); sigUnderline.setUnderline(0.1f, -2f); paragraph.add(sigUnderline); document.add(paragraph); } /**objStmMark = null * 追加簽名 */ public File mergePdf(String [] files,String savePath){ PdfReader pdfReader = null; Document document = null; try { //創(chuàng)建一個(gè)與a.pdf相同紙張大小的document pdfReader = new PdfReader(files[0]); document = new Document(pdfReader.getPageSize(1)); PdfCopy copy = new PdfCopy(document, new FileOutputStream(savePath)); document.open(); for (int i = 0; i < files.length; i++) { //一個(gè)一個(gè)的遍歷現(xiàn)有的PDF PdfReader reader = new PdfReader(files[i]); int n = reader.getNumberOfPages();//PDF文件總共頁(yè)數(shù) System.out.println("n:"+n); for (int j = 1; j <= n; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } reader.close(); } document.close(); pdfReader.close(); return new File(savePath); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } finally { document.close(); pdfReader.close(); } return null; } /** * 添加下劃線 */ public Paragraph addUnderLine(Boolean check,Paragraph paragraph,String text1,String text2){ Chunk sigUnderline = null; if (check){ if (Objects.isNull(text1)){ text1 = shortSpacing; } else { text1 = StringUtils.join(" ",text1," "); } sigUnderline = new Chunk(text1); } else { if (Objects.isNull(text2)){ text2 = shortSpacing; } else { text2 = StringUtils.join(" ",text2," "); } sigUnderline = new Chunk(text2); } sigUnderline.setUnderline(0.1f, -2f); paragraph.add(sigUnderline); return paragraph; } /** * 添加下劃線 */ public void addUnderLine(Document document,Boolean check,Paragraph paragraph,String text1,String text2) throws DocumentException { Chunk sigUnderline = null; if (check){ if (Objects.isNull(text1)){ text1 = shortSpacing; } else { text1 = StringUtils.join(" ",text1," "); } sigUnderline = new Chunk(text1); } else { if (Objects.isNull(text2)){ text2 = shortSpacing; } else { text2 = StringUtils.join(" ",text2," "); } sigUnderline = new Chunk(text2); } sigUnderline.setUnderline(0.1F, -2.0F); paragraph.add(sigUnderline); document.add(paragraph); } /** * 添加下劃線 Chunk */ public Chunk createUnderLineChunk(String text) { if (Objects.isNull(text)){ text = shortSpacing; } else { text = StringUtils.join(" ",text," "); } Chunk sigUnderline = new Chunk(text); sigUnderline.setUnderline(0.1f, -2f); return sigUnderline; } private Document createDocument() throws IOException { // 1.新建document對(duì)象 建立一個(gè)Document對(duì)象 Document document = new Document(PageSize.A4); // PdfUtils.htFile.createNewFile(); // 3.打開(kāi)文檔 document.open(); document.addTitle("銷售合同");// 標(biāo)題 document.addAuthor("chuz");// 作者 document.addSubject("Subject@iText pdf sample");// 主題 document.addKeywords("Keywords@iTextpdf");// 關(guān)鍵字 document.addCreator("chuz develop");// 創(chuàng)建者 return document; } /** * 添加下劃線 Chunk */ public Chunk createUnderLineChunk(Boolean check,String text1,String text2) throws DocumentException { Chunk sigUnderline = null; if (check){ if (Objects.isNull(text1)){ text1 = shortSpacing; } else { text1 = StringUtils.join(" ",text1," "); } sigUnderline = new Chunk(text1); } else { if (Objects.isNull(text2)){ text2 = shortSpacing; } else { text2 = StringUtils.join(" ",text2," "); } sigUnderline = new Chunk(text2); } sigUnderline.setUnderline(0.1f, -2f); return sigUnderline; } /** * 添加下劃線 Chunk */ public Chunk createChunk(String text) throws DocumentException { if (StringUtils.isBlank(text)){ text = shortSpacing; } text = StringUtils.join(" ",text," "); return new Chunk(text); } /** * 添加帶選擇框文本 */ // public void addCheck(Document document,Boolean check,String text) throws Exception { // Paragraph paragraph = createTextParagraph(""); // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // document.add(paragraph); // } /** * 添加帶選擇框文本 */ // public void addCheck(Paragraph paragraph,Boolean check,String text) throws Exception { // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // } /** * 添加帶選擇框文本 */ // public Paragraph addCheck(Boolean check,String text) throws Exception { // Paragraph paragraph = createTextParagraph(""); // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // return paragraph; // } /** * 添加帶選擇框文本 */ // public Paragraph appendCheck(Paragraph paragraph,Boolean check,String text) throws Exception { // if (check){ // paragraph.add(new Chunk(checkPng,0,0,true)); // } else { // paragraph.add(new Chunk(unCheckPng,0,0,true)); // } // Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont); // paragraph.add(chunk); // return paragraph; // } public void packageDateParagraph(Document document, Paragraph paragraph, Date date) throws DocumentException { if (Objects.nonNull(date)){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); addUnderLine(paragraph,StringUtils.join(year)); paragraph.add("年"); addUnderLine(paragraph,StringUtils.join(month)); paragraph.add("月"); addUnderLine(paragraph,StringUtils.join(day)); paragraph.add("日"); } else { addUnderLine(paragraph,StringUtils.join(shortSlash)); paragraph.add("年"); addUnderLine(paragraph,StringUtils.join(shortSlash)); paragraph.add("月"); addUnderLine(paragraph,StringUtils.join(shortSlash)); paragraph.add("日"); } document.add(paragraph); } public MultipartFile fileToMultipartFile(File file) { FileItem fileItem = createFileItem(file); MultipartFile multipartFile = new CommonsMultipartFile(fileItem); return multipartFile; } public static FileItem createFileItem(File file) { FileItemFactory factory = new DiskFileItemFactory(16, null); FileItem item = factory.createItem("textField", "text/plain", true, file.getName()); int bytesRead = 0; byte[] buffer = new byte[8192]; try { FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream(); while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } return item; } public String precision(BigDecimal number){ if (Objects.nonNull(number)){ return number.setScale(0,BigDecimal.ROUND_DOWN).toString(); } return null; } }
總結(jié)
解決每一個(gè)bug,開(kāi)發(fā)每一個(gè)功能都是對(duì)程序員能力上、心里上的修煉。既然翻不過(guò)浪浪山,那就要適應(yīng)浪浪山。
到此這篇關(guān)于Java用itextpdf導(dǎo)出PDF的文章就介紹到這了,更多相關(guān)Java導(dǎo)出PDF內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringSecurity6自定義JSON登錄的實(shí)現(xiàn)
目前最新版的Spring Boot已經(jīng)到了3.0.5了,隨之而來(lái)Spring Security 目前的版本也到了6.0.2了,Spring Security寫(xiě)法的變化特別多,本文就來(lái)介紹下,感興趣的可以了解一下2023-12-12詳解Spring Cloud Config采用Git存儲(chǔ)時(shí)兩種常用的配置策略
這篇文章主要介紹了詳解Spring Cloud Config采用Git存儲(chǔ)時(shí)兩種常用的配置策略,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07Java簡(jiǎn)單實(shí)現(xiàn)猜數(shù)字游戲附C語(yǔ)言版本
猜數(shù)字是興起于英國(guó)的益智類小游戲,起源于20世紀(jì)中期,一般由兩個(gè)人或多人玩,也可以由一個(gè)人和電腦玩。游戲規(guī)則為一方出數(shù)字,一方猜,今天我們來(lái)用Java和C語(yǔ)言分別把這個(gè)小游戲?qū)懗鰜?lái)練練手2021-11-11Java基于堆結(jié)構(gòu)實(shí)現(xiàn)優(yōu)先隊(duì)列功能示例
這篇文章主要介紹了Java基于堆結(jié)構(gòu)實(shí)現(xiàn)優(yōu)先隊(duì)列功能,結(jié)合實(shí)例形式分析了java優(yōu)先隊(duì)列的簡(jiǎn)單定義與使用方法,需要的朋友可以參考下2017-11-11Jackson2的JsonSchema實(shí)現(xiàn)java實(shí)體類生成json方式
這篇文章主要介紹了Jackson2的JsonSchema實(shí)現(xiàn)java實(shí)體類生成json,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11POI通用導(dǎo)出Excel(.xls,.xlsx)的方法
這篇文章主要介紹了POI通用導(dǎo)出Excel(.xls,.xlsx)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05springboot+dynamicDataSource動(dòng)態(tài)添加切換數(shù)據(jù)源方式
這篇文章主要介紹了springboot+dynamicDataSource動(dòng)態(tài)添加切換數(shù)據(jù)源方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01詳解Java對(duì)象結(jié)構(gòu)與對(duì)象鎖的升級(jí)
這篇文章主要為大家詳細(xì)介紹了Java對(duì)象結(jié)構(gòu)與對(duì)象鎖的升級(jí),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-03-03