亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java利用ITextPdf庫(kù)生成PDF預(yù)覽文件的具體實(shí)現(xiàn)

 更新時(shí)間:2024年04月09日 08:38:11   作者:PunkSerris  
這篇文章主要給大家介紹了Java利用ITextPdf庫(kù)生成PDF預(yù)覽文件的具體實(shí)現(xiàn),文中通過(guò)代碼示例和圖文給大家介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下

背景

其實(shí)公司之前的項(xiàng)目里是用到了帆軟報(bào)表的,然而最近接了一個(gè)新項(xiàng)目,這個(gè)項(xiàng)目獨(dú)立部署在甲方的獨(dú)立環(huán)境中,組長(zhǎng)的意思是不用再單獨(dú)部署一套帆軟報(bào)表,成本太大,用其他方式實(shí)現(xiàn)一下。雖然我不太理解成本大在哪兒,不過(guò)身為助理工程師,別管那么多,照著干就完事了。

之前有其他哥們寫(xiě)過(guò)類(lèi)似功能,通過(guò)解析數(shù)據(jù)動(dòng)態(tài)生成pdf文件。但他用的那個(gè)技術(shù)jasper有點(diǎn)老了,資料不太好找,問(wèn)過(guò)神奇的chatgpt后,了解到iTextPdf這個(gè)庫(kù),應(yīng)該是比較好的選擇。

解決方案

我們先觀察下真實(shí)的開(kāi)票預(yù)覽的模板。

發(fā)票信息由兩部分組成:

  • 固定信息,例如購(gòu)買(mǎi)方信息、銷(xiāo)售方信息。
  • 商品信息,可能有多行,需動(dòng)態(tài)填充

很明顯的一個(gè)主子結(jié)構(gòu)。 了解了一下iTextPdf的相關(guān)api。要實(shí)現(xiàn)這個(gè)功能,其實(shí)我們需要分別生成兩部分的發(fā)票信息,也就是兩個(gè)pdf,然后將兩個(gè)pdf拼接成同一個(gè)。 對(duì)于第一部分的固定信息,我們可以用Acrobat之類(lèi)的pdf設(shè)計(jì)工具設(shè)計(jì)出一個(gè)模板,然后在java程序中讀取并填充對(duì)應(yīng)的模板值。 對(duì)于第二部分的商品信息,就需要獲取商品數(shù)據(jù),動(dòng)態(tài)生成表格,當(dāng)然iTextPdf是支持這一功能的。 分別得到兩部分的pdf之后,再將其合并為同一個(gè)pdf就可以了。

具體實(shí)現(xiàn)

1.引入iTextPdf庫(kù)

在pom文件中添加iTextPdf的對(duì)應(yīng)依賴(lài)。 其中 itext-asian 這個(gè)也是需要的,不然生成的pdf中無(wú)法顯示中文

        <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.編輯對(duì)應(yīng)模板

下載Adobe Acrobat工具,這部分就不細(xì)說(shuō)了 點(diǎn)擊文件-創(chuàng)建-表單。如果你有現(xiàn)成的pdf文件,也可以在這步選擇單一文件開(kāi)始,沒(méi)有的話就從頭新建

通過(guò)放置文字和文字域來(lái)設(shè)計(jì)好表單模板。 注意,文字域“屬性”里的名稱(chēng)就是最后使用iTextPdf填充時(shí)需要填充的對(duì)應(yīng)字段。

3.編寫(xiě)java PDF生成程序

使用框架還是老一套的SpringBoot,但為了方便測(cè)試,不展示最終的成品接口,而是寫(xiě)在一個(gè)可執(zhí)行的主方法里main里。

3.1 讀取PDF模板文件

iTextPdf負(fù)責(zé)讀取文件的Class是PdfReader,支持多種解析方式 可以讀取文件路徑,也支持直接傳入文件的字節(jié)流 線上環(huán)境使用了字節(jié)流的讀取方式。演示的主方法中使用了直接讀取本地文件路徑的方式。

  // 讀取本地文件,當(dāng)然線上環(huán)境肯定不這么寫(xiě)
  PdfReader reader = new PdfReader("C:\\Users\\User\\Desktop\\開(kāi)票預(yù)覽模板.pdf");
  // 線上環(huán)境使用了s3服務(wù)器,會(huì)提前得到字節(jié)流 byte[] bytes
  PdfReader reader = new PdfReader(bytes);

3.2 填寫(xiě)模板文件并生成固定信息的PDF文件

iTextPdf負(fù)責(zé)填充表單字段的Class是PdfStamper Stamper,譯文壓模;母盤(pán);模子;印章 用來(lái)形容把動(dòng)態(tài)數(shù)據(jù)填充進(jìn)已有的表單里,還挺形象的 注意 form.setField("purName","購(gòu)買(mǎi)方對(duì)應(yīng)公司"); 這里設(shè)值的key就是我們?cè)谠O(shè)計(jì)表單時(shí),文字域的名稱(chēng)。

        // 臨時(shí)輸出流-表單
        ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos1);


        // 獲取表單
        AcroFields form = stamper.getAcroFields();
        form.setGenerateAppearances(true);

        // 表單填充
        form.setField("purName","購(gòu)買(mǎi)方對(duì)應(yīng)公司");
        stamper.close();

在實(shí)際的實(shí)現(xiàn)中,這里使用了一個(gè)Map<String,String> map 遍歷所有entrySet,將值通過(guò)setField(entrySet.key(),entrySet.value())方法填充至表單

