itext导出pdf代码并处理中文乱码(2)

package com.itext.ipdf;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

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;

public class ReportPDF {

  public static void main(String[] args) throws IOException {

  makePdf();
  }


  public static void makePdf() throws IOException{


    PdfReader readeTemplate = null;
    FileOutputStream out = null;
    try {
      //1.读取template.pdf
      readeTemplate = new PdfReader("template.pdf");
      out = new FileOutputStream("ok.pdf");
      PdfStamper ps = new PdfStamper(readeTemplate, out);//模板转换成新文件
      AcroFields templateFileds = ps.getAcroFields();//获取Adobe Acrobat DC填充的字段
      //2.处理中文乱码
      //STZHONGS.TTF华文仿宋字体 可以到C:WindowsFonts文件下找
      String fonurl = ReportPDF.class.getClassLoader().getResource("STZHONGS.TTF").getPath();
      fonurl = fonurl.replaceAll("%20", " ");
      BaseFont bfChinese = BaseFont.createFont(fonurl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
      templateFileds.addSubstitutionFont(bfChinese);
      //3.向Adobe Acrobat DC填充的字段赋值
      templateFileds.setField("producer", "zzl");
      templateFileds.setField("productionTime", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
      templateFileds.setField("name", "内存条");
      templateFileds.setField("size", "8G");
      templateFileds.setField("color", "黑色");
      templateFileds.setField("amount", "1");

      ps.setFormFlattening(true);
      ps.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    }finally{
      if(out != null){
        out.close();
      }
      if(readeTemplate != null){
        readeTemplate.close();
      }
    }
  }

}

<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itextpdf</artifactId>
  <version>5.5.13</version>
  </dependency>
</dependencies>

原文地址:https://www.cnblogs.com/zzlcome/p/11059677.html