java pdf 转图片

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PdfUtil {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(PdfUtil.class);

    public static final int DEFAULT_DPI = 150;
 
    /**
     * pdf转图片
     * 多页PDF会每页转换为一张图片,下面会有多页组合成一页的方法
     *
     * @param pdfFile pdf文件路径
     * @param outPath 图片输出路径
     * @param dpi 相当于图片的分辨率,值越大越清晰,但是转换时间变长
     */
    public static void pdf2multiImage(String pdfFile, String outPath, int dpi , boolean str) {
        if (ObjectUtil.isEmpty(dpi)) {
            // 如果没有设置DPI,默认设置为150
            dpi = DEFAULT_DPI;
        }

        try (PDDocument pdf = PDDocument.load(new FileInputStream(pdfFile))) {
            List<Integer> list = new ArrayList<>();
            int actSize = pdf.getNumberOfPages();
            List<BufferedImage> picList = Lists.newArrayList();
            for (int i = 0; i < actSize; i++) {
                if (str && i == actSize - 1) {
                    continue;
                }
                BufferedImage image = new PDFRenderer(pdf).renderImageWithDPI(i, dpi, ImageType.RGB);
                if (!list.contains(image.getWidth())) {
                    list.add(image.getWidth());
                }
                picList.add(image);
            }
            if (list.size() > 1) {
                List<BufferedImage> newPicList = Lists.newArrayList();
                Collections.sort(list); // 倒序排列
                for (BufferedImage bufferedImage : picList) {
                    int width = list.get(0);

                    double roi = bufferedImage.getWidth() / (double)width;
                    BufferedImage bufferedImage1 = resizeImage(bufferedImage, list.get(0), (int) (bufferedImage.getHeight() / roi) );
                    newPicList.add(bufferedImage1);
                }
                // 组合图片
                PdfUtil.yPic(newPicList, outPath);
            } else {
                // 组合图片
                PdfUtil.yPic(picList, outPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /***
     * PDF文件转PNG图片,全部页数
     *
     * @param pdfFilePath pdf完整路径
     * @param dpi dpi越大转换后越清晰,相对转换速度越慢
     */
    public static void pdf2Image(String pdfFilePath, int dpi) {
        File file = new File(pdfFilePath);
        PDDocument pdDocument;
        try {
            String imgPdfPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            // 获取图片文件名
            String imagePdfName = file.getName().substring(0, dot);

            pdDocument = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            /* dpi越大转换后越清晰,相对转换速度越慢 */
            PdfReader reader = new PdfReader(pdfFilePath);
            int pages = reader.getNumberOfPages();
            StringBuffer imgFilePath;
            for (int i = 0; i < pages; i++) {
                String imgFilePathPrefix = imgPdfPath + File.separator + imagePdfName;
                imgFilePath = new StringBuffer();
                imgFilePath.append(imgFilePathPrefix);
                imgFilePath.append("_");
                imgFilePath.append((i + 1));
                imgFilePath.append(".png");
                File dstFile = new File(imgFilePath.toString());
                BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                ImageIO.write(image, "png", dstFile);
            }
            log.info("PDF文档转PNG图片成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 将宽度相同的图片,竖向追加在一起 ##注意:宽度必须相同
     *
     * @param picList 文件流数组
     * @param outPath 输出路径
     */
    public static void yPic(List<BufferedImage> picList, String outPath) {// 纵向处理图片
        if (picList == null || picList.size() <= 0) {
            log.info("图片数组为空!");
            return;
        }
        try {
            // 总高度
            int height = 0,
                    // 总宽度
                    width = 0,
                    // 临时的高度 , 或保存偏移高度
                    offsetHeight = 0,
                    // 临时的高度,主要保存每个高度
                    tmpHeight = 0,
                    // 图片的数量
                    picNum = picList.size();
            // 保存每个文件的高度
            int[] heightArray = new int[picNum];
            // 保存图片流
            BufferedImage buffer = null;
            // 保存所有的图片的RGB
            List<int[]> imgRgb = new ArrayList<int[]>();
            // 保存一张图片中的RGB数据
            int[] tmpImgRgb;
            for (int i = 0; i < picNum; i++) {
                buffer = picList.get(i);
                // 图片高度
                heightArray[i] = offsetHeight = buffer.getHeight();
                if (i == 0) {
                    // 图片宽度
                    width = buffer.getWidth();
                }
                // 获取总高度
                height += offsetHeight;
                // 从图片中读取RGB
                tmpImgRgb = new int[width * offsetHeight];
                tmpImgRgb = buffer.getRGB(0, 0, width, offsetHeight, tmpImgRgb, 0, width);
                imgRgb.add(tmpImgRgb);
            }
            // 设置偏移高度为0
            offsetHeight = 0;
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < picNum; i++) {
                tmpHeight = heightArray[i];
                if (i != 0) {
                    // 计算偏移高度
                    offsetHeight += heightArray[i - 1];
                }
                // 写入流中
                imageResult.setRGB(0, offsetHeight, width, tmpHeight, imgRgb.get(i), 0, width);
            }
            File outFile = new File(outPath);
            // 写图片
            ImageIO.write(imageResult, "png", outFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过BufferedImage图片流调整图片大小
     */
    public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);
        BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
        return outputImage;
    }



    public static void main(String[] args) throws Exception {
        PdfUtil.pdf2multiImage("C:/Users/202309100-ex.pdf","e:1.png",300, false);
    }


}

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值