欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自动生成PDF文件(Java通过PDF模板自动生成PDF)

程序员文章站 2024-03-21 14:49:28
...

思路:

1、创建PDF模板(先创建对应的excel文件,创建好后另存为PDF文件)即可。

2、使用Adobe Acrobat DC工具打开PDF文件,设置自己想要替换的内容。

3、maven项目引入依赖:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.5</version>
</dependency>

<dependency>
     <groupId>com.itextpdf</groupId>
     <artifactId>itext-asian</artifactId>
     <version>5.2.0</version>
</dependency>

3、编写工具类读取模板文件,自动生成PDF文件。

package com.icbc.jfxj.util;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

/**
 * *
 * http://www.sinoufc.com/
 *  .--,       .--,
 * ( (  \.---./  ) )
 *  '.__/o   o\__.'
 *     {=  ^  =}
 *      >  -  <
 *     /       \
 *    //       \\
 *   //|   .   |\\
 *   "'\       /'"_.-~^`'-.
 *      \  _  /--'         `
 *    ___)( )(___
 *   (((__) (__)))    高山仰止,景行行止.虽不能至,心向往之。
 * 
 *
 * @Description 	由PDF模板生成PDF文件工具类
 * @Author Bingyong.Wang
 * @Date 2020年10月21日上午9:23:19
 */
public class Template2PDFTtil {
	
	/**
	 * 	使用指定数据填充PDF模板(通知书notice)
	 *  参数:
	 *     1、模板文件路径         templatePath
	 *     2、生成的新文件路径  newPDFPath
	 *     3、获取的数据(这里是通知书相关数据)
	 */
	public static void fillNoticeTemplate(String templatePath, String newPDFPath) {
        // 模板路径
        //String templatePath = "C:\\Users\\asus\\Desktop\\受理通知书和不动产证明.pdf";
        System.out.println("通知书模板路径 tempaltePath = " + templatePath);
        // 新的文件名
		/*String newName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + (int)(new Random().nextDouble() * 100000);
		System.out.println("生成文件的名称 newName = " + newName);*/
        // 生成的新文件路径
		/*String newPDFPath = "D:\\upload\\notice\\notice_"+newName+".pdf";
		System.out.println("生成文件的路径 newPDFPath = " + newPDFPath);*/
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
        	// 文件输出流 即写入的文件
            out = new FileOutputStream(newPDFPath);
            // PDF读入 即PDF模板
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            Map<String, String> map = new HashMap<>();
            // 获取缴费单的数据。    以下为测试数据
            
            // 业务类型
            map.put("businessType", "土地及房屋抵押权首次登记");
            // 业务编号
            map.put("businessCode", "202011270006");
            // 申请人(权利人)
            map.put("RightHolder", "中国建设银行股份有限公司云南省分行");
            // 申请人(义务人)
            map.put("Obligor", "张万奎");
            // 坐落
            map.put("address", "云南省昆明市官渡区小板桥街道北门街58号4-5幢1层520号云南省昆明市官渡区小板桥街道北门街58号4-5幢1层520号");
            // 权属证书(已登记证明)号
            map.put("OCNumber", "云(2020)五华区不动产权第0293218号");
            // 不动产登记申请书 页数
            map.put("page1", "2");
            // 不动产权证书 页数
            map.put("page2", "4");
            // 主债权合同及抵押合同表 页数
            map.put("page3", "11");
            // 不动产登记按规定要求提供的其他材料 页数
            map.put("page4", "1");
            
            Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next();
                // 替换模板中对应字段的值
                form.setField(name, map.get(name));
            }
            // true代表生成的PDF文件不可编辑
            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception{
        
        System.out.println("=====================  以下是获取模板文件的路径  ========================");
        
		File directory = new File("src/main/resources/pdf");
		
        // 获取通知书模板
		String noticeTemplatePath = directory.getCanonicalPath() + "\\template\\受理通知书和不动产证明.pdf";
		System.out.println("========== noticeTemplatePath ====> " + noticeTemplatePath + "============");
		
		String newName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + (int)(new Random().nextDouble() * 100000);
		// 生成新的文件
		String newPDFPath = directory.getCanonicalPath() + "\\create\\notice_" + newName + ".pdf";
		System.out.println("========== notice newPDFPath =====> " + newPDFPath);
		fillNoticeTemplate(noticeTemplatePath, newPDFPath);
        
        
    }
}

注意:

1  首先安装Adobe Acrobat DC。下载地址:https://pan.baidu.com/s/1BxjHtK5zAWBBsrOGZbEtdw

2  pdf模板编辑注意事项   详见 https://my.oschina.net/aijiaoer0624/blog/1921113?tdsourcetag=s_pcqq_aiomsg