java实现将PDF文件拆分成图片

2022-02-04 00:00:00 拆分 文件 图片

利用java实现将PDF文件拆分成图片

实现代码如下:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/** * @Description pdf工具类 * @ClassName PdfUtils * @Author yuhuofei * @Date 2022/3/16 20:21 * @Version 1.0 */
public class PdfUtils { 

    /** * 将PDF文档拆分成多张图片,并返回所有图片的路径 * * @param pdfPath * @param pictureFolderPath * @return * @throws Exception */
    public static List<String> pdfSwitchToPicture(String pdfPath, String pictureFolderPath) throws Exception { 
        List<String> picUrlList = new ArrayList<>();
        File file = new File(pictureFolderPath);
        if (!file.exists()) { 
            file.mkdirs();
        }
        String pictureRootName = file.getName() + "_";
        List<byte[]> imageList = handlePdf(pdfPath);
        AtomicInteger pictureNameNumber = new AtomicInteger(1);
        for (byte[] image : imageList) { 
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byteArrayOutputStream.write(image);
            String pictureUrl = file.getAbsolutePath() + File.separator + pictureRootName + pictureNameNumber.getAndIncrement() + ".jpg";
            byteArrayOutputStream.writeTo(new FileOutputStream(pictureUrl));
            picUrlList.add(pictureUrl);
            byteArrayOutputStream.close();
        }
        return picUrlList;
    }

    /** * 处理PDF文档 * * @param pdfPath * @return * @throws Exception */
    public static List<byte[]> handlePdf(String pdfPath) throws Exception { 
        File pdfFile = new File(pdfPath);
        //加载PDF文档
        PDDocument pdDocument = PDDocument.load(pdfFile);
        //创建PDF渲染器
        PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
        int pageNum = pdDocument.getNumberOfPages();
        List<byte[]> list = new ArrayList<>();
        for (int i = 0; i < pageNum; i++) { 
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            //将PDF的每一页渲染成一张图片,并放大1.5倍
            BufferedImage image = pdfRenderer.renderImage(i, 1.5F);
            ImageIO.write(image, "jpg", outputStream);
            list.add(outputStream.toByteArray());
            outputStream.close();
        }
        pdDocument.close();
        return list;
    }

}

需要引入的jar包:

<dependency>
     <groupId>org.apache.pdfbox</groupId>
     <artifactId>pdfbox</artifactId>
     <version>2.0.24</version>
</dependency>
    原文作者:yuhuofei2021
    原文地址: https://blog.csdn.net/Crezfikbd/article/details/123536213
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章