首页 > 其他 > 详细

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

时间:2019-06-20 17:04:07      阅读:527      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

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:\Windows\Fonts文件下找
      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();
      }
    }
  }

}

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!