itext 之表单

 

  本例亲自测度验证,来自于网上,经过甄别 改造 又还之于网络。 本例重点展示 生成PDF模板,在模板上通过pdf第三方编辑软件打开编辑,在指定地方加入表单,然后通过java代码打开模板对指定名称的表单加入数据 生成用户所需的pdf文件。 特别注意:itext包括adobe官方的PDF编辑器,很难几乎不可能 完成这种操作: 打开生成好的PDF文件,插入一段文字或表格,让插入点原因的内容的位置移动变化。  或者说 ITEXT很难完成真正意义上的插入功能,他只能在原因基础上 增加一层 对原因的内容进行覆盖。

另外本例,也解决了一个中文网上少有资料解决的一个问题 : 对于模板中的复选框 选中样式后,生成非表单样式的PDF文件时,复选框是叉,而不是表单中设定的选中样式。其核心代码是:

 form.setField(item.getKey(),str,true);
注意,第三个参数的值一定是逻辑值true.

说明:
agreementTemplate.pdf中需要加入一个文本表单元素name属生为:sampleField ;同时不得加一个checkbox表单元素,name属性为check1


import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Auther: cloud
 * @Date: 2019/8/18 12:22
 * @Description:
 */
public class FillFormDemo {
    static final Logger log = LoggerFactory.getLogger(FillFormDemo.class);


    public static void   main(String[] args) throws IOException, DocumentException {
        String formTemplate = "templatepdf/agreementTemplate.pdf";

        ClassPathResource resource=new ClassPathResource(formTemplate);
        PdfReader reader = new PdfReader(resource.getInputStream());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);
        /**
         * 使用中文字体 使用 AcroFields填充值的不需要在程序中设置字体,在模板文件中设置字体为中文字体 Adobe 宋体 std L
         */
        AcroFields form = stamper.getAcroFields();

        String fontFilePath = "font/SimSun.TTF";
        ClassPathResource resource1=new ClassPathResource(fontFilePath);

        BaseFont baseFont = BaseFont.createFont(resource1.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        form.addSubstitutionFont(baseFont);//这句必须加,不加生成的新表单不会显示

        form.setField("sampleField", "中国雄起了aaaaa");
        form.setField("check1", "是",true);
//        stamper.partialFormFlattening("sampleField");//保持表单样式
        // 设为true
        stamper.setFormFlattening(true);//为true时,保存后表单样式取消了
        stamper.flush();
        log.info( form.getField("sampleField"));
        stamper.close();
        FileOutputStream fos = new FileOutputStream("target/agreement.pdf");
        fos.write(bos.toByteArray());
        bos.close();
        fos.close();
        reader.close();




    }


}

  

 

转载于:https://www.cnblogs.com/isv1/p/11411549.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值