日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

SpringBoot+Vue项目的PDF导出及给PDF文件盖章的功能示例

發布時間:2023/12/16 vue 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot+Vue项目的PDF导出及给PDF文件盖章的功能示例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言

版本:
SpringBoot:2.3.1.RELEASE
itextpdf:5.4.3

最近在做SpringBoot+Vue的項目,需要將委托單商品的數據導出為PDF文檔。Java的PDF操作第三方工具類用的最多的應該是itextpdf了吧,當然以前也用過icepdf這種小眾的。那現在就來看看用itextpdf怎么做,還是很簡單的。
首先前端頁面如下,可以導出箱單和發票兩種格式的PDF文件:

一、引入itextpdf依賴
<!--PDF導出--> <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.3</version> </dependency>

只需要這一個包就可以了。網上其他教程引了一大堆包,完全沒必要。

二、主要業務代碼
導出發票
/*** 導出PDF格式發票** @param id* @return io.zbus.transport.Message* @author ZHANGCHAO* @date 2021/1/26 13:42**/public Message exportCommercialInvoiceOfPdf(String id) {Apply apply = baseMapper.selectById(id);if (isEmpty(apply)) {return null;}String tenantId = RequestKit.getRequestIn().getHeader(TENANT_ID);Message res = new Message();RequestKit.copyHeaders(false, TENANT_ID, HEADER_TOKEN, TENANT_TYPE);List<ApplyInvoices> applyInvoicesList = applyInvoicesMapper.selectList(new QueryWrapper<ApplyInvoices>().lambda().eq(ApplyInvoices::getApplyNumber, id).orderByAsc(ApplyInvoices::getSequence));apply.setApplyInvoicesList(applyInvoicesList);// pdf文件名String fileName = "發票_" + (isNotBlank(apply.getInvoiceNo()) ? apply.getInvoiceNo() : "無發票號") + ".pdf";String path = ProjectPath.getExportPdfPath() + File.separator;File file = new File(path);if (!file.exists()) { // 如果文件夾不存在file.mkdir(); // 創建文件夾}String filePath = path + fileName;/*****************創建PDF開始*********************//** 實例化文檔對象 */Document document = new Document(PageSize.A4);log.info("A4的寬度:" + PageSize.A4.getWidth() + "高度:" + PageSize.A4.getHeight());try {/** 創建 PdfWriter 對象 */// 文檔對象的引用// 為document創建一個監聽,并把PDF流寫到文件中PdfWriter.getInstance(document, new FileOutputStream(filePath)); // 文件的輸出路徑+文件的實際名稱document.open();// 打開文檔// // 解決中文不顯示問題 // BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); // // 設置字體大小 // Font fontChina18_BOLD = new Font(bfChinese, 18, Font.BOLD); // Font fontChina12 = new Font(bfChinese, 12); // Font fontChina12_BOLD = new Font(bfChinese, 12, Font.BOLD); // Font fontChina8 = new Font(bfChinese, 8);//加粗 Font.BOLD // Font fontChina8_BOLD = new Font(bfChinese, 8, Font.BOLD); // 加粗 Font.BOLD//英文下字體 // Font fontContent = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD|Font.ITALIC);// 用自己的字體BaseFont bf = BaseFont.createFont(ProjectPath.getFontPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);Font titleFont = new Font(bf, 20, Font.BOLDITALIC); // 24號加粗斜體// 空格代碼Paragraph blank = new Paragraph(" ");/**** 向文檔添加內容 ***/// 標題String title = "";String kehuAddress = "";String kehuTelFax = "";// 境外收發貨人抬頭信息if (isNotBlank(apply.getConsignee())) {Customer customer = orderService.getCustomerByName(apply.getConsignee().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getCustomerAddressList())) {title = getHeaderInfo(customer.getCustomerAddressList());CustomerAddress ca = getAddress(customer.getCustomerAddressList());if (isNotEmpty(ca)) {kehuAddress = ca.getAddress();kehuTelFax = "TEL:" + ca.getPhone() + " FAX:" + ca.getFax();}}}Paragraph titleParagraph = new Paragraph(title, titleFont);document.add(titleParagraph); // 文檔標題document.add(blank);Paragraph addressParagraph = new Paragraph(kehuAddress, new Font(bf, 15, Font.NORMAL));Paragraph telFaxParagraph = new Paragraph(kehuTelFax, new Font(bf, 15, Font.NORMAL));document.add(addressParagraph); // 客戶地址document.add(telFaxParagraph); // 客戶電話+傳真document.add(blank);document.add(blank);document.add(blank);// 畫橫線//1.線寬度//2.直線長度,是個百分百,0-100之間//3.直線顏色//4.直線位置//5.上下移動位置LineSeparator line = new LineSeparator(2f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, 0f);document.add(line); // 畫橫線Paragraph invoiceParagraph = new Paragraph("INVOICE", new Font(bf, 20, Font.BOLD));invoiceParagraph.setSpacingBefore(20);document.add(invoiceParagraph); // invoicedocument.add(blank);Paragraph billTo = new Paragraph("Bill To", new Font(bf, 12, Font.BOLD));document.add(billTo); // billto// 承運商委托單位企業信息String headerInfo = "";String address = "";String telFax = "";if (isNotBlank(apply.getConsignor())) {Customer customer = orderService.getCustomerByName(apply.getConsignor().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getCustomerAddressList())) {headerInfo = getHeaderInfo(customer.getCustomerAddressList());CustomerAddress ca = getAddress(customer.getCustomerAddressList());if (isNotEmpty(ca)) {address = ca.getAddress();telFax = "Tel:" + ca.getPhone() + " Fax:" + ca.getFax();}}}Paragraph headerInfoParagraph = new Paragraph(headerInfo, new Font(bf, 12, Font.NORMAL));headerInfoParagraph.setIndentationRight(PageSize.A4.getWidth() / 2 - 30);Paragraph addressParagraph_ = new Paragraph(address, new Font(bf, 12, Font.NORMAL));Paragraph telFaxParagraph_ = new Paragraph(telFax, new Font(bf, 12, Font.NORMAL));document.add(headerInfoParagraph);document.add(addressParagraph_);document.add(telFaxParagraph_);// 2021/2/1 13:57@ZHANGCHAO 追加/變更/完善:獲取簽名地址!! // if (isNotBlank(apply.getConsignor())) { // Customer customer = orderService.getCustomerByName(apply.getConsignor().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null); // if (isNotEmpty(customer) && isNotEmpty(customer.getAttachmentList())) { // // 獲取已綁定的表單圖片! // List<Attachment> attachments = customer.getAttachmentList().stream() // .filter(attachment -> "0".equals(attachment.getSubType()) // && "1".equals(attachment.getStatus())).collect(Collectors.toList()); // if (isNotEmpty(attachments)) { // Image yinzhang = Image.getInstance(ProjectPath.getImgPath() + attachments.get(0).getPath()); // yinzhang.setAlignment(Image.ALIGN_UNDEFINED); yinzhang.scalePercent(75); // 依照比例縮放 Image類方法: // yinzhang.scaleAbsolute(120, 120); // 將圖像縮放到絕對寬度和絕對高度。 scaleAbsoluteHeight(float newHeight); // 將圖像縮放到絕對高度。 scaleAbsoluteWidth(float newWidth); //將圖像縮放到絕對寬度。 scalePercent(float percent); // 將圖像縮放到一定百分比。 scalePercent(float percentX, float percentY); //將圖像的寬度和高度縮放到一定百分比。 scaleToFit(float fitWidth, float fitHeight); //縮放圖像,使其適合特定的寬度和高度。 yinzhang.scaleToFit(120, 120); // 依照比例縮放 // yinzhang.setSpacingBefore(200); // yinzhang.setIndentationRight(150); // document.add(yinzhang); // } // } // }document.add(blank);// 2021/2/1 14:38@ZHANGCHAO 追加/變更/完善:獲取供應商的簽名章!!// 境外收發貨人抬頭信息if (isNotBlank(apply.getConsignee())) {Customer customer = orderService.getCustomerByName(apply.getConsignee().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getAttachmentList())) {// 獲取已綁定的表單圖片!List<Attachment> attachments = customer.getAttachmentList().stream().filter(attachment -> "0".equals(attachment.getSubType())&& "1".equals(attachment.getStatus())).collect(Collectors.toList());if (isNotEmpty(attachments)) {Image sign = Image.getInstance(ProjectPath.getImgPath() + attachments.get(0).getPath());sign.setAlignment(Image.ALIGN_RIGHT); // sign.scalePercent(75); // 依照比例縮放sign.scaleToFit(120, 120); // 依照比例縮放sign.setIndentationRight(50);document.add(sign);}}}document.add(blank);LineSeparator line1 = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, 0f);document.add(line1); // 畫橫線Paragraph pg = new Paragraph("TERMS OF DELIVERY", new Font(bf, 13, Font.NORMAL));document.add(pg);// 轉化成交方式String transMode = "";if (isNotBlank(apply.getTransMode())) {DictQuery dictQuery = baseMapper.getDictInfo("CJFS", apply.getTransMode());if (isNotEmpty(dictQuery)) {transMode = dictQuery.getText();}}Paragraph transModePG = new Paragraph(transMode, new Font(bf, 13, Font.NORMAL));transModePG.setIndentationLeft(80);document.add(transModePG);Paragraph pg1 = new Paragraph("THIS PROFORMA INVOICE IS NOT ASSIGNABLE OR NEGOTIABLE", new Font(bf, 13, Font.ITALIC));document.add(pg1);Paragraph pg2 = new Paragraph("SUBJECT TO DELIVERY WHEN AVAILABLE AND AT PRICE IN EFFECT AT DATE OF SHIPMENT.", new Font(bf, 13, Font.ITALIC));document.add(pg2);// 處理表格if (isNotEmpty(applyInvoicesList)) {List<String> invoiceList = createInvoiceList(applyInvoicesList);float[] columnWidths = {1.2f, // 件號1.5f, // 英文品名1f, // 數量0.8f, // 單位1.1f, // 幣制1.1f, // 單價1.5f, // 總價}; // 設置表格列寬參數getCiTableList(document, 7, columnWidths, invoiceList, applyInvoicesList, "CI", 100,new Font(bf, 13, Font.BOLD), new Font(bf, 13, Font.NORMAL));}// 關閉文檔document.close();/*****************創建PDF結束*********************/// 2021/2/8 10:53@ZHANGCHAO 追加/變更/完善:設置印章!!boolean flag = false;String targetPath = "";if (isNotBlank(apply.getConsignor())) {Customer customer = orderService.getCustomerByName(apply.getConsignor().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getAttachmentList())) {// 獲取已綁定的表單圖片!List<Attachment> attachments = customer.getAttachmentList().stream().filter(attachment -> "0".equals(attachment.getSubType())&& "1".equals(attachment.getStatus())).collect(Collectors.toList());if (isNotEmpty(attachments)) {// 讀取模板文件targetPath = path + "1-" + fileName;InputStream input = new FileInputStream(filePath);PdfReader reader = new PdfReader(input);PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath));// 獲取操作的頁面PdfContentByte under = stamper.getOverContent(1);Image image = Image.getInstance(ProjectPath.getImgPath() + attachments.get(0).getPath());// 根據域的大小縮放圖片image.scaleToFit(120, 120);// 添加圖片// 獲取關鍵字的坐標List<float[]> positions = PDFUtil.findKeywordPostions(new FileInputStream(filePath), "Bill To");System.out.println("total:" + positions.size());if (isNotEmpty(positions)) {for (float[] position : positions) {System.out.print("pageNum: " + (int) position[0]);System.out.print("\tx: " + position[1]);System.out.println("\ty: " + position[2]);}} // image.setAbsolutePosition(PageSize.A4.getWidth() / 3 - 95, PageSize.A4.getHeight() / 2 + 60);image.setAbsolutePosition(positions.get(0)[1] + 70, positions.get(0)[2] - 120);under.addImage(image);stamper.close();reader.close();flag = true;}}}String contentType = "application/octet-stream";res.setHeader(Http.CONTENT_TYPE, contentType);res.setStatus(RspCode.SUCCESS);// 將文件轉為字節流輸出if (flag) {res.setBody(fileConvertToByteArray(new File(targetPath)));// 刪除文件FileUtil.deleteFile(filePath);FileUtil.deleteFile(targetPath);} else {res.setBody(fileConvertToByteArray(new File(filePath)));// 刪除文件FileUtil.deleteFile(filePath);}return res;} catch (Exception e) {e.printStackTrace();ExceptionUtil.getFullStackTrace(e);}return null;}
導出箱單
/*** 導出PDF格式箱單** @param id* @return io.zbus.transport.Message* @author ZHANGCHAO* @date 2021/1/26 13:43**/public Message exportPackingListOfPdf(String id) {Apply apply = baseMapper.selectById(id);if (isEmpty(apply)) {return null;}String tenantId = RequestKit.getRequestIn().getHeader(TENANT_ID);Message res = new Message();RequestKit.copyHeaders(false, TENANT_ID, HEADER_TOKEN, TENANT_TYPE);List<ApplyInvoices> applyInvoicesList = applyInvoicesMapper.selectList(new QueryWrapper<ApplyInvoices>().lambda().eq(ApplyInvoices::getApplyNumber, id).orderByAsc(ApplyInvoices::getSequence));apply.setApplyInvoicesList(applyInvoicesList);// pdf文件名String fileName = "箱單_" + (isNotBlank(apply.getInvoiceNo()) ? apply.getInvoiceNo() : "無發票號") + ".pdf";String path = ProjectPath.getExportPdfPath() + File.separator;File file = new File(path);if (!file.exists()) { // 如果文件夾不存在file.mkdir(); // 創建文件夾}String filePath = path + fileName;/*****************創建PDF開始*********************//** 實例化文檔對象 */Document document = new Document(PageSize.A4);log.info("A4的寬度:" + PageSize.A4.getWidth() + "高度:" + PageSize.A4.getHeight());try {/** 創建 PdfWriter 對象 */// 文檔對象的引用// 為document創建一個監聽,并把PDF流寫到文件中PdfWriter.getInstance(document, new FileOutputStream(filePath)); // 文件的輸出路徑+文件的實際名稱document.open();// 打開文檔// 用自己的字體BaseFont bf = BaseFont.createFont(ProjectPath.getFontPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);Font titleFont = new Font(bf, 20, Font.BOLDITALIC); // 24號加粗斜體// 空格代碼Paragraph blank = new Paragraph(" ");/**** 向文檔添加內容 ***/// 標題String title = "";String kehuAddress = "";String kehuTelFax = "";// 境外收發貨人抬頭信息if (isNotBlank(apply.getConsignee())) {Customer customer = orderService.getCustomerByName(apply.getConsignee().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getCustomerAddressList())) {title = getHeaderInfo(customer.getCustomerAddressList());CustomerAddress ca = getAddress(customer.getCustomerAddressList());if (isNotEmpty(ca)) {kehuAddress = ca.getAddress();kehuTelFax = "TEL:" + ca.getPhone() + " FAX:" + ca.getFax();}}}Paragraph titleParagraph = new Paragraph(title, titleFont);document.add(titleParagraph); // 文檔標題document.add(blank);Paragraph addressParagraph = new Paragraph(kehuAddress, new Font(bf, 15, Font.NORMAL));Paragraph telFaxParagraph = new Paragraph(kehuTelFax, new Font(bf, 15, Font.NORMAL));document.add(addressParagraph); // 客戶地址document.add(telFaxParagraph); // 客戶電話+傳真document.add(blank);document.add(blank);Paragraph invoiceParagraph = new Paragraph("Packing list", new Font(bf, 20, Font.BOLD));invoiceParagraph.setSpacingBefore(20);document.add(invoiceParagraph); // invoicedocument.add(blank);// 2021/2/1 13:57@ZHANGCHAO 追加/變更/完善:獲取簽名地址!! // if (isNotBlank(apply.getConsignor())) { // Customer customer = orderService.getCustomerByName(apply.getConsignor().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null); // if (isNotEmpty(customer) && isNotEmpty(customer.getAttachmentList())) { // // 獲取已綁定的表單圖片! // List<Attachment> attachments = customer.getAttachmentList().stream() // .filter(attachment -> "0".equals(attachment.getSubType()) // && "1".equals(attachment.getStatus())).collect(Collectors.toList()); // if (isNotEmpty(attachments)) { // Image yinzhang = Image.getInstance(ProjectPath.getImgPath() + attachments.get(0).getPath()); // yinzhang.setAlignment(Image.ALIGN_UNDEFINED); // yinzhang.scalePercent(75); // 依照比例縮放 // yinzhang.setIndentationRight(150); // document.add(yinzhang); // } // } // }Paragraph billTo = new Paragraph("Bill To", new Font(bf, 12, Font.BOLD));document.add(billTo); // billto// 承運商委托單位企業信息String headerInfo = "";String address = "";String telFax = "";if (isNotBlank(apply.getConsignor())) {Customer customer = orderService.getCustomerByName(apply.getConsignor().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getCustomerAddressList())) {headerInfo = getHeaderInfo(customer.getCustomerAddressList());CustomerAddress ca = getAddress(customer.getCustomerAddressList());if (isNotEmpty(ca)) {address = ca.getAddress();telFax = "Tel:" + ca.getPhone() + " Fax:" + ca.getFax();}}}Paragraph headerInfoParagraph = new Paragraph(headerInfo, new Font(bf, 12, Font.NORMAL));headerInfoParagraph.setIndentationRight(PageSize.A4.getWidth() / 2 - 30);Paragraph addressParagraph_ = new Paragraph(address, new Font(bf, 12, Font.NORMAL));Paragraph telFaxParagraph_ = new Paragraph(telFax, new Font(bf, 12, Font.NORMAL));document.add(headerInfoParagraph);document.add(addressParagraph_);document.add(telFaxParagraph_);document.add(blank);// 2021/2/1 14:38@ZHANGCHAO 追加/變更/完善:獲取供應商的簽名章!!// 境外收發貨人抬頭信息if (isNotBlank(apply.getConsignee())) {Customer customer = orderService.getCustomerByName(apply.getConsignee().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getAttachmentList())) {// 獲取已綁定的表單圖片!List<Attachment> attachments = customer.getAttachmentList().stream().filter(attachment -> "0".equals(attachment.getSubType())&& "1".equals(attachment.getStatus())).collect(Collectors.toList());if (isNotEmpty(attachments)) {Image sign = Image.getInstance(ProjectPath.getImgPath() + attachments.get(0).getPath());sign.setAlignment(Image.ALIGN_RIGHT); // sign.scalePercent(75); // 依照比例縮放sign.scaleToFit(120, 120); // 依照比例縮放sign.setIndentationRight(50);document.add(sign);}}}document.add(blank);// 處理表格if (isNotEmpty(applyInvoicesList)) {PdfPTable table = new PdfPTable(6);// 設置列數table.setSpacingBefore(20);table.setWidthPercentage(100);// 表格寬度為100%float[] columnWidths = {1.5f, // 件號1.5f, // 英文品名1.1f, // 數量1.2f, // 凈重1.3f, // 毛重1.3f, // 包裝數}; // 設置表格列寬參數table.setWidths(columnWidths);/*表頭*/getPlTableList(table, apply, new Font(bf, 13, Font.BOLD), new Font(bf, 13, Font.NORMAL));document.add(table);document.add(blank);}String lastStr = "";String packStr = "";if (isNotBlank(apply.getPacksKinds())) {DictQuery dictQuery = baseMapper.getDictInfo("BZZL", apply.getPacksKinds());if (isNotEmpty(dictQuery)) {packStr = dictQuery.getTable();}}lastStr = "TOTAL ON " + apply.getPacks() + " " + (isNotBlank(packStr) ? packStr : "");Paragraph last = new Paragraph(lastStr, new Font(bf, 12, Font.BOLD));document.add(last); // billto// 關閉文檔document.close();/*****************創建PDF結束*********************/// 2021/2/8 10:54@ZHANGCHAO 追加/變更/完善:設置印章!!boolean flag = false;String targetPath = "";if (isNotBlank(apply.getConsignor())) {Customer customer = orderService.getCustomerByName(apply.getConsignor().trim(), tenantId, isNotEmpty(apply.getConsignorId()) ? apply.getConsignorId().toString() : null);if (isNotEmpty(customer) && isNotEmpty(customer.getAttachmentList())) {// 獲取已綁定的表單圖片!List<Attachment> attachments = customer.getAttachmentList().stream().filter(attachment -> "0".equals(attachment.getSubType())&& "1".equals(attachment.getStatus())).collect(Collectors.toList());if (isNotEmpty(attachments)) {// 讀取模板文件targetPath = path + "1-" + fileName;InputStream input = new FileInputStream(filePath);PdfReader reader = new PdfReader(input);PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath));// 獲取操作的頁面PdfContentByte under = stamper.getOverContent(1);Image image = Image.getInstance(ProjectPath.getImgPath() + attachments.get(0).getPath());// 根據域的大小縮放圖片image.scaleToFit(120, 120);// 添加圖片// 獲取關鍵字的坐標List<float[]> positions = PDFUtil.findKeywordPostions(new FileInputStream(filePath), "Bill To");System.out.println("total:" + positions.size());if (isNotEmpty(positions)) {for (float[] position : positions) {System.out.print("pageNum: " + (int) position[0]);System.out.print("\tx: " + position[1]);System.out.println("\ty: " + position[2]);}} // image.setAbsolutePosition(PageSize.A4.getWidth() / 3 - 95, PageSize.A4.getHeight() / 2 + 60);image.setAbsolutePosition(positions.get(0)[1] + 70, positions.get(0)[2] - 120);under.addImage(image);stamper.close();reader.close();flag = true;}}}String contentType = "application/octet-stream";res.setHeader(Http.CONTENT_TYPE, contentType);res.setStatus(RspCode.SUCCESS);// 將文件轉為字節流輸出if (flag) {res.setBody(fileConvertToByteArray(new File(targetPath)));// 刪除文件FileUtil.deleteFile(filePath);FileUtil.deleteFile(targetPath);} else {res.setBody(fileConvertToByteArray(new File(filePath)));// 刪除文件FileUtil.deleteFile(filePath);}return res;} catch (Exception e) {e.printStackTrace();}return null;} }
其他一些方法:
/*** 把一個文件轉化為byte字節數組。** @return*/private byte[] fileConvertToByteArray(File file) {byte[] data = null;try {FileInputStream fis = new FileInputStream(file);ByteArrayOutputStream bos = new ByteArrayOutputStream();int len;byte[] buffer = new byte[1024];while ((len = fis.read(buffer)) != -1) {bos.write(buffer, 0, len);}data = bos.toByteArray();fis.close();bos.close();} catch (Exception e) {e.printStackTrace();}return data;}/*** 按一定規則獲取客戶抬頭信息* <p>* 委托單導出箱單發票,獲取標簽為1 的地址聯系人。(如果找不到取0通用地址,如果沒有則取默認地址,如果沒有默認取第一條)** @param customerAddressList* @return java.lang.String* @author ZHANGCHAO* @date 2021/1/19 9:33**/private String getHeaderInfo(List<CustomerAddress> customerAddressList) {String headerInfo;// 1.取對應List<CustomerAddress> duiyings = customerAddressList.stream().filter(customerAddress -> "1".equals(customerAddress.getType())).collect(Collectors.toList());if (isNotEmpty(duiyings)) {headerInfo = duiyings.get(0).getHeaderInfo();} else {// 2.取通用List<CustomerAddress> tongyongs = customerAddressList.stream().filter(customerAddress -> "0".equals(customerAddress.getType())).collect(Collectors.toList());if (isNotEmpty(tongyongs)) {headerInfo = tongyongs.get(0).getHeaderInfo();} else {// 3.取默認List<CustomerAddress> morens = customerAddressList.stream().filter(CustomerAddress::getIsDefault).collect(Collectors.toList());if (isNotEmpty(morens)) {headerInfo = morens.get(0).getHeaderInfo();} else {// 4.取第一條headerInfo = customerAddressList.get(0).getHeaderInfo();}}}return headerInfo;}/*** 按一定規則獲取客戶地址信息* <p>* 委托單導出箱單發票,獲取標簽為1 的地址聯系人。(如果找不到取0通用地址,如果沒有則取默認地址,如果沒有默認取第一條)** @param customerAddressList* @return java.lang.String* @author ZHANGCHAO* @date 2021/1/19 9:33**/private CustomerAddress getAddress(List<CustomerAddress> customerAddressList) {CustomerAddress ca;// 1.取對應List<CustomerAddress> duiyings = customerAddressList.stream().filter(customerAddress -> "1".equals(customerAddress.getType())).collect(Collectors.toList());if (isNotEmpty(duiyings)) {ca = duiyings.get(0);} else {// 2.取通用List<CustomerAddress> tongyongs = customerAddressList.stream().filter(customerAddress -> "0".equals(customerAddress.getType())).collect(Collectors.toList());if (isNotEmpty(tongyongs)) {ca = tongyongs.get(0);} else {// 3.取默認List<CustomerAddress> morens = customerAddressList.stream().filter(CustomerAddress::getIsDefault).collect(Collectors.toList());if (isNotEmpty(morens)) {ca = morens.get(0);} else {// 4.取第一條ca = customerAddressList.get(0);}}}return ca;}

主要思路是先根據委托單的流水號,查詢出其下的商品數據,然后寫入生成的PDF文件中。再讀取生成的PDF文件,根據關鍵字“Bill To”的坐標插入印章,最后轉為字節流輸出給前端下載。

1. 處理商品數據的createInvoiceList方法:
/*** 處理商品數據** @param applyInvoicesList* @return java.util.List<java.lang.String>* @author ZHANGCHAO* @date 2021/1/27 15:28**/public static List<String> createInvoiceList(List<ApplyInvoices> applyInvoicesList) {List<String> invoiceList = new ArrayList<>();/****標題行****/invoiceList.add("Part No.");invoiceList.add("DESCRIPTION");invoiceList.add("QTY.");invoiceList.add("UNIT");invoiceList.add("CURRENCY");invoiceList.add("Unit price");invoiceList.add("AMOUNT");/****每行的值****/applyInvoicesList.forEach(applyInvoices -> {invoiceList.add(isNotBlank(applyInvoices.getPn()) ? applyInvoices.getPn() : null); // 件號物料號invoiceList.add(isNotBlank(applyInvoices.getEnName()) ? applyInvoices.getEnName() : null); // 英文品名invoiceList.add(isNotEmpty(applyInvoices.getQty()) ? applyInvoices.getQty().toString() : null); // 數量invoiceList.add(isNotBlank(applyInvoices.getQunit()) ? applyInvoices.getQunit() : null); // 單位invoiceList.add(isNotBlank(applyInvoices.getCurrency()) ? applyInvoices.getCurrency() : null); // 幣制invoiceList.add(isNotEmpty(applyInvoices.getDcluprcamt()) ? applyInvoices.getDcluprcamt().toString() : null); // 單價invoiceList.add(isNotEmpty(applyInvoices.getValue()) ? applyInvoices.getValue().toString() : null); // 總價});return invoiceList;}
2. 獲取表格數據getCiTableList方法代碼:
/*** 創建表格** @param document* @param colspan* @param columnWidths* @param list* @param widthPercentage* @param headFont* @param childFont* @return void* @author ZHANGCHAO* @date 2021/1/27 15:44**/public static void getCiTableList(Document document, int colspan, float[] columnWidths, List<String> list,List<ApplyInvoices> applyInvoices, String type,float widthPercentage, Font headFont, Font childFont) throws DocumentException {PdfPTable table = new PdfPTable(colspan);// 設置列數table.setSpacingBefore(20);table.setWidthPercentage(widthPercentage);// 表格寬度為100%if (columnWidths != null) {//自定義列寬table.setWidths(columnWidths);}int number = 0;//設置打印行數for (int i = 0; i < list.size() / colspan; i++) {//打印條數 = 數據個數除以列數//每行每列生成一個單元格for (int j = 0; j < colspan; j++) { //打印列數PdfPCell cell = new PdfPCell(); //創建單元格cell.setMinimumHeight(30F);//表格高度cell.setUseAscender(true);cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中if (i == 0) {//第一行標題欄cell.setPhrase(new Paragraph(list.get(number), headFont));} else {cell.setPhrase(new Paragraph(list.get(number), childFont));}table.addCell(cell);number++;}}// 處理最后一行if ("CI".equalsIgnoreCase(type)) {BigDecimal totalQty = new BigDecimal("0");BigDecimal totalAmount = new BigDecimal("0");for (ApplyInvoices a : applyInvoices) {totalQty = totalQty.add(isNotEmpty(a.getQty()) ? a.getQty() : new BigDecimal("0"));totalAmount = totalAmount.add(isNotEmpty(a.getValue()) ? a.getValue() : new BigDecimal("0"));}PdfPCell cell = new PdfPCell(); //創建單元格cell.setMinimumHeight(30F);//表格高度cell.setColspan(2);cell.setUseAscender(true); //開啟單元格內文字位置設計cell.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell.setPhrase(new Paragraph("TOTAL", headFont));table.addCell(cell);PdfPCell cell1 = new PdfPCell(); //創建單元格cell1.setMinimumHeight(30F);//表格高度cell1.setUseAscender(true); //開啟單元格內文字位置設計cell1.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell1.setPhrase(new Paragraph(totalQty.toString(), headFont));table.addCell(cell1);PdfPCell cell2 = new PdfPCell(); //創建單元格cell2.setMinimumHeight(30F);//表格高度cell2.setUseAscender(true); //開啟單元格內文字位置設計cell2.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell2.setPhrase(new Paragraph("", headFont));table.addCell(cell2);PdfPCell cell3 = new PdfPCell(); //創建單元格cell3.setMinimumHeight(30F);//表格高度cell3.setUseAscender(true); //開啟單元格內文字位置設計cell3.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell3.setPhrase(new Paragraph("", headFont));table.addCell(cell3);PdfPCell cell4 = new PdfPCell(); //創建單元格cell4.setMinimumHeight(30F);//表格高度cell4.setUseAscender(true); //開啟單元格內文字位置設計cell4.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell4.setPhrase(new Paragraph("", headFont));table.addCell(cell4);PdfPCell cell5 = new PdfPCell(); //創建單元格cell5.setMinimumHeight(30F);//表格高度cell5.setUseAscender(true); //開啟單元格內文字位置設計cell5.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell5.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell5.setPhrase(new Paragraph(totalAmount.toString(), headFont));table.addCell(cell5);}document.add(table);}
3. 注意:箱單的話需要縱向合并單元格,而itextpdf的縱向合并簡直是殘廢,這里需要單獨處理下:
/*** 創建箱單表格** @param table* @param apply* @param headFont* @param childFont* @return void* @author ZHANGCHAO* @date 2021/1/28 10:53**/public static void getPlTableList(PdfPTable table, Apply apply, Font headFont, Font childFont) {PdfPCell cell = new PdfPCell(); //創建單元格cell.setMinimumHeight(30F);//表格高度cell.setUseAscender(true); //開啟單元格內文字位置設計cell.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell.setPhrase(new Paragraph("Part No.", headFont));table.addCell(cell);PdfPCell cell1 = new PdfPCell(); //創建單元格cell1.setMinimumHeight(30F);//表格高度cell1.setUseAscender(true); //開啟單元格內文字位置設計cell1.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell1.setPhrase(new Paragraph("DESCRIPTION", headFont));table.addCell(cell1);PdfPCell cell2 = new PdfPCell(); //創建單元格cell2.setMinimumHeight(30F);//表格高度cell2.setUseAscender(true); //開啟單元格內文字位置設計cell2.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell2.setPhrase(new Paragraph("QTY.", headFont));table.addCell(cell2);PdfPCell cell3 = new PdfPCell(); //創建單元格cell3.setMinimumHeight(30F);//表格高度cell3.setUseAscender(true); //開啟單元格內文字位置設計cell3.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell3.setPhrase(new Paragraph("N.WT(Kg)", headFont));table.addCell(cell3);PdfPCell cell4 = new PdfPCell(); //創建單元格cell4.setMinimumHeight(30F);//表格高度cell4.setUseAscender(true); //開啟單元格內文字位置設計cell4.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell4.setPhrase(new Paragraph("G.WT(Kg)", headFont));table.addCell(cell4);PdfPCell cell5 = new PdfPCell(); //創建單元格cell5.setMinimumHeight(30F);//表格高度cell5.setUseAscender(true); //開啟單元格內文字位置設計cell5.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cell5.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cell5.setPhrase(new Paragraph("Package", headFont));table.addCell(cell5);/****每行的值****/List<String> invoiceList = new ArrayList<>();apply.getApplyInvoicesList().forEach(applyInvoices -> {invoiceList.add(isNotBlank(applyInvoices.getPn()) ? applyInvoices.getPn() : null); // 件號物料號invoiceList.add(isNotBlank(applyInvoices.getEnName()) ? applyInvoices.getEnName() : null); // 英文品名invoiceList.add(isNotEmpty(applyInvoices.getQty()) ? applyInvoices.getQty().toString() : null); // 數量invoiceList.add(isNotEmpty(applyInvoices.getWeight()) ? applyInvoices.getWeight().toString() : null); // 凈重invoiceList.add(isNotEmpty(apply.getGrosswt()) ? apply.getGrosswt().toString() : null); // 毛重invoiceList.add(isNotEmpty(apply.getPacks()) ? apply.getPacks().toString() + " CASES" : null); // 總價});log.info("invoiceList==> " + invoiceList);int line = 0;for (int i = 0; i < invoiceList.size() / 6; i++) {for (int j = 0; j < 6; j++) {PdfPCell cell_ = new PdfPCell(); //創建單元格cell_.setMinimumHeight(30F);//表格高度cell_.setUseAscender(true);cell_.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中cell_.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中if (i == 0) {if (j == 4 || j == 5) {cell_.setRowspan(apply.getApplyInvoicesList().size());String value = invoiceList.get(line);cell_.setPhrase(new Paragraph(value, childFont));table.addCell(cell_);}}if (j != 4 && j != 5) {cell_.setPhrase(new Paragraph(invoiceList.get(line), childFont));table.addCell(cell_);}line++;}}// 處理最后一行BigDecimal totalQty = new BigDecimal("0");BigDecimal totalWeight = new BigDecimal("0");for (ApplyInvoices a : apply.getApplyInvoicesList()) {totalQty = totalQty.add(isNotEmpty(a.getQty()) ? a.getQty() : new BigDecimal("0"));totalWeight = totalWeight.add(isNotEmpty(a.getWeight()) ? a.getWeight() : new BigDecimal("0"));}PdfPCell cellLast = new PdfPCell(); //創建單元格cellLast.setMinimumHeight(30F);//表格高度cellLast.setColspan(2);cellLast.setUseAscender(true); //開啟單元格內文字位置設計cellLast.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cellLast.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cellLast.setPhrase(new Paragraph("TOTAL", headFont));table.addCell(cellLast);PdfPCell cellLast1 = new PdfPCell(); //創建單元格cellLast1.setMinimumHeight(30F);//表格高度cellLast1.setUseAscender(true); //開啟單元格內文字位置設計cellLast1.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cellLast1.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cellLast1.setPhrase(new Paragraph(totalQty.toString(), headFont));table.addCell(cellLast1);PdfPCell cellLast2 = new PdfPCell(); //創建單元格cellLast2.setMinimumHeight(30F);//表格高度cellLast2.setUseAscender(true); //開啟單元格內文字位置設計cellLast2.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cellLast2.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cellLast2.setPhrase(new Paragraph(totalWeight.toString(), headFont));table.addCell(cellLast2);PdfPCell cellLast3 = new PdfPCell(); //創建單元格cellLast3.setMinimumHeight(30F);//表格高度cellLast3.setUseAscender(true); //開啟單元格內文字位置設計cellLast3.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cellLast3.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cellLast3.setPhrase(new Paragraph(isNotEmpty(apply.getGrosswt()) ? apply.getGrosswt().toString() : "", headFont));table.addCell(cellLast3);PdfPCell cellLast4 = new PdfPCell(); //創建單元格cellLast4.setMinimumHeight(30F);//表格高度cellLast4.setUseAscender(true); //開啟單元格內文字位置設計cellLast4.setHorizontalAlignment(Element.ALIGN_CENTER); //設置單元格的水平居中cellLast4.setVerticalAlignment(Element.ALIGN_MIDDLE); //設置單元格的垂直居中cellLast4.setPhrase(new Paragraph(isNotEmpty(apply.getPacks()) ? apply.getPacks().toString() + " CASES" : null, headFont));table.addCell(cellLast4);}
三、測試
1. 導出的發票如下:

2. 導出的箱單如下:


總的來說用itextpdf導出PDF還是很簡單的,需要其他功能可以自己研究。

以上!

總結

以上是生活随笔為你收集整理的SpringBoot+Vue项目的PDF导出及给PDF文件盖章的功能示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。