Java 实现发票信息输出为 PDF 文件(模板化)

转载:https://ld246.com/article/1578382225705

1.PDF 模板设计神器

软件名称:Adobe Acrobat DC
下载地址:可以自己下载,需要的私聊站长。
使用方式:
1.使用 Adobe Acrobat DC 打开需要设计的 PDF 模板文件(可编辑)
2.打开【工具】选项,如下图所示:

728 x 3001348 x 556

3.点击【准备表单】进入表单设计页面

728 x 3051358 x 569

4.进入表单设计页面,可以看到相关表单元素

728 x 4281207 x 710

5.设计相关表单
注意:此处的表单的 key 为类似 fill_3 这样的名称,这个 key 是程序设计
需要使用的。因此,建议自行按照相关程序定义进行编写,方便下一步的处理。

2.Java 操作 PDF 文件神器

1.引入依赖

	<dependencies>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.1.1</version>
            <type>pom</type>
        </dependency>
    </dependencies>

2.实现模板文件的标准化输出示例

 public static void main(String[] args) throws Exception {
        //模板文件路径
        String filePath = "c:/template.pdf";
        //标准化输出文件路径
        String toPath = "c:/template-output.pdf";
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(filePath), new PdfWriter(toPath));
        PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);
        //原始数据(待填充到PDF文件中的数据)
        Map<String, String> formDatas = new HashMap<>();
        //获取模板文件中的全量字段
        Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields();
        formFields.forEach((key, value) -> {
            try {
                //处理中文乱码
                PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
                //获取到模板中的某个字段
                PdfFormField agreementId = formFields.get(key);
                agreementId.setFont(font);
                //为模板中的某个字段设置值
                agreementId.setValue(formDatas.get(key));
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        //设置生成表单不可编辑,注意itext的版本,在7.0.0版本报错
        pdfAcroForm.flattenFields();
        pdfDoc.close();
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值