Springboot利用itext通过模板生成pdf文档带图片功能并把PDF上传到OSS存储

1 pdf模板生成

下载 Adobe Acrobat dc
http://www.downza.cn/soft/20562.html

用dc 打开pdf , 编写静态文字,生成表单

pom.xml

 <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

 先创建零时文件夹然后读取临时文件夹的file上传到OSS存储

System.getProperty("java.io.tmpdir")  如果在main方法中运行会在系统中生成一个临时虚拟文件夹;如果在web项目中会在项目中生成一个临时的虚拟文件夹。

使用和测试

   /**
     * 临时文件
     */
    private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "/tempdf/%s";

@Test
   public void contextLoads() {
        Map<String,String> map = new HashMap();
        map.put("companyName","上海庆楷");//添加合同编号
        //添加公司名称
        map.put("name_es_:fullname","李四");//甲
        //乙方公司名称
        map.put("token","156498746456468979");//乙

        map.put("phone","156486156498");//甲
        map.put("address","换那会");
        map.put("uName","李四1");//甲
        map.put("uPhone","156498748764");
        map.put("uGrngt","李四");//甲
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String date=localDate.format(formatters);
        //获取一年后的前一天
        LocalDate after1year = localDate.plusYears(1).minusDays(1);
        //格式化日期格式
        String TheDayBeforeAYearLater = after1year.format(formatters);
        //合同起始年月日
        map.put("startTime", date);
        //合同结束年月日
        map.put("entTime", TheDayBeforeAYearLater);
        //签订日期
        map.put("ymd",date );
        Map<String,Object> o=new HashMap();
        o.put("datemap",map);
        //调用方法
        pdfout(o);

    }
    public void pdfout(Map<String,Object> o) {
        Map<String,String> datemap = (Map<String,String>)o.get("datemap");
        // 你的PDF模板路径
        String templatePath = "";

        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            //↓↓↓↓↓这个是字体文件
            String fontUrl = "src/main/resources/font/GlowSansSC-Normal-Bold.otf";

            BaseFont bf = BaseFont.createFont(fontUrl,BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font FontChinese = new Font(bf, 5, Font.NORMAL);
            // 读取pdf模板
            PdfReader reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            form.addSubstitutionFont(bf);
            for(String key : datemap.keySet()){
                String value = datemap.get(key);
                form.setField(key,value);
            }
            // 生成的新文件路径


            File outFile = null;

                //生成临时文件位置,存储到 java.io.tmpdir 下
                outFile = new File(String.format(FILE_PATH_TEMPLATE, form.getField("name_es_:fullname")+ System.currentTimeMillis()+ ".pdf"));
                //如果不存在临时文件夹,则创建文件夹
                if (!outFile.getParentFile().exists()) {
                    outFile.getParentFile().mkdirs();
                }
                System.out.println("临时文件所在位置:——" + outFile.getPath());
                FileOutputStream out = new FileOutputStream(outFile);

            // 插入图片,图片的路径
            String imgUrl = "";
            AcroFields.FieldPosition position = form.getFieldPositions("img_es_:signer:signatureblock").get(0) ;

            int pageNo = position.page ;

            Rectangle signRect = position.position;

            float x = signRect.getLeft();

            float y = signRect.getBottom();

            // 读图片

            Image image = Image.getInstance(imgUrl);

            // 获取操作的页面

            PdfContentByte under = stamper.getOverContent(pageNo);

            // 根据域的大小缩放图片

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

            // 添加图片

            image.setAbsolutePosition(x, y);

            under.addImage(image);
            stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
            stamper.close();
            Document doc = new Document();
            Font font = new Font(bf, 32);
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = null;
            ///循环是处理成品只显示一页的问题
            for (int i=1;i<=reader.getNumberOfPages();i++){
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }
            doc.close();
            System.err.println("生成pdf文件完成~~~~~~~~~~");
            //file转MultipartFile
            MultipartFile file =  fileToMultipartFile(outFile);
            AliYunOSSUtil.uploadpdf(file);
        } catch (IOException e) {
            System.out.println(e);
        } catch (DocumentException e) {
            System.out.println(e);
        }
    }



    public MultipartFile fileToMultipartFile(File file) {
        org.apache.commons.fileupload.FileItem fileItem=createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static org.apache.commons.fileupload.FileItem createFileItem(File file) {
        org.apache.commons.fileupload.FileItemFactory factory = new org.apache.commons.fileupload.disk.DiskFileItemFactory(16, null);
        org.apache.commons.fileupload.FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

有没有大佬知道更好的办法直接上传到OSS存储。欢迎留言!!!如有不对请留言纠正!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值