2021-08-10 itextPDF根据模板生成PDF

这篇博客介绍了如何利用Adobe Acrobat Pro DC的表单功能来创建文本域,并通过编程方式设置字段值,包括日期、类别、版权等信息。同时,文章详细展示了如何在PDF中插入图片,以及处理多个图片的方法。最后,通过Java代码实现PDF文件的生成和预览,整个过程涉及文件流操作和PDF库的使用。
摘要由CSDN通过智能技术生成

一、使用刀板 AdobeAcrobatPro DC 的准备表单功能生成文本域

在这里插入图片描述
1、给各个文本域起名,作品类别起名t0,t1,t2,t…(相近内容起名推荐xxx0 xxx1 xxx2在java后台方便处理)
pic0,pic1,pic…在此文本域设置存放图片。

二、编写 代码

MatchProductReview product = matchProductReviewService.getById(productId);
        MatchType matchType = matchTypeService.getById(product.getTypeId());
        String[] piclist = null; 
        if (StrUtil.isNotBlank(product.getPicture())){
           piclist = product.getPicture().split(",");//存放图片的地址用,号分隔https://wenhui.whb.cn/u/cms/www/202108/0917101477gw.jpg
        }
        MatchUserInfo matchUser = matchUserInfoService.getOne(new LambdaQueryWrapper<MatchUserInfo>().eq(MatchUserInfo::getUserId, product.getUserId()));
        List<DropDown> groupDropDoen = matchGroupService.DropDown();
        String groupList = "";
        //获取yml中存放pdf模板的地址"F:\MINE\*.PDF"
        String templatePath = environment.getProperty("pdf.filepath")+""+environment.getProperty("pdf.file");
        //生成pdf地址名称	
        String newPDFPath=environment.getProperty("pdf.filepath")+product.getProductName()+".pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        Document doc = new Document();
        try {
            out = new FileOutputStream(newPDFPath);
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //设置字体,,该字体可自行百度搜下载。不使用,中文可能会不显示
            String code = product.getCode();
                        BaseFont bf = BaseFont.createFont("/root/simkai.ttf",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);//将字体放入设置中
            form.setField("code",code);//"code"对应pdf中的文本域,code输入的数据

            //上市时间
            form.setField("year1", String.valueOf(product.getListingDate().getYear()));
            form.setField("month1", String.valueOf(product.getListingDate().getMonthValue()));
            form.setField("day1", String.valueOf(product.getListingDate().getDayOfMonth()));
//            form.setField("toggle1","On",true);
//            form.setField("toggle2","On",true);
//            form.setField("toggle3","On",true);
//            form.setField("toggle4","On",true);
//            form.setField("toggle5","On",true);
//            form.setField("toggle6","On",true);

           //   作品类别
            String t=matchType.getCode();
            form.setField("t"+t,"On",true);//将txxx打上点,,On对应文本域属性导出值
            //form.setField("toggle6","one",false);//文本域不勾上点,,默认也是不勾上点
            if (product.getCopyright() == 0){ //版权复选框
                form.setField("nocopyright","On",true);
            }else{
                form.setField("iscopyright","On",true);
            }
            if (product.getOwnership()==0){ //所有权复选框
                form.setField("ownershipcom","On",true);
            }else{
                form.setField("ownershipper","On",true);
            }
            if (product.getPatent() == 0){ //申请专利复选框
                form.setField("notpatent","On",true);
            }else{
                form.setField("ispatent","On",true);
            }
            //添加图片
            if (piclist!=null){
                for(int i =0;i<piclist.length;i++){
                    if (piclist[i].equals("-1")){
                    }else{
                        int no = form.getFieldPositions("pic"+i).get(0).page;
                        Rectangle rect = form.getFieldPositions("pic"+i).get(0).position;
                        float x1=rect.getLeft();
                        float y2 =rect.getBottom();
                        Image img2 = Image.getInstance(piclist[i]);
                        PdfContentByte under2 = stamper.getOverContent(no);
                        img2.scaleToFit(rect.getWidth(), rect.getHeight());
                        img2.setAbsolutePosition(x1, y2);
                        under2.addImage(img2);
                    }
                }
            }
            //添加图片end
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true
            stamper.close();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            for(int i=1;i<=7;i++){	//注意***:7代表7页pdf,,pdf模板有几页就设置几
                PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }
//            under.endText();
            reader.close();//关闭流
            bos.close();
            doc.close();
            out.close();
            previewPDF(newPDFPath,response);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            File file = new File(newPDFPath);
            file.delete();//删除文件
        }
public  void previewPDF(String files,HttpServletResponse response){
    File file = new File(files);
    FileInputStream input=null;
    byte[] data = null;
    try {
        input = new FileInputStream(file);//输出流
        data = new byte[input.available()];
        input.read(data);
        response.setContentType("application/pdf;charset=UTF-8");//输出格式
        response.getOutputStream().write(data);
        input.close();
    }catch (IOException e) {
        e.printStackTrace();
    }
}```

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值