【玩轉PDF】賊穩,產品要作一個三方合同簽署,我方了!

1、前言

事情是這個樣子的,小農的公司,以前有個功能須要簽署來進行一系列的操做,因而咱們引入了一個三方平臺的簽署——上上籤,可是有一個比較尷尬的點就是,它不支持合同在瀏覽器上和附件一塊兒預覽的,咱們想要的是須要將附件拼接在合同主文件中一塊兒展現,可是它不支持,因而咱們就開了一個需求會。。。java

產品說,咱們要作一個線上合同簽署的功能,不依靠第三方來完成,能夠瀏覽器上預覽和下載合同,小農,你這邊能作嗎?git

我一聽,這個啊,這個有點難度啊(我須要時間),不太好作,以前咱們接入的第三方就沒有徹底完成瀏覽器預覽的功能,至關於咱們作一個和這個第三方如出一轍的東西,並且還要比它那個兼容更多的功能,不太好作(確實有點不太好作),加上以前也沒有作過,內心沒有底。github

產品說,這個沒有辦法(你作也得作,不作也得作),是領導要求的(上面要求的,你只能作),你看下完成這些功能大概須要多久?web

因而只能硬着頭皮上了,因而給了一個大概的時間後,就開始研究了,什麼是快樂星球,若是你想知道的話,那我就帶你研究,what???等等,跑偏了,回來回來。 在這裏插入圖片描述spring

2、那我就帶你研究

研究什麼?什麼是快樂星球[手動狗頭],咳咳,洗腦了,請你當即中止你的傻*行爲。數據庫

咱們知道,若是是想要操做PDF的話(由於簽署合同通常都是用的PDF,同志們爲大家解疑了,掌聲能夠響起來了),因此通常都是用iText(PDF 操做類庫)操做類庫??? ,咳咳,你怎麼回事? 在這裏插入圖片描述apache

咱們通常都是要使用 Adobe工具設計表單和iText 來進行內容操做,這也是咱們今天須要講解的主體,知道了用什麼,咱們來說一下咱們的需求是什麼?工做後的小夥伴有沒有以爲很可怕,「咱們來說一下需求」,首先須要實現的是 經過PDF模板填充咱們對應的甲乙方基本數據後,生成PDF文件,而後再將數據庫的特定數據拼接在PDF裏面一塊兒,經過甲乙方前後簽署後,而後讓該合同進行生效操做!能夠預覽和下載。數組

要求就是這麼個要求,聽着卻是不難,主要是以前沒有作過,內心不太有譜,可是作完以後,不得不呼本身真是個天才啊,我可真聰明,想起小農從實習的時候就是作的PDF,現在工做這麼久了仍是在作PDF的,真是漂(cao)亮(dan),那就作唄,誰怕誰啊!瀏覽器

3、Adobe工具

工欲善其事必先利其器,首先若是想要填充PDF模板裏面的內容的話,咱們須要使用到Adobe Acrobat Peo DC這個工具tomcat

下載地址:

連接:pan.baidu.com/s/1JdeKr7-a…

提取碼:6h0i

一、打開PDF文件

當咱們下載好Adobe Acrobat Peo DC後,用它打開PDF文件,而後點擊 準備表單 在這裏插入圖片描述

二、添加文本域

點擊添加文本域 在這裏插入圖片描述

三、填寫變量名

這個變量名就是咱們填充數據的參數,要一一對應 在這裏插入圖片描述

四、填寫完成後,以下所示

在這裏插入圖片描述

三、開始安排

別擔憂小夥伴們,項目都給大家準備好了 項目地址:github.com/muxiaonong/…

jar文件:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>layout</artifactId>
            <version>7.1.15</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <!--itext生成word文檔,須要下面dependency-->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>iText-rtf</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
複製代碼

根據PDF模板生成文件和拼接產品的數據

