自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何利用 Java 在線生成 PDF 文件?看這篇教程就夠了!

開(kāi)發(fā) 前端
itext框架是一個(gè)非常實(shí)用的第三方pdf文件生成庫(kù),尤其是面對(duì)比較簡(jiǎn)單的pdf文件內(nèi)容渲染的時(shí)候,它完全滿足我們的需求。但是對(duì)于那種復(fù)雜的pdf文檔,可能需要我們自己?jiǎn)为?dú)進(jìn)行適配開(kāi)發(fā)。具體的深度玩法,大家可以參閱itext官方API。

一、背景介紹

在實(shí)際的業(yè)務(wù)開(kāi)發(fā)的時(shí)候,研發(fā)人員往往會(huì)碰到很多這樣的一些場(chǎng)景,需要提供相關(guān)的電子憑證信息給用戶,例如網(wǎng)銀/支付寶/微信購(gòu)物支付的電子發(fā)票、訂單的庫(kù)存打印單、各種電子簽署合同等等,以方便用戶查看、打印或者下載。

例如下圖的電子發(fā)票!

圖片

熟悉這塊業(yè)務(wù)的童鞋,一定特別清楚,目前最常用的解決方案是:把相關(guān)的數(shù)據(jù)信息,通過(guò)一些技術(shù)手段生成對(duì)應(yīng)的 PDF 文件,然后返回給用戶,以便預(yù)覽、下載或者打印。

不太熟悉這項(xiàng)技術(shù)的同學(xué),也不用著急,今天我們一起來(lái)詳細(xì)了解一下在線生成 PDF 文件的技術(shù)實(shí)現(xiàn)手段!

二、方案實(shí)踐

在介紹這個(gè)代碼實(shí)踐之前,我們先來(lái)了解一下這個(gè)第三方庫(kù):iText,對(duì),沒(méi)錯(cuò),它就是我們今天的主角。

iText是著名的開(kāi)放源碼站點(diǎn)sourceforge一個(gè)項(xiàng)目,是用于生成PDF文檔的一個(gè)java類庫(kù),通過(guò)iText不僅可以生成PDFrtf的文檔,而且還可以將XML、Html文件轉(zhuǎn)化為PDF文件。

iText目前有兩套版本,分別是iText5iText7。iText5應(yīng)該是網(wǎng)上用的比較多的一個(gè)版本。iText5因?yàn)槭呛芏嚅_(kāi)發(fā)者參與貢獻(xiàn)代碼,因此在一些規(guī)范和設(shè)計(jì)上存在不合理的地方。iText7是后來(lái)官方針對(duì)iText5的重構(gòu),兩個(gè)版本差別還是挺大的。不過(guò)在實(shí)際使用中,一般用到的都比較簡(jiǎn)單的 API,所以不用特別拘泥于使用哪個(gè)版本。

2.1、添加 iText 依賴包

在使用它之前,我們先引人相關(guān)的依賴包!

<dependencies>
    <!-- pdf:start -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.11</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.5.11</version>
    </dependency>
    <!-- 支持中文 -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>
    <!-- 支持css樣式渲染 -->
    <dependency>
        <groupId>org.xhtmlrenderer</groupId>
        <artifactId>flying-saucer-pdf-itext5</artifactId>
        <version>9.1.16</version>
    </dependency>
    <!-- 轉(zhuǎn)換html為標(biāo)準(zhǔn)xhtml包 -->
    <dependency>
        <groupId>net.sf.jtidy</groupId>
        <artifactId>jtidy</artifactId>
        <version>r938</version>
    </dependency>
    <!-- pdf:end -->    
</dependencies>

2.2、簡(jiǎn)單實(shí)現(xiàn)

老規(guī)矩,我們先來(lái)一個(gè)hello world,代碼如下:

public class CreatePDFMainTest {

    public static void main(String[] args) throws Exception {
        Document document = new Document(PageSize.A4);
        //第二步,創(chuàng)建Writer實(shí)例
        PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
        //創(chuàng)建中文字體
        BaseFont bfchinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bfchinese, 12, Font.NORMAL);
        //第三步,打開(kāi)文檔
        document.open();
        //第四步,寫(xiě)入內(nèi)容
        Paragraph paragraph = new Paragraph("hello world", fontChinese);
        document.add(paragraph);
        //第五步,關(guān)閉文檔
        document.close();
    }
}

打開(kāi)hello.pdf文件,內(nèi)容如下!

圖片

2.3、復(fù)雜實(shí)現(xiàn)

