2021-03-08-java-pdf导出-lowagie
生活随笔
收集整理的這篇文章主要介紹了
2021-03-08-java-pdf导出-lowagie
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用到的包引入
<dependency><groupId>com.lowagie</groupId><artifactId>itext</artifactId><version>2.1.7</version> </dependency>調用:
/*** @param grInfo 收料* @param list 排期* @param isPurchaseOrder 是否顯示采購訂單號* @param os 流OutputStream*/ ExportPdf.exportGrPdf(grInfo, list, imgByteList, isPurchaseOrder, os);實現代碼:
package com.sgm.msm.util;import com.hgcc.hdf.wf.exception.BadArgumentException; import com.hgcc.htools.time.DateUtil; import com.lowagie.text.Font; import com.lowagie.text.Image; import com.lowagie.text.Rectangle; import com.lowagie.text.*; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import com.sgm.msm.constants.MsmConstants; import com.sgm.msm.domain.gr.TmGrInfo; import com.sgm.msm.domain.sp.SpInfo; import com.sgm.msm.service.FileService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component;import java.awt.*; import java.io.*; import java.util.ArrayList; import java.util.List;@Slf4j @Component public class ExportPdf {// 導出文件名稱private static final String fileName = "排期收料明細清單.pdf";// 靜態調用private static FileService fileService;public ExportPdf(FileService fileService) {this.fileService = fileService;}/*** 生成pdf文件,下載到本地* @param grInfo 收料* @param list 排期* @param imgByteList 圖片字節組* @param isPurchaseOrder 是否顯示采購訂單號* @param os 流*/public static void exportGrPdf(TmGrInfo grInfo, List<SpInfo> list, List<byte[]> imgByteList,boolean isPurchaseOrder, OutputStream os) {// 創建一個文檔對象紙張大小為A4Rectangle rectangle = new Rectangle(842, 595);Document doc = new Document(rectangle);// 邊框距離:左, 下, 右, 上doc.setMargins(20, 20, 20, 20);// 設置要輸出到磁盤上的文件路徑String path = "templates/exportPdf";PdfWriter writer;File file = new File(path);// 判斷是否存在文件夾,不存在則創建if (!file.exists()) {boolean mkdirs = file.mkdirs();if(!mkdirs) {log.info("文件夾創建失敗!");throw new BadArgumentException("文件夾創建失敗!");}}// 創建文件try(FileOutputStream fos = new FileOutputStream(path + "/" + fileName)) {writer = PdfWriter.getInstance(doc, fos);doc.open();// 表格生成填充數據pafTable(grInfo, doc, list, imgByteList, isPurchaseOrder);doc.close();// 關閉文件writer.flush();writer.close();} catch (IOException | DocumentException e) {log.info("文件生成錯誤!");throw new BadArgumentException("文件生成錯誤!");}// 導出到磁盤try(InputStream ins = new BufferedInputStream(new FileInputStream(path + "/" + fileName))) {FileUtil.inToOut(ins, os);} catch (IOException e) {log.info("導出錯誤!");throw new BadArgumentException("導出錯誤!");}}/*** 生成pdf文件,上傳到服務器,返回路徑* @param grInfo 收料* @param list 排期* @param imgByteList 圖片字節組* @param isPurchaseOrder 是否顯示采購訂單號* @param os 流*/public static String exportGrPdf(TmGrInfo grInfo, List<SpInfo> list,List<byte[]> imgByteList, boolean isPurchaseOrder) {// 創建一個文檔對象紙張大小為A4Rectangle rectangle = new Rectangle(842, 595);Document doc = new Document(rectangle);// 邊框距離:左, 下, 右, 上doc.setMargins(20, 20, 20, 20);// 設置要輸出到磁盤上的文件路徑String path = "templates/exportPdf";PdfWriter writer;File file = new File(path);// 判斷是否存在文件夾,不存在則創建if (!file.exists()) {boolean mkdirs = file.mkdirs();if(!mkdirs) {log.info("文件夾創建失敗!");throw new BadArgumentException("文件夾創建失敗!");}}// 創建文件try(FileOutputStream fos = new FileOutputStream(path + "/" + fileName)) {writer = PdfWriter.getInstance(doc, fos);doc.open();// 表格生成填充數據pafTable(grInfo, doc, list, imgByteList, isPurchaseOrder);doc.close();// 關閉文件writer.flush();writer.close();} catch (IOException | DocumentException e) {log.info("文件生成錯誤!");throw new BadArgumentException("文件生成錯誤!");}// 將生成的文件上傳到服務器String filePath = "";try(InputStream ins = new BufferedInputStream(new FileInputStream(path + "/" + fileName))) {byte[] bytes = inputStreamToBytes(ins);// 上傳返回的路徑,上傳方法需自己寫filePath = fileService.singleUpload(fileName, bytes, null, null);} catch (IOException e) {e.printStackTrace();}// 返回文件路徑return filePath;}// 數據填充,每頁數據10條,每張都存在表頭和表尾private static void pafTable(TmGrInfo grInfo, Document doc,List<SpInfo> list, List<byte[]> imgByteList, boolean isPurchaseOrder){// 字體BaseFont bfChinese;try {// 字體設置bfChinese = BaseFont.createFont("fonts/SIMFANG.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);} catch (DocumentException | IOException e) {log.info("獲取字體錯誤!");throw new BadArgumentException("獲取字體錯誤!", e);}Font font = new Font(bfChinese, 10, Font.NORMAL);// 每頁數量int pageSize = 10;int exist = 0;PdfPTable table = null;for(int num=0; num < list.size(); num++){boolean isLast = num == list.size() - 1;// 表頭if(exist == MsmConstants.Number.ZERO) {table = tableHeader(grInfo, font, isPurchaseOrder);}// 中間數據內容,每頁數據10條,每張都存在表頭和表尾tableContent(list.get(num), font, table, num+1);exist += 1;// 表尾if(exist == pageSize || isLast) {tableTail(grInfo, imgByteList, font, table, isLast);try {doc.add(table);} catch (DocumentException e) {log.info("表格寫入錯誤!");throw new BadArgumentException("表格寫入錯誤!");}exist = 0;}}}// 表頭數據填充private static PdfPTable tableHeader(TmGrInfo grInfo, Font font, boolean isPurchaseOrder) {// 行高-正常int height = 25;// 行高-正常int remarkHeight = 12;// 創建一個七列的表格int[] widths = {7, 14, 23, 14, 14, 14, 14};PdfPTable table = new PdfPTable(7);try {table.setWidths(widths);} catch (DocumentException e) {log.info("表格單元格寬度設置錯誤!");throw new BadArgumentException("表格單元格寬度設置錯誤!");}table.setLockedWidth(true);table.setTotalWidth(800);table.setHorizontalAlignment(Element.ALIGN_LEFT);PdfPCell td = cellValueNew("排期收料明細清單\nMaterial receiving list", font, height, Element.ALIGN_CENTER, 7, 1, null);table.addCell(td);PdfPCell td1 = cellValueNew("OP.040.040-2.00 附件", font, remarkHeight, Element.ALIGN_LEFT, 7,1, null);table.addCell(td1);PdfPCell td2 = cellValueNew("*供貨/服務單位\nSupplier", font, height, Element.ALIGN_CENTER, 2, 1, null);PdfPCell td3 = cellValueNew(grInfo.getAgencyName(), font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td4 = cellValueNew("采購訂單號\nPO no.", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td5 = cellValueNew(isPurchaseOrder?grInfo.getPurchaseOrder():"", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td6 = cellValueNew("開口合同號\nContract no.", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td7 = cellValueNew(grInfo.getOpenContract(), font, height, Element.ALIGN_CENTER, 1, 1, null);table.addCell(td2);table.addCell(td3);table.addCell(td4);table.addCell(td5);table.addCell(td6);table.addCell(td7);PdfPCell td8 = cellValueNew("*交貨/完成服務日期\nDate of Delivery", font, height, Element.ALIGN_CENTER, 2, 1, null);String deliveryDate = "";if(grInfo.getDeliveryDate() != null) {deliveryDate = DateUtil.dateToStr(grInfo.getDeliveryDate().toEpochMilli(), MsmConstants.CHECK_DATE_FORMAT_TWO);}PdfPCell td9 = cellValueNew(deliveryDate, font, height, 1, 1, Element.ALIGN_CENTER, null);PdfPCell td10 = cellValueNew("*收料依據描述\nSupporting documents", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td11 = cellValueNew("詳見系統媒體監測記錄", font, height, Element.ALIGN_CENTER,3, 1, null);table.addCell(td8);table.addCell(td9);table.addCell(td10);table.addCell(td11);PdfPCell td12 = cellValueNew("合同約定", font, height, Element.ALIGN_CENTER, 5, 1, null);PdfPCell td13 = cellValueNew("收 料", font, height, Element.ALIGN_CENTER, 2, 1, null);table.addCell(td12);table.addCell(td13);PdfPCell td14 = cellValueNew("序號", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td15 = cellValueNew("*排期編號", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td16 = cellValueNew("*排期名稱", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td17 = cellValueNew("*數量", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td18 = cellValueNew("*單位", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td19 = cellValueNew("本次收料金額", font, height, Element.ALIGN_CENTER, 2, 1, null);table.addCell(td14);table.addCell(td15);table.addCell(td16);table.addCell(td17);table.addCell(td18);table.addCell(td19);PdfPCell td20 = cellValueNew("No.", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td21 = cellValueNew("*Num", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td22 = cellValueNew("*Name", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td23 = cellValueNew("*Qty", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td24 = cellValueNew("*Unit", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td25 = cellValueNew("Receiving Amount", font, height, Element.ALIGN_CENTER, 2, 1, null);table.addCell(td20);table.addCell(td21);table.addCell(td22);table.addCell(td23);table.addCell(td24);table.addCell(td25);return table;}// 填充表格中間數據private static void tableContent(SpInfo spInfo, Font font, PdfPTable table, int orderNum) {// 行高-正常int height = 25;table.addCell(cellValueNew(orderNum, font, height, Element.ALIGN_CENTER, 1, 1, null));table.addCell(cellValueNew(spInfo.getSpInfoCode(), font, height, Element.ALIGN_CENTER, 1, 1, null));table.addCell(cellValueNew(spInfo.getName(), font, height, Element.ALIGN_CENTER, 1, 1, null));table.addCell(cellValueNew(1, font, height, Element.ALIGN_CENTER, 1, 1, null));table.addCell(cellValueNew("個", font, height, Element.ALIGN_CENTER, 1, 1, null));table.addCell(cellValueNew(spInfo.getAmountToBePaid(), font, height, Element.ALIGN_CENTER, 2, 1, null));}// 填充表尾數據private static void tableTail(TmGrInfo grInfo, List<byte[]> imgBytyList, Font font, PdfPTable table, boolean isLast) {// 行高-正常int height = 25;// 行高-圖片int imgHeight = 30;// 行高-正常int remarkHeight = 12;PdfPCell td26 = cellValueNew("**本次收料金額合計 Summary of Receiving Amount", font, 15, Element.ALIGN_CENTER, 5, 1, null);PdfPCell td27 = cellValueNew(isLast?grInfo.getPurchaseOrderAmount():"", font, 15, Element.ALIGN_CENTER, 2, 1, null);table.addCell(td26);table.addCell(td27);PdfPCell td28 = cellValueNew("備注\nRemark", font, height, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td29 = cellValueNew(grInfo.getRemark(), font, height, Element.ALIGN_CENTER, 6, 1, null);table.addCell(td28);table.addCell(td29);PdfPCell td30 = cellValueNew("驗收人\nChecked by", font, height, Element.ALIGN_CENTER, 4, 1, null);PdfPCell td31 = cellValueNew("高級經理\nApproved by Senior Manager", font, 30, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td32 = cellValueNew("科室總監/品牌總監/廠長\nApproved by Director\n( > RMB 400,000)", font, 30, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td33 = cellValueNew("部門負責人/品牌部長/基地總經理\nApproved by Executive Director\n( > RMB 2,000,000)", font, 30, Element.ALIGN_CENTER, 1, 1, null);table.addCell(td30);table.addCell(td31);table.addCell(td32);table.addCell(td33);PdfPCell td37;PdfPCell td34;try {td37 = cellImg(Image.getInstance(imgBytyList.get(imgBytyList.size()-1)), Element.ALIGN_CENTER);List<byte[]> imgBytyRemoveLastList = new ArrayList<>();imgBytyRemoveLastList.addAll(imgBytyList);imgBytyRemoveLastList.remove(imgBytyList.size()-1);List<Image> imageList = new ArrayList<>();for(byte[] imgByte : imgBytyRemoveLastList) {imageList.add(Image.getInstance(imgByte));}// 將圖片寫入單元格td34 = cellImgList(imageList, Element.ALIGN_LEFT);} catch (BadElementException | IOException e) {log.info("簽名錯誤!");throw new BadArgumentException("簽名錯誤!");}PdfPCell td35 = cellValueNew("", font, imgHeight, Element.ALIGN_CENTER, 1, 1, null);PdfPCell td36 = cellValueNew("", font, imgHeight, Element.ALIGN_CENTER, 1, 1, null);table.addCell(td34);table.addCell(td35);table.addCell(td36);table.addCell(td37);PdfPCell td38 = cellValueNew("標注\"*\"符號的欄目屬必填項。The blank with \"*\" must be fill out.", font, remarkHeight, Element.ALIGN_LEFT, 7, 1, null);table.addCell(td38);PdfPCell td39 = cellValueNew("以\"本次收料金額合計\"提交審批. Approval per \"summary of receiving amount\".", font, remarkHeight, Element.ALIGN_LEFT, 7, 1, null);table.addCell(td39);}/*** @param obValue 單元格的填充數據* @param font 字體* @param height 行號* @param alignment 顯示位置* @param colspan 合并列* @param rowspan 合并行* @param colorValue 背景顏色*/private static PdfPCell cellValueNew(Object obValue, Font font, int height,int alignment, int colspan, int rowspan, Color colorValue) {if (obValue == null) {obValue = "";}PdfPCell cellValue = new PdfPCell();font.setSize(6);Paragraph paragraph = new Paragraph(String.valueOf(obValue), font);cellValue.setPhrase(paragraph);// 行高cellValue.setMinimumHeight(height);// 居中顯示cellValue.setHorizontalAlignment(alignment);// 縱向居中顯示cellValue.setVerticalAlignment(Element.ALIGN_MIDDLE);// 合并行cellValue.setRowspan(rowspan);// 合并列cellValue.setColspan(colspan);// 背景顏色cellValue.setBackgroundColor(colorValue);return cellValue;}// 單元格中填充圖片private static PdfPCell cellImgList(List<Image> imgList, int alignment) {// 根據圖片數量計算列數和每列寬度int arrLength = imgList.size()>11?450/imgList.size():imgList.size();int callLength = 100/arrLength;int[] widths = new int[arrLength];for(int i=0; i<arrLength; i++) {widths[i] = callLength;}int totalWidth = arrLength>11?450:arrLength*40;// 因圖片大小可能會將單元格撐大,所以將圖片放到新的PdfPTable中PdfPTable imgTable = new PdfPTable(arrLength);try {imgTable.setWidths(widths);} catch (DocumentException e) {log.info("表格單元格寬度設置錯誤!");throw new BadArgumentException("表格單元格寬度設置錯誤!");}imgTable.setLockedWidth(true);imgTable.setTotalWidth(totalWidth);imgList.forEach(image -> {PdfPCell pd = new PdfPCell(image, true);pd.setVerticalAlignment(Element.ALIGN_MIDDLE);imgTable.addCell(pd);});PdfPCell pdfPCell = new PdfPCell(imgTable);pdfPCell.setColspan(4);pdfPCell.setHorizontalAlignment(alignment);return pdfPCell;}// 每個圖片一個PdfPTable,將其放到PdfPCell 中private static PdfPCell cellImg(Image img, int alignment) {PdfPTable imgTable = new PdfPTable(1);imgTable.setLockedWidth(true);imgTable.setTotalWidth(40);PdfPCell pd = new PdfPCell(img, true);pd.setVerticalAlignment(Element.ALIGN_MIDDLE);imgTable.addCell(pd);PdfPCell pdfPCell = new PdfPCell(imgTable);pdfPCell.setHorizontalAlignment(alignment);return pdfPCell;}// 將流轉成字節組public static byte[] inputStreamToBytes(InputStream in) throws IOException {ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] buff = new byte[100];int rc;while ((rc = in.read(buff, 0, 100)) > 0) {byteArrayOutputStream.write(buff, 0, rc);}return byteArrayOutputStream.toByteArray();} }總結
以上是生活随笔為你收集整理的2021-03-08-java-pdf导出-lowagie的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA单例之我见
- 下一篇: epoll.h 源码记录