使用itext将base64转成图片合并为pdf

依赖

        <!-- pdf解析-->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

base64转字节数组

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.dci.common.core.restful.exception.ServiceException;

/**
 * @author lawrence
 * @date 12/30/2022 10:32 AM
 * @decr
 */
public class Base64Util {

    /**
     * 解析base64数组为byte数组
     *
     * @param base64s
     * @return
     */
    public static byte[][] parseBase64(String[] base64s) {
        byte[][] result = new byte[base64s.length][];
        if (ArrayUtil.isEmpty(base64s)) {
            throw new ServiceException("base64数组不能为空");
        }
        int index = 0;
        for (String base64 : base64s) {
            if (StrUtil.isBlank(base64)) {
                continue;
            }
            String b64encoded = base64.substring(base64.indexOf("base64,") + "base64,".length());
            // 解码
            byte[] decode = Base64Decoder.decode(b64encoded);
            result[index++] = decode;
        }
        return result;
    }

    /**
     * 解析base64为byte数组
     *
     * @param base64
     * @return
     */
    public static byte[] parseByte64(String base64) {
        return parseBase64(new String[]{base64})[0];
    }
}

字节数组转Image对象

import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;

import java.io.IOException;

/**
 * @author lawrence
 * @date 12/30/2022 11:06 AM
 * @decr
 */
public class ImageUtil {
    /**
     * 解析字节流为Image对象
     *
     * @param bytes
     * @return
     */
    public static Image[] paresImage(byte[][] bytes) {
        int index = 0;
        Image[] result = new Image[bytes.length];
        for (byte[] bytes1 : bytes) {
            try {
                result[index++] = Image.getInstance(bytes1);
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 解析字节流为Image对象
     *
     * @param bytes
     * @return
     */
    public static Image paresImage(byte[] bytes) {
        return paresImage(new byte[][]{bytes})[0];
    }
}

合并PDF

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.dci.common.core.restful.exception.ServiceException;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfWriter;

import java.io.FileOutputStream;

/**
 * @author lawrence
 * @date 12/30/2022 10:33 AM
 * @decr
 */
public class PdfUtil {

    /**
     * 根据image对象生成pdf
     *
     * @param images
     * @param filePath
     */
    public static void generatePdf(Image[] images, String filePath) {
        if (ArrayUtil.isEmpty(images)) {
            throw new ServiceException("图片不能为空");
        }
        if (StrUtil.isBlank(filePath)) {
            throw new ServiceException("生成路径不能为空");
        }
        if (!filePath.endsWith(".pdf")) {
            filePath = filePath + ".pdf";
        }
        //创建一个文档对象
        Document doc = new Document();
        try {
            //定义输出文件的位置
            PdfWriter.getInstance(doc, new FileOutputStream(filePath));
            //开启文档
            doc.open();
            for (Image img : images) {
                //获得宽高
                Float h = img.getHeight();
                Float w = img.getWidth();
                //统一压缩
                Integer percent = getPercent(h, w);
                //图片居中
                img.setAlignment(Image.MIDDLE);
                //百分比显示图
                img.scalePercent(percent);
                doc.add(img);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }

    /**
     * 根据image对象生成pdf
     *
     * @param image
     * @param filePath
     */
    public static void generatePdf(Image image, String filePath) {
        generatePdf(new Image[]{image}, filePath);
    }

    /**
     * 压缩
     *
     * @param
     */
    public static Integer getPercent(Float h, Float w) {
        int g = 0;
        float g2 = 0.0f;
        g2 = 480 / w * 100;
        g = Math.round(g2);
        return g;
    }
}

方法

    /**
     * 导出图表的pdf
     *
     * @param param
     */
    @Override
    public void exportImagePdf(ExportQueryParam param) {
        String targetPath = param.getFilePath();
        if (StrUtil.isBlank(targetPath)) {
            throw new RuntimeException("文件路径不能为空");
        }
        String[] base64Images = param.getBase64Images();
        if (ArrayUtil.isEmpty(base64Images)) {
            throw new RuntimeException("base64数组不能为空");
        }
        // 1.base64转image对象
        byte[][] imageBytes = Base64Util.parseBase64(base64Images);
        // 2.image对象转jpg
        Image[] images = ImageUtil.paresImage(imageBytes);
        // 2.jpg转pdf
        PdfUtil.generatePdf(images, targetPath);
        log.info("生成pdf文件{}", targetPath);
    }

Test

    @Test
    public void exportPdf() {
        String base64 = FileUtil.readString("H:\\base64导出pdf测试数据.txt", StandardCharsets.UTF_8);
        ExportQueryParam exportQueryParam = new ExportQueryParam();
        exportQueryParam.setFilePath("C:\\Users\\admin\\Desktop\\测试文件\\pdf测试")
                .setBase64Images(new String[]{base64});

        iExportExcelService.exportImagePdf(exportQueryParam);
    }

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值