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

依赖

        
        <dependency>
            <groupId>com.lowagiegroupId>
            <artifactId>itextartifactId>
            <version>2.1.7version>
        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);
    }

你可能感兴趣的:(pdf,java)