利用java的iText操作PDF文件

来源:互联网 发布:单片机音乐播放器程序 编辑:程序博客网 时间:2024/04/29 12:44



使用背景:存在一个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); // 为字段赋值,注意字段名称是区分大小写的
      }
}