/** * 根據PDF模板生成PDF文件 * @return */
    @GetMapping("generatePdf")
    public String generatePdf() throws Exception{
// File file = ResourceUtils.getFile("classpath:"+SAVE_PATH);
        File pdfFile = new File(ResourceUtils.getURL("classpath:").getPath()+SAVE_PATH);
        try {
            PdfReader pdfReader;
            PdfStamper pdfStamper;
            ByteArrayOutputStream baos;

            Document document = new Document();
//

            PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document,
                    new FileOutputStream(pdfFile));

            document.open();

            File file = ResourceUtils.getFile("classpath:"+templatePath);
            pdfReader = new PdfReader(file.getPath());
            int n = pdfReader.getNumberOfPages();
            log.info("頁數:"+n);
            baos = new ByteArrayOutputStream();
            pdfStamper = new PdfStamper(pdfReader, baos);

            for(int i = 1; i <= n; i++) {
                AcroFields acroFields = pdfStamper.getAcroFields();

                //key statement 1
                acroFields.setGenerateAppearances(true);

                //acroFields.setExtraMargin(5, 5);
                acroFields.setField("customerAddress", "上海市浦東新區田子路520弄1號樓");
                acroFields.setField("customerCompanyName", "上海百度有限公司");
                acroFields.setField("customerName", "張三");
                acroFields.setField("customerPhone", "15216667777");
                acroFields.setField("customerMail", "123456789@sian.com");

                acroFields.setField("vendorAddress", "上海市浦東新區瑟瑟發抖路182號");
                acroFields.setField("vendorCompanyName", "牧小農科技技術有限公司");
                acroFields.setField("vendorName", "王五");
                acroFields.setField("vendorPhone", "15688886666");
                acroFields.setField("vendorMail", "123567@qq.com");

                acroFields.setField("effectiveStartTime", "2021年05月25");
                acroFields.setField("effectiveEndTime", "2022年05月25");

                //true表明生成的PDF文件不可編輯
                pdfStamper.setFormFlattening(true);

                pdfStamper.close();

                pdfReader = new PdfReader(baos.toByteArray());


                pdfSmartCopy.addPage(pdfSmartCopy.getImportedPage(pdfReader, i));
                pdfSmartCopy.freeReader(pdfReader);
                pdfReader.close();
            }
            pdfReader.close();
            document.close();
        } catch(DocumentException dex) {
            dex.printStackTrace();
        } catch(IOException ex) {
            ex.printStackTrace();
        }
        //建立PDF文件
        createPdf();


        File file3 = new File(ResourceUtils.getURL("classpath:").getPath()+TEMP_PATH);
        File file1 = new File(ResourceUtils.getURL("classpath:").getPath()+outputFileName);

        List<File> files = new ArrayList<>();
        files.add(pdfFile);
        files.add(file3);

        try {
            PdfUtil pdfUtil = new PdfUtil();
            pdfUtil.mergeFileToPDF(files,file1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //若是你是上傳文件服務器上,這裏能夠上傳文件
// String url = fileServer.uploadPdf(File2byte(file1));

        //刪除總文件
        //若是是你本地預覽就不要刪除了,刪了就看不到了
// if(file1.exists()){
// file1.delete();
// }
        //刪除模板文件
        if(pdfFile.exists()){
            System.gc();
            pdfFile.delete();
        }
        //刪除產品文件
        if(file3.exists()){
            file3.delete();
        }
        return "success";
    }

複製代碼

建立PDF附件信息拼接到主文件中:

/** * 建立PDF附件信息 */
    public static void createPdf() {
        Document doc = null;
        try {
            doc = new Document();
            PdfWriter.getInstance(doc, new FileOutputStream(ResourceUtils.getURL("classpath:").getPath()+TEMP_PATH));
            doc.open();
            BaseFont bfChi = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font fontChi = new Font(bfChi, 8, Font.NORMAL);

            PdfPTable table = new PdfPTable(5);

            Font fontTitle = new Font(bfChi, 15, Font.NORMAL);
            PdfPCell cell = new PdfPCell(new Paragraph("*貨運*運輸服務協議-附件1 運輸費用報價",fontTitle));


            cell.setColspan(5);
            table.addCell(cell);
// "序號"
            table.addCell(new Paragraph("序號",fontChi));
            table.addCell(new Paragraph("品類",fontChi));
            table.addCell(new Paragraph("名稱",fontChi));
            table.addCell(new Paragraph("計算方式",fontChi));
            table.addCell(new Paragraph("費率",fontChi));

            table.addCell(new Paragraph("1",fontChi));
            table.addCell(new Paragraph("貨運",fontChi));
            table.addCell(new Paragraph("費率1.0",fontChi));
            table.addCell(new Paragraph("算",fontChi));
            table.addCell(new Paragraph("0~100萬-5.7%,上限:500元,下限:20元",fontChi));

            table.addCell(new Paragraph("2",fontChi));
            table.addCell(new Paragraph("貨運",fontChi));
            table.addCell(new Paragraph("費率1.0",fontChi));
            table.addCell(new Paragraph("倒",fontChi));
            table.addCell(new Paragraph("100萬~200萬-5.6%,無上限、下限",fontChi));

            table.addCell(new Paragraph("3",fontChi));
            table.addCell(new Paragraph("貨運",fontChi));
            table.addCell(new Paragraph("費率1.0",fontChi));
            table.addCell(new Paragraph("算",fontChi));
            table.addCell(new Paragraph("200萬~300萬-5.5%,無上限、下限",fontChi));


            doc.add(table);

// doc.add(new Paragraph("Hello World,看看中文支持不........aaaaaaaaaaaaaaaaa",fontChi));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
複製代碼

合同簽署:

/** * 簽署合同 * @return * @throws IOException * @throws DocumentException */
    @GetMapping("addContent")
    public String addContent() throws IOException, DocumentException {

        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont);

        //這裏能夠填寫本地地址,也能夠是服務器上的文件地址
        PdfReader reader = new PdfReader(ResourceUtils.getURL("classpath:").getPath()+outputFileName);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(ResourceUtils.getURL("classpath:").getPath()+endPdf));

//
        PdfContentByte over = stamper.getOverContent(1);
        ColumnText columnText = new ColumnText(over);

        PdfContentByte over1 = stamper.getOverContent(1);
        ColumnText columnText1 = new ColumnText(over1);

        PdfContentByte over2 = stamper.getOverContent(1);
        ColumnText columnText2 = new ColumnText(over2);


        PdfContentByte over3 = stamper.getOverContent(1);
        ColumnText columnText3 = new ColumnText(over3);
        // llx 和 urx 最小的值決定離左邊的距離. lly 和 ury 最大的值決定離下邊的距離
        // llx 左對齊
        // lly 上對齊
        // urx 寬帶
        // ury 高度
        columnText.setSimpleColumn(29, 117, 221, 16);
        Paragraph elements = new Paragraph(0, new Chunk("上海壹站供應鏈有限公司"));

        columnText1.setSimpleColumn(26, 75, 221, 16);
        Paragraph elements1 = new Paragraph(0, new Chunk("2021年03月03日"));

        columnText2.setSimpleColumn(800, 120, 200, 16);
        Paragraph elements2 = new Paragraph(0, new Chunk("壹匯(江蘇)供應鏈管理有限公司蕪湖分公司"));

        columnText3.setSimpleColumn(800, 74, 181, 16);
        Paragraph elements3 = new Paragraph(0, new Chunk("2022年03月03日"));

// acroFields.setField("customerSigntime", "2021年03月03日");
// acroFields.setField("vendorSigntime", "2021年03月09日");
        // 設置字體,若是不設置添加的中文將沒法顯示
        elements.setFont(font);
        columnText.addElement(elements);
        columnText.go();

        elements1.setFont(font);
        columnText1.addElement(elements1);
        columnText1.go();

        elements2.setFont(font);
        columnText2.addElement(elements2);
        columnText2.go();

        elements3.setFont(font);
        columnText3.addElement(elements3);
        columnText3.go();

        stamper.close();

        File tempFile = new File(ResourceUtils.getURL("classpath:").getPath()+"簽署測試.pdf");

        //若是是你要上傳到服務器上,填寫服務器的地址
// String url = fileServer.uploadPdf(File2byte(tempFile));
// log.info("url:"+url);

        //若是是上傳服務器後,要刪除信息
        //本地不要刪除,不然沒有文件
// if(tempFile.exists()){
// tempFile.delete();
// }

        return "success";
    }

複製代碼

PDF工具類:

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.List;

/*** * pdf 相關操做 * @author mxn */
@Slf4j
@Component
public class PdfUtil {

    /** * 合併PDF文件 * @param files 文件列表 * @param output 輸出的PDF文件 */
    public void mergeFileToPDF(List<File> files, File output) {
        Document document = null;
        PdfCopy copy = null;
        OutputStream os = null;
        try {
            os = new FileOutputStream(output);
            document = new Document();
            copy = new PdfCopy(document, os);
            document.open();
            for (File file : files) {
                if (!file.exists()) {
                    continue;
                }
                String fileName = file.getName();
                if (fileName.endsWith(".pdf")) {
                    PdfContentByte cb = copy.getDirectContent();
                    PdfOutline root = cb.getRootOutline();
                    new PdfOutline(root, new PdfDestination(PdfDestination.XYZ), fileName
                            .substring(0, fileName.lastIndexOf(".")));
                    // 不使用reader來維護文件,不然刪除不掉文件,一直被佔用
                    try (InputStream is = new FileInputStream(file)) {
                        PdfReader reader = new PdfReader(is);
                        int n = reader.getNumberOfPages();
                        for (int j = 1; j <= n; j++) {
                            document.newPage();
                            PdfImportedPage page = copy.getImportedPage(reader, j);
                            copy.addPage(page);
                        }
                    } catch(Exception e) {
                        log.warn("error to close file : {}" + file.getCanonicalPath(), e);
// e.printStackTrace();
                    }
                } else {
                    log.warn("file may not be merged to pdf. name:" + file.getCanonicalPath());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            if (copy != null) {
                copy.close();
            }
            if (os != null) {
                IOUtils.closeQuietly(os);
            }
        }
    }


    /** * 將文件轉換成byte數組 * @param file * @return * **/
    public static byte[] File2byte(File file){
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }
}
複製代碼

演示

當咱們編寫完成以後,就來到了最關鍵的地方,測試了,內心還有點小激動,應該不會有BUG的

在這裏插入圖片描述

首先咱們輸入http://localhost:8080/generatePdf,生成填充模板,生成新的PDF文件併合並文件,生成完成以後咱們會在項目的class目錄下看到這個文件

在這裏插入圖片描述

打開咱們的文件,就能夠看到,對應的數據信息,到這裏有驚無險,就查最後一步簽署合同了 在這裏插入圖片描述

到這裏若是可以把簽署的信息,填寫到合同簽署的位置上,那咱們就能夠說大功告成了,咱們輸入簽署的地址http://localhost:8080/addContent,當咱們在目錄下看到 簽署測試.PDF的時候就說明咱們大功告成了

在這裏插入圖片描述 在這裏插入圖片描述 咱們能夠看到對應的簽署信息已經被咱們添加上去了,除了沒有第三方認證,該有的功能都有了,太優秀了啊!

這個時候我不免想起了,李白那句 「仰天大笑出門去,我輩豈是蓬蒿人」,天晴了,雨停了,我以爲我又行了,我都已經聯想到產品小姐姐崇拜的小眼神了,魅力放光芒,請你不要再迷戀哥!別光喝酒啊,吃點菜啊,幾個菜喝成這樣 在這裏插入圖片描述

總結

這個功能,花費了小農三天的時候,若是這個功能已經可以在公司項目中正常使用了,以上就是這個功能的詳細代碼和說明,若是有疑問或者也在作這個功能的小夥伴能夠留言,小農看到了會第一時間回覆

若是你們以爲不錯,記得一鍵三連~

點贊過百,我就是懷雙胞胎也出下一篇

我是牧小農,怕什麼真理無窮,進一步有進一步的歡喜,你們加油!

相關文章
相關標籤/搜索