3.3 動(dòng)態(tài)創(chuàng)建表格并生成商品信息的PDF文件

搞定了第一部分的PDF文件,我們?cè)賮?lái)處理第二部分的PDF文件:生成商品列表。 這里我們需要新建一個(gè)Document,在這個(gè)Document中動(dòng)態(tài)創(chuàng)建一個(gè)表格對(duì)象PdfPTable 最后將Document關(guān)閉。調(diào)用Document.close()時(shí)會(huì)觸發(fā)輸出流ByteArrayOutputStream的更新。 另外還有一個(gè)要點(diǎn)是,如果表格要顯示中文,那么輸出的內(nèi)容格必須設(shè)置中文字體,否則無(wú)法顯示。

我們來(lái)看一下填充一個(gè)最簡(jiǎn)單的Pdf表格是怎么做的

// 最簡(jiǎn)單的示例
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)建一個(gè)新的 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對(duì)象后(需指定列的數(shù)目),通過(guò)調(diào)用Table.addCell()方法添加行數(shù)據(jù)。 Table.addCell()會(huì)自動(dòng)切換行的。假如表有兩列,連續(xù)調(diào)用三個(gè)Table.addCell()方法,第三個(gè)方法就會(huì)自動(dòng)切換到第二行。 知道了這一點(diǎn)后,我們分析一下:對(duì)于表格的某一列,我們至少需要以下兩個(gè)參數(shù):表頭中文名稱(chēng),列的數(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ù)名稱(chēng)","commodityName",80));
        infos.add(new HeadRowMetaInfo("規(guī)格型號(hào)","model",80));
        infos.add(new HeadRowMetaInfo("單位","pushUnitName",80));
        infos.add(new HeadRowMetaInfo("數(shù)量","orderNum",80));
        infos.add(new HeadRowMetaInfo("單價(jià)","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ù)來(lái)看我們的主方法

        // 臨時(shí)文件流-商品
        ByteArrayOutputStream bos2 = new ByteArrayOutputStream();

        // 獲取原頁(yè)面的尺寸和樣式
        Document document = new Document(reader.getPageSize(1));
        PdfWriter writer = PdfWriter.getInstance(document, bos2);

        document.open();
        //新創(chuàng)建一頁(yè)來(lái)存放后面生成的表格
        document.newPage();

        // 獲取商品導(dǎo)出數(shù)據(jù)
        List<Map<String, Object>> mapData = otherService.getData();
        // 全局統(tǒng)一字體,不設(shè)置無(wú)法顯示中文
        // 創(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)閉后才會(huì)觸發(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ì)算表格在頁(yè)面上的位置并添加到頁(yè)面
        // 注意:這里的坐標(biāo)可能需要根據(jù)實(shí)際情況調(diào)整
        table.setLockedWidth(true);
        return table;
    }

3.4 拼接兩個(gè)PDF文件

    public static byte[] copy(List<byte[]> files) throws DocumentException, IOException {
        // 創(chuàng)建文檔對(duì)象
        Document document = new Document();
        // 創(chuàng)建PdfCopy對(duì)象
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(document, bos);
        // 設(shè)置只讀
        copy.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);


        // 打開(kāi)文檔
        document.open();
        PdfReader reader;
        int n;
        // 循環(huán)遍歷所有PDF文件
        for (byte[] file : files) {
            reader = new PdfReader(file);
            // 獲取每個(gè)PDF文件的頁(yè)數(shù)
            n = reader.getNumberOfPages();
            for (int page = 0; page < n; ) {
                // 向PdfCopy添加每一頁(yè)
                copy.addPage(copy.getImportedPage(reader, ++page));
            }
            // 關(guān)閉PdfReader
            reader.close();
        }

        // 關(guān)閉文檔,否則輸出流不會(huì)刷新
        document.close();

        byte[] bytes = bos.toByteArray();

        // 關(guān)閉流
        bos.close();
        return bytes;
    }

3.5 輸出

用于線上環(huán)境的接口,在此處得到了字節(jié)流之后就上傳s3了 在演示用的主函數(shù)里,將字節(jié)流保存為了本地文件

        log.info(returnPath +" pdf模板填充成功,進(jìn)行合并");
        List<byte[]> files = new ArrayList<>();
        files.add(bos1.toByteArray());
        files.add(bos2.toByteArray());
        // 合并兩個(gè)pdf流
        byte[] s3bytes = copy(files);

        // 關(guān)閉流
        bos1.close();
        bos2.close();
        reader.close();

        // 有流之后 可以把流存儲(chǔ)至本地文件,也可以上傳s3了
        String outputPath = "C:\\Users\\User\\Desktop\\test3.pdf";
        FileOutputStream fileOutputStream = new FileOutputStream(outputPath);
        fileOutputStream.write(s3bytes);
        fileOutputStream.close();

賽后總結(jié)

通過(guò)這次的需求學(xué)習(xí)到了JAVA里生成操作pdf文件的方法。 先制作PDF表格模板,設(shè)置文字域,可以處理掉導(dǎo)出數(shù)據(jù)中的固定部分?jǐn)?shù)據(jù) 針對(duì)表格類(lèi)的數(shù)據(jù),長(zhǎng)度不固定,需要通過(guò)生成PDF表格來(lái)進(jìn)行處理。

以上就是Java利用ITextPdf庫(kù)生成PDF預(yù)覽文件的具體實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于Java ITextPdf PDF預(yù)覽文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論