在實(shí)際的業(yè)務(wù)開(kāi)發(fā)中,因?yàn)闃I(yè)務(wù)場(chǎng)景非常復(fù)雜,而且變化快,我們往往不會(huì)采用上面介紹的寫(xiě)入內(nèi)容方式來(lái)生成文件,而是采用HTML文件轉(zhuǎn)化為PDF文件。

例如下面這張入庫(kù)單!

圖片

我們應(yīng)該如何快速實(shí)現(xiàn)呢?

首先,我們采用html語(yǔ)言編寫(xiě)一個(gè)入庫(kù)單頁(yè)面,將其命令為printDemo.html,源代碼如下:

<html>
    <head></head>
    <body>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>出庫(kù)單</title>
        <div>
            <div>
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tbody>
                        <tr>
                            <td height="40" colspan="2"><h3 style="font-weight: bold; text-align: center; letter-spacing: 5px; font-size: 24px;">入庫(kù)單</h3></td>
                            <td width="12%" height="20" rowspan="2">
                                <img style="width: 105px;height: 105px;" src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAH0AAAB9AQAAAACn+1GIAAAAqElEQVR42u3VMQ7DMAwDQP6A//8lx24qKRRw0s1yu8Uw4OQGIaHsBHUfLzzwAxCAInoZg6dI9dUUBIOyHEG56CmodAaxwtfbboLTVWpeU9+EDAH37m9CmkTYxDGUE0agMIakk3y4Ut8G37iom02M4bPniHWAtqFDTjjSGLrZvXAOmTnL1124C73r6Yo8Ane61k6eQeVjIM2h482D1RwScrpNjuH5R/0b3s6ZZNyKlt3iAAAAAElFTkSuQmCC" />
                            </td>
                        </tr>
                        <tr>
                            <td width="50%" height="30">操作人:xxx</td>
                            <td width="50%" height="30" colspan="2">創(chuàng)建時(shí)間:2021-09-14 12:00:00</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div style="margin-top: 5px; margin-bottom: 6px; margin-left: 4px"></div>
            <div>
                <table width="100%"
                    style="border-collapse: collapse; border-spacing: 0;border:0px;">
                        <tr style="height: 25px;">
                            <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;"
                             width="10%">序號(hào)</td>
                            <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;"
                             width="30%">商品</td>
                            <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;"
                             width="30%">單位</td>
                            <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;"
                             width="30%">數(shù)量</td>
                        </tr>
                        <tr>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">1</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx沐浴露</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">3</td>
                        </tr>
                        <tr>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">2</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx洗發(fā)水</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">4</td>
                        </tr>
                        <tr>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">3</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx洗衣粉</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">5</td>
                        </tr>
                        <tr>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">4</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">xxx洗面奶</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">箱</td>
                            <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000; border-bottom: 1px solid #000000;">5</td>
                        </tr>
                </table>
            </div>
        </div>
    </body>

</html>

接著,我們將html文件轉(zhuǎn)成PDF文件,源碼如下:

public class CreatePDFMainTest {


    /**
     * 創(chuàng)建PDF文件
     * @param htmlStr
     * @throws Exception
     */
    private static void writeToOutputStreamAsPDF(String htmlStr) throws Exception {
        String targetFile = "pdfDemo.pdf";
        File targeFile = new File(targetFile);
        if(targeFile.exists()) {
            targeFile.delete();
        }

        //定義pdf文件尺寸,采用A4橫切
        Document document = new Document(PageSize.A4, 25, 25, 15, 40);// 左、右、上、下間距
        //定義輸出路徑
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(targetFile));
        PdfReportHeaderFooter header = new PdfReportHeaderFooter("", 8, PageSize.A4);
        writer.setPageEvent(header);
        writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
        document.open();

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssAppliers cssAppliers = new CssAppliersImpl(new XMLWorkerFontProvider(){

            @Override
            public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
                try {
                    //用于中文顯示的Provider
                    BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                    returnnew Font(bfChinese, size, style);
                } catch (Exception e) {
                    returnsuper.getFont(fontname, encoding, size, style);
                }
            }
        });

        //html
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        htmlContext.setImageProvider(new AbstractImageProvider() {
            @Override
            public Image retrieve(String src) {
                //支持圖片顯示
                int pos = src.indexOf("base64,");
                try {
                    if (src.startsWith("data") && pos > 0) {
                        byte[] img = Base64.decode(src.substring(pos + 7));
                        return Image.getInstance(img);
                    } elseif (src.startsWith("http")) {
                        return Image.getInstance(src);
                    }
                } catch (BadElementException ex) {
                    returnnull;
                } catch (IOException ex) {
                    returnnull;
                }
                returnnull;
            }

            @Override
            public String getImageRootPath() {
                returnnull;
            }
        });


        // Pipelines
        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.parse(new ByteArrayInputStream(htmlStr.getBytes()));

        document.close();
    }

    /**
     * 讀取 HTML 文件
     * @return
     */
    private static String readHtmlFile() {
        StringBuffer textHtml = new StringBuffer();
        try {
            File file = new File("printDemo.html");
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次讀入一行,直到讀入null為文件結(jié)束
            while ((tempString = reader.readLine()) != null) {
                textHtml.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            returnnull;
        }
        return textHtml.toString();
    }

    public static void main(String[] args) throws Exception {
        //讀取html文件
        String htmlStr = readHtmlFile();
        //將html文件轉(zhuǎn)成PDF
        writeToOutputStreamAsPDF(htmlStr);
    }
}

