Bootstrap

IText创建加盖公章的pdf文件并生成压缩文件

第一、前言
此前已在文章:Java使用IText根据pdf模板创建pdf文件介绍了Itex的基本使用技巧,本篇以一个案例为基础,主要介绍IText根据pdf模板填充生成pdf文件,并生成压缩文件。

第二、案例
以下面pdf模板为例,生成一个pdf文件,并将其压缩成zip文件。
在这里插入图片描述
在这里插入图片描述
第三、代码实现
1、将pdf模板机公章图片放到resource目录;
在这里插入图片描述
2、为提高效率,在系统启动后将模板加载到redis缓存中,代码如下;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Objects;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolAbstract;
@Component
public class InitConfig {
    private static final Logger logger = LoggerFactory.getLogger(InitConfig.class);
    private final JedisPoolAbstract jedisPool;

    @Autowired
    public InitConfig(JedisPoolAbstract jedisPool) {
        super();
        this.jedisPool = jedisPool;
    }

    @PostConstruct
    public void init() {
        try {
            Jedis jedis = jedisPool.getResource();
            final byte[] key="data".getBytes();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            InputStream is = this.getClass().getResourceAsStream("/template/data.pdf");
            jedis.set(key, streamToByteArray(is));
            final byte[] gongzhangKey="gongzhang".getBytes();
            if (jedis.exists(gongzhangKey)) {
                jedis.del(gongzhangKey);
            }
            is = this.getClass().getResourceAsStream("/image/gongzhang.png");
            jedis.set(gongzhangKey, streamToByteArray(is));

        } catch (Exception e) {
            logger.error("加载模板异常", e);
        }
    }
    public static byte[] streamToByteArray(InputStream is) throws Exception {
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            logger.error("初始化模板", e);
            throw e;
        } finally {
            if (Objects.nonNull(bos)) {
                bos.close();
            }
        }
    }
}

3、操作文件工具类;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

public final class CommonFileUtil {
    private final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CommonFileUtil.class);

    /**
     * 根据模板生成文件
     * @param paramMap
     * @param deskFile
     * @param template
     * @param gongZhang
     * @throws Exception
     */
    public static void create(Map<String, Object> paramMap, File deskFile, final byte[] template, final byte[] gongZhang) throws Exception {
        PdfReader reader = null;
        PdfStamper stamp = null;
        try {
            reader = new PdfReader(template);
            stamp = new PdfStamper(reader, new FileOutputStream(deskFile));
            stamp.setEncryption(null, "lsy2024".getBytes(), PdfWriter.ALLOW_PRINTING, true);
            //取出报表模板中的所有字段
            AcroFields form = stamp.getAcroFields();
            //设置宋体
            BaseFont song = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //设置参数
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                String key = entry.getKey();
                form.setFieldProperty(key, "textfont", song, null);
                form.setField(key, entry.getValue().toString());
            }
            //插入公章
            CommonFileUtil.insertImage(form, stamp, "gongzhang", gongZhang);
            //保存修改
            stamp.setFormFlattening(true);
        } catch (Throwable e) {
            logger.error("deskFile:{};文件生成失败!", deskFile, e);
            throw e;
        } finally {
            if (Objects.nonNull(stamp)) {
                stamp.close();
            }
            if (Objects.nonNull(reader)) {
                reader.close();
            }
        }
    }
    /**
     * pdf模板插入图片
     * @param form
     * @param stamper
     * @param filedName
     * @param gongZhang
     * @throws Exception
     */
    public static void insertImage(AcroFields form, PdfStamper stamper, String filedName, final byte[] gongZhang) throws Exception {
        final Rectangle signRect = form.getFieldPositions(filedName).get(0).position;
        float x = signRect.getLeft();
        float y = signRect.getBottom();
        Image image = Image.getInstance(gongZhang);
        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent(form.getFieldPositions(filedName).get(0).page);
        // 根据域的大小缩放图片
        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
        // 添加图片
        image.setAbsolutePosition(x, y);
        under.addImage(image);
    }
    /**
     * 文件压缩
     * @param sourcePath
     * @param zipFilePath
     * @throws Exception
     */
    public static void encryptNoPassword(String sourcePath, String zipFilePath) throws Exception {
        final long start = System.currentTimeMillis();
        byte[] buf = new byte[1024];
        File zipFile = new File(zipFilePath);
        //zip文件不存在,则创建文件,用于压缩
        ZipOutputStream zos = null;
        try {
            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            File file = new File(sourcePath);
            for (File sourceFile : file.listFiles()) {
                if (sourceFile == null || !sourceFile.exists()) {
                    continue;
                }
                try (FileInputStream fis = new FileInputStream(sourceFile)) {
                    //直接放到压缩包的根目录
                    zos.putNextEntry(new ZipEntry(sourceFile.getName()));
                    int len;
                    while ((len = fis.read(buf)) > 0) {
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                }
            }
        } catch (Throwable e) {
            logger.error("sourcePath:{};zipFilePath:{};压缩文件失败!", sourcePath, zipFilePath, e);
            throw e;
        } finally {
            if (zos != null) {
                zos.close();
            }
        }
        logger.info("sourcePath:{};zipFilePath:{};压缩文件结束!{}", sourcePath, zipFilePath, System.currentTimeMillis() - start);
    }
    /**
     * 清理文件
     * @param path
     */
    public static void clean(String path) {
        File rootPath = new File(path);
        if (rootPath.exists()) {
            if (rootPath.isDirectory()) {
                for (File file : rootPath.listFiles()) {
                    clean(file.getPath());
                }
            }
            if (rootPath.isFile() || rootPath.listFiles().length == 0) {
                rootPath.delete();
            }
        }
    }
}

4、编写一个测试方法;

    public void print() {
        try {
            final String name = "张三";
            final String rootPath = "D:/temp/";
            File rootFile = new File(rootPath);
            if (!rootFile.exists()) {
                rootFile.mkdir();
            }
            File destFile = new File(rootPath + name + ".pdf");
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("name", name);
            paramMap.put("birthDate", "2000-01-01");
            paramMap.put("currentDate", "2024  年  11  月  22  日");
            CommonFileUtil.create(paramMap, destFile, this.jedisPool.getResource().get("data".getBytes()), this.jedisPool.getResource().get("gongzhang".getBytes()));
            CommonFileUtil.encryptNoPassword(rootPath, "D:/data.zip");
        } catch (Exception e) {
            logger.error("==" + e);
        }
    }

5、调用并执行测试方法,将会在D盘创建压缩文件;
在这里插入图片描述
6、解压后如下;
在这里插入图片描述

欢迎大家积极留言交流学习心得!

;