apache pdfbox文本填充中文

  • maven依赖
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.26</version>
        </dependency>

准备PDF模板

设置好需要填充文本的占位符

  • 使用Adobe Acrobat DC > https://www.superso.top/Adobe/
    image.png
  • 打开PDF文件,选择准备表单
    image.png
  • 如果没有,则选择更多工具-准备表单
    image.png
  • 双击设置每个表单的属性
    image.png
    image.png
    image.png
  • 推荐设置:
    • 名称:即占位符的名称,后面需要在程序中使用到
    • 表单域:可见,且只读,否则生成后的PDF文件的表单还是能编辑
    • 字体大小:可在编辑PDF的时候查看一下周边自己的大小,设置为一样的就行
    • 字体:中文设置为华文中宋,数字、英文设置为Arial,避免乱码
    • 对其方式设置为居中,会比较好看
  • 然后调整文本域框的大小、高宽,设置好之后保存即可。

编码替换

 try (InputStream inputStream = new ClassPathResource(OFFER_TEMPLATE_FORMAL).getInputStream();
             // 按需要添加特殊的字体,但是这会导致生成的PDF变大
             InputStream fontIS = new ClassPathResource("fonts/微软雅黑.ttf").getInputStream();
             PDDocument pdfDocument = PDDocument.load(inputStream)
        ) {
            PDDocumentCatalog documentCatalog = pdfDocument.getDocumentCatalog();
            PDAcroForm acroForm = documentCatalog.getAcroForm();
            PDResources res = acroForm.getDefaultResources();
            PDFont font = PDType0Font.load(pdfDocument, fontIS, false);
            // 添加字体
            String fontName = res.add(font).getName();
            String chineseDefaultAppearanceString = "/" + fontName + " 9 Tf 0 g";
            
            // 如果填充的是中文
            PDVariableText username = (PDVariableText) acroForm.getField("username");
            username.setDefaultAppearance(chineseDefaultAppearanceString);
            username.setValue(dhrPreCandidateEntity.getEmployeeName());
        
            // 填充的是英文或数字,可直接填充
           acroForm.getField("entryYear").setValue(arrDate.getYear() + StringUtils.EMPTY);
            
            // PDF文档信息
            PDDocumentInformation info = new PDDocumentInformation();
            info.setTitle("标题");
            info.setAuthor("一只特立独行的猪");
            info.setCreator("一只特立独行的猪");
            info.setSubject("一只特立独行的猪");
            info.setKeywords("一只特立独行的猪,apache pdfbox,pdf文本填充");
            info.setCreationDate(Calendar.getInstance());
            pdfDocument.setDocumentInformation(info);
            pdfDocument.save(outputStream);
  • 有些报错可能是因为PDF模板表单设置的字体不支持中文,需要改成华文中宋

其他资料

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值