運(yùn)行程序,打開(kāi)pdfDemo.pdf,結(jié)果如下!

圖片

2.4、變量替換方式

上面的html文件,是我們事先已經(jīng)編輯好的,才能正常渲染。

但是在實(shí)際的業(yè)務(wù)開(kāi)發(fā)的時(shí)候,例如下面的商品內(nèi)容,完全是動(dòng)態(tài)的,還是xxx-202109入庫(kù)單的名稱,以及二維碼,都是動(dòng)態(tài)的。

這個(gè)時(shí)候,我們可以采用freemarker模板引擎,通過(guò)定義變量來(lái)動(dòng)態(tài)填充內(nèi)容,直到轉(zhuǎn)換出來(lái)的結(jié)果就是我們想要的html頁(yè)面。

當(dāng)然,還有一種辦法,例如下面這個(gè),我們也可以在html頁(yè)面里面定義${name}變量,然后在讀取完文件之后,我們將其變量進(jìn)行替換成我們想填充的任何值,這其實(shí)也是模板引擎最核心的一個(gè)玩法。

<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div>您好:${name}</div>
        <div>歡迎,登錄博客網(wǎng)站</div>
    </body>
</html>

三、小結(jié)

itext框架是一個(gè)非常實(shí)用的第三方pdf文件生成庫(kù),尤其是面對(duì)比較簡(jiǎn)單的pdf文件內(nèi)容渲染的時(shí)候,它完全滿足我們的需求。

但是對(duì)于那種復(fù)雜的pdf文檔,可能需要我們自己?jiǎn)为?dú)進(jìn)行適配開(kāi)發(fā)。具體的深度玩法,大家可以參閱itext官方API。

鑒于筆者才疏學(xué)淺,難免會(huì)有理解不到位的地方,歡迎網(wǎng)友批評(píng)指出!

四、參考

1、https://www.cnblogs.com/wangjintao-0623/p/10559877.html

責(zé)任編輯:武曉燕 來(lái)源: 潘志的技術(shù)筆記
相關(guān)推薦

2021-05-07 07:52:51

Java并發(fā)編程

2021-09-30 07:59:06

zookeeper一致性算法CAP

2019-08-16 09:41:56

UDP協(xié)議TCP

2023-11-22 07:54:33

Xargs命令Linux

2022-03-29 08:23:56

項(xiàng)目數(shù)據(jù)SIEM

2024-08-27 11:00:56

單例池緩存bean

2017-03-30 22:41:55

虛擬化操作系統(tǒng)軟件

2021-09-10 13:06:45

HDFS底層Hadoop

2023-09-25 08:32:03

Redis數(shù)據(jù)結(jié)構(gòu)

2023-10-04 00:32:01

數(shù)據(jù)結(jié)構(gòu)Redis

2023-11-07 07:46:02

GatewayKubernetes

2021-07-28 13:29:57

大數(shù)據(jù)PandasCSV

2025-02-03 07:00:00

Java接口工具

2020-10-23 07:43:37

Log配置性能

2019-10-09 10:06:48

容器監(jiān)控軟件

2021-04-11 08:30:40

VRAR虛擬現(xiàn)實(shí)技術(shù)

2018-09-26 11:02:46

微服務(wù)架構(gòu)組件

2021-10-21 06:52:17

ZooKeeper分布式配置

2022-08-18 20:45:30

HTTP協(xié)議數(shù)據(jù)

2023-12-07 09:07:58

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)