Java利用ITextPdf庫生成PDF預(yù)覽文件的具體實現(xiàn)
背景
其實公司之前的項目里是用到了帆軟報表的,然而最近接了一個新項目,這個項目獨立部署在甲方的獨立環(huán)境中,組長的意思是不用再單獨部署一套帆軟報表,成本太大,用其他方式實現(xiàn)一下。雖然我不太理解成本大在哪兒,不過身為助理工程師,別管那么多,照著干就完事了。
之前有其他哥們寫過類似功能,通過解析數(shù)據(jù)動態(tài)生成pdf文件。但他用的那個技術(shù)jasper有點老了,資料不太好找,問過神奇的chatgpt后,了解到iTextPdf這個庫,應(yīng)該是比較好的選擇。
解決方案
我們先觀察下真實的開票預(yù)覽的模板。
發(fā)票信息由兩部分組成:
- 固定信息,例如購買方信息、銷售方信息。
- 商品信息,可能有多行,需動態(tài)填充
很明顯的一個主子結(jié)構(gòu)。 了解了一下iTextPdf的相關(guān)api。要實現(xiàn)這個功能,其實我們需要分別生成兩部分的發(fā)票信息,也就是兩個pdf,然后將兩個pdf拼接成同一個。 對于第一部分的固定信息,我們可以用Acrobat之類的pdf設(shè)計工具設(shè)計出一個模板,然后在java程序中讀取并填充對應(yīng)的模板值。 對于第二部分的商品信息,就需要獲取商品數(shù)據(jù),動態(tài)生成表格,當然iTextPdf是支持這一功能的。 分別得到兩部分的pdf之后,再將其合并為同一個pdf就可以了。
具體實現(xiàn)
1.引入iTextPdf庫
在pom文件中添加iTextPdf的對應(yīng)依賴。 其中 itext-asian 這個也是需要的,不然生成的pdf中無法顯示中文
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.2</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
2.編輯對應(yīng)模板
下載Adobe Acrobat工具,這部分就不細說了 點擊文件-創(chuàng)建-表單。如果你有現(xiàn)成的pdf文件,也可以在這步選擇單一文件開始,沒有的話就從頭新建
通過放置文字和文字域來設(shè)計好表單模板。 注意,文字域“屬性”里的名稱就是最后使用iTextPdf填充時需要填充的對應(yīng)字段。
3.編寫java PDF生成程序
使用框架還是老一套的SpringBoot,但為了方便測試,不展示最終的成品接口,而是寫在一個可執(zhí)行的主方法里main里。
3.1 讀取PDF模板文件
iTextPdf負責讀取文件的Class是PdfReader,支持多種解析方式 可以讀取文件路徑,也支持直接傳入文件的字節(jié)流 線上環(huán)境使用了字節(jié)流的讀取方式。演示的主方法中使用了直接讀取本地文件路徑的方式。
// 讀取本地文件,當然線上環(huán)境肯定不這么寫 PdfReader reader = new PdfReader("C:\\Users\\User\\Desktop\\開票預(yù)覽模板.pdf"); // 線上環(huán)境使用了s3服務(wù)器,會提前得到字節(jié)流 byte[] bytes PdfReader reader = new PdfReader(bytes);
3.2 填寫模板文件并生成固定信息的PDF文件
iTextPdf負責填充表單字段的Class是PdfStamper Stamper,譯文壓模;母盤;模子;印章 用來形容把動態(tài)數(shù)據(jù)填充進已有的表單里,還挺形象的 注意 form.setField("purName","購買方對應(yīng)公司"); 這里設(shè)值的key就是我們在設(shè)計表單時,文字域的名稱。
// 臨時輸出流-表單 ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(reader, bos1); // 獲取表單 AcroFields form = stamper.getAcroFields(); form.setGenerateAppearances(true); // 表單填充 form.setField("purName","購買方對應(yīng)公司"); stamper.close();
在實際的實現(xiàn)中,這里使用了一個Map<String,String> map 遍歷所有entrySet,將值通過setField(entrySet.key(),entrySet.value())方法填充至表單
3.3 動態(tài)創(chuàng)建表格并生成商品信息的PDF文件
搞定了第一部分的PDF文件,我們再來處理第二部分的PDF文件:生成商品列表。 這里我們需要新建一個Document,在這個Document中動態(tài)創(chuàng)建一個表格對象PdfPTable 最后將Document關(guān)閉。調(diào)用Document.close()時會觸發(fā)輸出流ByteArrayOutputStream的更新。 另外還有一個要點是,如果表格要顯示中文,那么輸出的內(nèi)容格必須設(shè)置中文字體,否則無法顯示。
我們來看一下填充一個最簡單的Pdf表格是怎么做的
// 最簡單的示例 import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileOutputStream; public class AdjustTablePositionInPdf { public static void main(String[] args) { try { // 創(chuàng)建一個新的 PDF 文檔 Document document = new Document(PageSize.A4); PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\Desktop\\adjusted_table_position.pdf")); document.open(); // 添加文本內(nèi)容 document.add(new Paragraph("Test PDF with Table")); // 創(chuàng)建表格 PdfPTable table = new PdfPTable(2); table.addCell("Name"); table.addCell("Age"); table.addCell("Alice"); table.addCell("25"); table.addCell("Bob"); table.addCell("30"); // 設(shè)置表格之前的間距 table.setSpacingBefore(20f); // 設(shè)置表格之后的間距 table.setSpacingAfter(20f); // 設(shè)置表格的總寬度 table.setTotalWidth(300f); // 將表格添加到 PDF document.add(table); document.close(); System.out.println("PDF 文件生成成功!"); } catch (Exception e) { e.printStackTrace(); } } }
聲明PdfPTable對象后(需指定列的數(shù)目),通過調(diào)用Table.addCell()方法添加行數(shù)據(jù)。 Table.addCell()會自動切換行的。假如表有兩列,連續(xù)調(diào)用三個Table.addCell()方法,第三個方法就會自動切換到第二行。 知道了這一點后,我們分析一下:對于表格的某一列,我們至少需要以下兩個參數(shù):表頭中文名稱,列的數(shù)據(jù)映射key
/** * 表頭信息 **/ @Data @AllArgsConstructor public class HeadRowMetaInfo { // 列中文名 private String colName; // 列key private String colKey; // 列寬度 private float width; }
/** * 自定義頭部信息 * @return */ public static List<HeadRowMetaInfo> headInfos(){ List<HeadRowMetaInfo> infos = new ArrayList<>(); infos.add(new HeadRowMetaInfo("貨物或應(yīng)稅勞務(wù)、服務(wù)名稱","commodityName",80)); infos.add(new HeadRowMetaInfo("規(guī)格型號","model",80)); infos.add(new HeadRowMetaInfo("單位","pushUnitName",80)); infos.add(new HeadRowMetaInfo("數(shù)量","orderNum",80)); infos.add(new HeadRowMetaInfo("單價","orderPriceNoTax",80)); infos.add(new HeadRowMetaInfo("不含稅金額","orderAmount",80)); infos.add(new HeadRowMetaInfo("稅額","taxAmt",80)); infos.add(new HeadRowMetaInfo("含稅金額","orderAmountTax",80)); infos.add(new HeadRowMetaInfo("稅率","taxRate",80)); return infos; }
好了,我們繼續(xù)來看我們的主方法
// 臨時文件流-商品 ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); // 獲取原頁面的尺寸和樣式 Document document = new Document(reader.getPageSize(1)); PdfWriter writer = PdfWriter.getInstance(document, bos2); document.open(); //新創(chuàng)建一頁來存放后面生成的表格 document.newPage(); // 獲取商品導(dǎo)出數(shù)據(jù) List<Map<String, Object>> mapData = otherService.getData(); // 全局統(tǒng)一字體,不設(shè)置無法顯示中文 // 創(chuàng)建支持中文的字體 BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false); Font font = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK); PdfPTable table = generatePdfPTable(720f,font,mapData,headInfos()); document.add(table); // 文檔流關(guān)閉 // 關(guān)閉后才會觸發(fā)ByteArrayOutputStream的流更新 document.close(); writer.close();
主方法中聲明的,生成PDF表格的子方法為:
public static PdfPTable generatePdfPTable(float totalWidth, Font font, List<Map<String, Object>> data, List<HeadRowMetaInfo> headRowMetaInfos) throws DocumentException { // 多少列 PdfPTable table = new PdfPTable(headRowMetaInfos.size()); // 表寬度 table.setTotalWidth(totalWidth); // 設(shè)置每列的寬度 List<Float> flist = headRowMetaInfos.stream().map(HeadRowMetaInfo::getWidth).collect(Collectors.toList()); float[] farr = new float[flist.size()]; for(int i = 0;i<flist.size();i++){ farr[i] = flist.get(i); } table.setWidths(farr); Map<Integer,String> indexToKeyMap = new HashMap<>(); // 根據(jù)表頭信息插入表頭 for(int i = 0 ;i < headRowMetaInfos.size();i++){ table.addCell(new Phrase(headRowMetaInfos.get(i).getColName(),font)); indexToKeyMap.put(i,headRowMetaInfos.get(i).getColKey()); } // 添加行數(shù)據(jù) for(Map<String,Object> dataItem:data){ for(int i=0;i<headRowMetaInfos.size();i++){ if(dataItem.get(indexToKeyMap.get(i)) != null){ table.addCell(new Phrase(dataItem.get(indexToKeyMap.get(i)).toString(),font)); }else{ table.addCell("-"); } } } // 計算表格在頁面上的位置并添加到頁面 // 注意:這里的坐標可能需要根據(jù)實際情況調(diào)整 table.setLockedWidth(true); return table; }
3.4 拼接兩個PDF文件
public static byte[] copy(List<byte[]> files) throws DocumentException, IOException { // 創(chuàng)建文檔對象 Document document = new Document(); // 創(chuàng)建PdfCopy對象 ByteArrayOutputStream bos = new ByteArrayOutputStream(); PdfCopy copy = new PdfCopy(document, bos); // 設(shè)置只讀 copy.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128); // 打開文檔 document.open(); PdfReader reader; int n; // 循環(huán)遍歷所有PDF文件 for (byte[] file : files) { reader = new PdfReader(file); // 獲取每個PDF文件的頁數(shù) n = reader.getNumberOfPages(); for (int page = 0; page < n; ) { // 向PdfCopy添加每一頁 copy.addPage(copy.getImportedPage(reader, ++page)); } // 關(guān)閉PdfReader reader.close(); } // 關(guān)閉文檔,否則輸出流不會刷新 document.close(); byte[] bytes = bos.toByteArray(); // 關(guān)閉流 bos.close(); return bytes; }
3.5 輸出
用于線上環(huán)境的接口,在此處得到了字節(jié)流之后就上傳s3了 在演示用的主函數(shù)里,將字節(jié)流保存為了本地文件
log.info(returnPath +" pdf模板填充成功,進行合并"); List<byte[]> files = new ArrayList<>(); files.add(bos1.toByteArray()); files.add(bos2.toByteArray()); // 合并兩個pdf流 byte[] s3bytes = copy(files); // 關(guān)閉流 bos1.close(); bos2.close(); reader.close(); // 有流之后 可以把流存儲至本地文件,也可以上傳s3了 String outputPath = "C:\\Users\\User\\Desktop\\test3.pdf"; FileOutputStream fileOutputStream = new FileOutputStream(outputPath); fileOutputStream.write(s3bytes); fileOutputStream.close();
賽后總結(jié)
通過這次的需求學習到了JAVA里生成操作pdf文件的方法。 先制作PDF表格模板,設(shè)置文字域,可以處理掉導(dǎo)出數(shù)據(jù)中的固定部分數(shù)據(jù) 針對表格類的數(shù)據(jù),長度不固定,需要通過生成PDF表格來進行處理。
以上就是Java利用ITextPdf庫生成PDF預(yù)覽文件的具體實現(xiàn)的詳細內(nèi)容,更多關(guān)于Java ITextPdf PDF預(yù)覽文件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Springboot整合freemarker和相應(yīng)的語法詳解
FreeMarker是一款Spring官方推薦使用的模板引擎。接下來通過本文給大家介紹Springboot整合freemarker和相應(yīng)的語法,感興趣的朋友一起看看吧2021-09-09Eclipse中查看android工程代碼出現(xiàn)"android.jar has no source attachment
這篇文章主要介紹了Eclipse中查看android工程代碼出現(xiàn)"android.jar has no source attachment"的解決方案,需要的朋友可以參考下2016-05-05Spring Boot整合Spring Security的示例代碼
這篇文章主要介紹了Spring Boot整合Spring Security的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04Java應(yīng)用層協(xié)議WebSocket實現(xiàn)消息推送
后端向前端推送消息就需要長連接,首先想到的就是websocket,下面這篇文章主要給大家介紹了關(guān)于java后端+前端使用WebSocket實現(xiàn)消息推送的詳細流程,需要的朋友可以參考下2023-02-02Java多線程中線程的兩種創(chuàng)建方式及比較代碼示例
這篇文章主要介紹了Java多線程中線程的兩種創(chuàng)建方式及比較代碼示例,簡單介紹了線程的概念,并行與并發(fā)等,然后通過實例代碼向大家展示了線程的創(chuàng)建,具有一定參考價值,需要的朋友可以了解下。2017-11-11zuulGateway 通過filter統(tǒng)一修改返回值的操作
這篇文章主要介紹了zuulGateway 通過filter統(tǒng)一修改返回值的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10