如何将PDF文件逐页拆分成图片 JAVA

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class PdfToImage {
    public static void main(String[] args) throws Exception {
        pdf2Image();
    }

    public static void pdf2Image() throws Exception {

                String pdfFilePath = "D:\\test\\1月.pdf";//pdf文件路径
                String destFormat = "jpg";//最终希望PDF文件转成的文件格式
                File file = new File(pdfFilePath);
               
                String destDirFile = "D:\\test\\1月";//最终jpg图片生成保存的目录
                PDDocument doc = null;
                try {
                    doc = PDDocument.load(file);
                    PDFRenderer renderer = new PDFRenderer(doc);
                    int pages = doc.getNumberOfPages();//获取到当前PDF内的总页数
                    for (int i = 0; i < pages ; i++) {//遍历每一页

                        //拼接生成的图片路径->D:/test/月份/月份(PDF后缀)-页数.jpg
                        int act = i + 1;//实际计数比计算机计数多一,因为计算机是从0计数
                        String destPath = destDirFile +  "\\" + "1月" + "-" + act + "." + destFormat;
                        BufferedImage image = renderer.renderImage(i);
                        File filepath = new File(destPath);
                        if (!filepath.exists()) {
                            filepath.mkdirs();//生成文件夹来存储输出的图片
                        }
                        File jpgFile = new File(destPath);//在此路劲内生成图片
                        ImageIO.write(image, destFormat, jpgFile);//传入参数,生成图片
                    }
                } finally {
                    if (doc != null) {
                        doc.close();
                    }

                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值