java根據模板生成PDF文件


1,首先下載,安裝 Adobe Acrobat DC

  步驟方法:https://jingyan.baidu.com/article/c14654138d7a9c0bfcfc4ce9.html

2,新建一個Word模板,轉成PDF格式

3,通過 Adobe Acrobat DC工具打開保存好的PDF文件

4,點擊右邊准備表單

 

 

過程一

 

 *** (模板中的fell_*,這些變量需要刪除重新寫一遍,不然數據存不進去)

過程二

4.准備好模板以后開始寫Java代碼

  首先導入所需jar包

  過程四

 

5.具體代碼實現

  1,模板

    private static final String TEMPLATE_PATH="/template/XXX.pdf";

  2.讀取模板位置

    //Award award=數據對象;

    //===award==為要導出的對象數據

    PdfReader reader=new PdfReader(TEMPLATE_PATH);

    ByteArrayOutputStream bos=new ByteArrayOutPutStream();

    PdfStamper ps=new PdfStamper(reader,bos);

    AcroFields s=ps.getAcroFields();

    //=====解決中文不顯示的問題,注意需要引入itext-asian.jar包

    BaseFont bf=BaseFont.createFont("STSong-Lignt","UniGB-USC2-H",BaseFont.Not_EMBEDDEL);

    //====填充PDF

    //姓名

    s.setFieldProperty("fill_1","testfont",bf,null);

    if(award,getName()!=null){

      s.setField("fill_1",award.getName());

    }

 

    //性別

    s.setFieldProperty("fill_2","testfont",bf,null);

    if(award.getSex()!=null){

      if(award.getSex()==0){

        s.setField("fill_2","男");

      }else if(award.getSex()==1){

        s.setField("fill_2:,"女");

       }

     }

     //身份證號

      s.setFieldProperty("fill_3","testfont",bf,null);

     if(award.getNumberID() != null) {

        s.setField("fill_3",award.getNumberID());

     }

     //模板中的圖片的位置--圖片

     AcroFields from=ps.getAcroFields();

    String imgpath=declaration.getFilePath();

    int pageNo=from.getFieldPositions("Text1").get(0).page;

    Rectangle signRect=from.getFieldPosition("Text1").get(0).position;

    float x=signRect.getLeft();

    float y=signRect.getBottom();

    //根據路徑讀取圖片

    Image image=Image.getInstance(imgpath);

    //獲取圖片頁面

    PdfContentByte under=ps.getOverContent(pageNo);

    //圖片大小自適應

    image.scaleToFit(signRect.getWidth(),signRect.getHeight());

    //添加圖片

    image.setAbsolutePostion(x,y);

    unser.addImage(image);

 

    ps.setFormFlattening(true);

    ps.close();

 

    //收尾--重新生成PDF

    File file=new File(Contants.ROOT_PATH+Contants.BASE_PATH+declaration.getDocumentPath();

    if(!file.exists()) {

      file.mkdirs();

    }

    String path=Contants.ROOT_PATH+Contants.BASE_PATH+

    declaration.getDocumentPath()+File.separatorChar+declaaaration.getName()+".pdf";

    FileOutputStream fos=new FileOutputStream(path);

    fos.write(bos.toByteArray());

    fos.flush();

    fos.close();

    return path;

 

  修改字體大小方式

  打開Adobe acrobat pro dc ,雙擊表單字段

  圖三


免責聲明!

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



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