专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

Java根据模板生成PDF文件

1,首先下载,安装 Adobe Acrobat DC

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

2,新建一个Word模板,转成PDF格式

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

4,点击右边准备表单

126_1.png

*** (模板中的fell_*,这些变量需要删除重新写一遍,不然数据存不进去)

126_2.png

4、准备好模板以后开始写Java代码

  首先导入所需jar包

  126_3.png

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 ,双击表单字段

  126_4.png

文章永久链接:https://tech.souyunku.com/48072

未经允许不得转载:搜云库技术团队 » Java根据模板生成PDF文件

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们