在现有的PDF上添加对应字段的值

话不多说直接上代码:

下面所需要的是maven依赖,使用最新版本的itextpdf

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext7-core</artifactId>
        <version>7.1.12</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>html2pdf</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>kernel</artifactId>
        <version>7.1.12</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>layout</artifactId>
        <version>7.1.12</version>
    </dependency>

代码如下:

public class PdfUtil {
/**
*
* @param template pdf模板
* @param target pdf生成地址
* @param data 对应参数
* @throws IOException
*/
public static void out(File template, String target, Map<String, String> data) throws IOException {
assert template != null && template.exists();
PdfReader reader = new PdfReader(template);
PdfDocument document = new PdfDocument(reader, new PdfWriter(target));
PdfAcroForm form = PdfAcroForm.getAcroForm(document, true);
Map<String, PdfFormField> fieldMap = form.getFormFields();

    PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", false);
    fieldMap.forEach((key, field) -> {
        if(data.containsKey(key)){
            field.setValue(data.get(key)).setFont(font).setFontSize(10);
        }
    });
    // 设置表单域不可编辑
    form.flattenFields();
    document.close();
    reader.close();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值