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:\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();
      }
    }
  }

}

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM