利用java的iText操作PDF文件



使用背景:存在一个PDF模板,此模板预留很多信息进行填写,类似于表单。并非代码生成一个pdf模板。



java代码:

                     
  // 通过一个int型的type。在string数组里面找到相应的pdf名字

String name = findNameByType(type);

// 已经存在的pdf模板路径,我只是将路径存储在properties文件里面

String templatePath = AppContext.get("pdf.tpl.path") + name;

// 将要生成的目标PDF文件名称 

String outputFileName = loanApplyId + "-" + name;

// 打印pdf后存储的路径

String outputPath = AppContext.get("pdf.output.path") + outputFileName;

PdfReader reader = null;

PdfStamper ps = null;

try {
       reader = new PdfReader(templatePath);

       FileOutputStream fos = new FileOutputStream(outputPath);

       ps = new PdfStamper(reader, fos);

       AcroFields fields = ps.getAcroFields();

       ps.setFormFlattening(true);

// queryData方法是通过这两个参数去数据库查出来的值,用键值对依次放进Map集合里,键对应模板中取的名字。

       fillData(fields, queryData(loanApplyId, type));

       String uri = AppContext.get("pdf.show.uri") + outputFileName;

       return uri;

} catch (Exception e) {

       return 
e.getMessage();

} finally {
        try {
             if (ps != null) {
             ps.close();
      }
        if (reader != null) {
             reader.close();
     }
  } catch (Exception e) {
             logger.error("contractInfo close error", e);

}
****************************************************************************************************************************


public void fillData(AcroFields fields, Map<String, Object> data) throws IOException, DocumentException {

      BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

      for (String key : data.keySet()) {

            String value = String.valueOf(data.get(key));

            fields.setFieldProperty(key, "textfont", bf, null);

            fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
      }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值