Java利用模板生成批量pdf,并压缩为zip文件

首先要使用到Adobe Acrobat Pro生成pdf模板(表单)

/**
     * @param sourceFile 原模板文件
     * @param targetFile 动态输入写入的文件
     * @param fieldMap   动态数据值
     * @param font(两个参数fontSize,spacing)(可为null)
     **/
    public static File toPdf(String sourceFile, String targetFile, Map<String, Object> fieldMap,Map<String,Integer> font) {
        File file = null;
        PdfReader reader = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        AcroFields acroFields = null;
        FileOutputStream fos=null;
        try {
            reader = new PdfReader(sourceFile);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            acroFields = stamper.getAcroFields();
            com.itextpdf.text.pdf.BaseFont bfChinese = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
            acroFields.addSubstitutionFont(bfChinese);
            String fileSavePath = targetFile;
            file = new File(fileSavePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            for (String key : fieldMap.keySet()) {
//选择器            
// 				if (acroFields.getFieldType(key)==(AcroFields.FIELD_TYPE_CHECKBOX)) {
                    // 处理复选框字段
//                    boolean isChecked = fieldMap.get(key)==null?false:(Boolean) fieldMap.get(key);
//                    acroFields.setField(key, isChecked ? "On" : "Off"); // 设置复选框的值
//               } else if (font == null) {
//                    acroFields.setField(key, fieldMap.get(key).toString());
//                } else {
//                    setFieldAndFont(bfChinese, stamper, acroFields, fieldMap.get(key).toString(), font.get("fontSize"), font.get("spacing"), key);
//                }                
                
                if(font==null){
                    acroFields.setField(key, fieldMap.get(key).toString());
                }else {
                    setFieldAndFont(bfChinese,stamper,acroFields,fieldMap.get(key).toString(),font.get("fontSize"),font.get("spacing"),key);

                }
                     }
            stamper.setFormFlattening(true);
            stamper.close();
            fos = new FileOutputStream(fileSavePath);
            fos.write(bos.toByteArray());
        } catch (Exception e) {
            throw new CommonRuntimeException("生成pdf文件异常" +e.getMessage());
        } finally {
            try {
                if(stamper!=null){
                    stamper.close();
                }
                if(fos!=null){
                    fos.close();
                }
                if(bos!=null){
                    bos.close();
                }
                if(reader!=null){
                    reader.close();
                }
            } catch (Exception e) {
                throw new CommonRuntimeException("生成pdf文件异常" +e.getMessage());
            }
        }
        return file;
    }

需要引入的jar包

		<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.3.2</version>
        </dependency>

将多个文件压缩为zip文件

/**
     * @param fileName 生成压缩文件的全路径
     * @param files 文件集
     **/		
	 private void zip(String fileName, List<File> files) {
        ZipOutputStream outputStream1 = null;
        FileOutputStream dest = null;
        try {
            byte[] data = new byte[1024];
            dest = new FileOutputStream(fileName);
            outputStream1 = new ZipOutputStream(new BufferedOutputStream(dest));
            for (int i = 0; i < files.size(); i++) {
                int count;
                FileInputStream fis = new FileInputStream(files.get(i));
                BufferedInputStream bfs = new BufferedInputStream(fis);
                ZipEntry entry = new ZipEntry(files.get(i).getName());
                outputStream1.putNextEntry(entry);
                while ((count = bfs.read(data, 0, 1024)) != -1) {
                    outputStream1.write(data, 0, count);
                }
                bfs.close();
                fis.close();
            }
        } catch (Exception e) {
            throw new CommonRuntimeException("压缩文件失败");
        } finally {
            try {
                outputStream1.close();
                dest.close();
            } catch (IOException e) {
                throw new CommonRuntimeException("压缩文件失败");
            }
        }
        for (File file : files) {
            file.delete();
        }
    }	

为文本域设置格式

	/**
     * @param chunkStr文本内容
     * @param size1字体大小
     * @param size2行距
     * @param property文本域名称
     **/	
public static void setFieldAndFont(BaseFont bf, PdfStamper stamp, AcroFields form, String chunkStr, Integer size1, Integer size2, String property){
	 Font font = new Font(bf, size1,-1,new BaseColor(0,0,0));
            List<AcroFields.FieldPosition> list = form.getFieldPositions(property);
            int page = list.get(0).page;
            PdfContentByte pdfContentByte = stamp.getOverContent(page);
            ColumnText columnText = new ColumnText(pdfContentByte);
            Rectangle rectangle = list.get(0).position;
            columnText.setSimpleColumn(rectangle);
            Chunk chunk = null;
            chunk = new Chunk(chunkStr);
            Paragraph paragraph = new Paragraph(size2, chunk);
            columnText.addText(paragraph);
            paragraph.setFont(font);
            columnText.addElement(paragraph);
        try {
            columnText.go();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
}
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值