使用 PDFBox 将 PDF 文件转换为图像 [英] Convert PDF files to images with PDFBox

查看:89
本文介绍了使用 PDFBox 将 PDF 文件转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能举个例子告诉我如何使用 Apache PDFBox 转换不同图像的 PDF 文件(PDF 的每一页一个)?

Can someone give me an example on how to use Apache PDFBox to convert a PDF file in different images (one for each page of the PDF)?

推荐答案

1.8.* 版本的解决方案:

Solution for 1.8.* versions:

PDDocument document = PDDocument.loadNonSeq(new File(pdfFilename), null);
List<PDPage> pdPages = document.getDocumentCatalog().getAllPages();
int page = 0;
for (PDPage pdPage : pdPages)
{ 
    ++page;
    BufferedImage bim = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
    ImageIOUtil.writeImage(bim, pdfFilename + "-" + page + ".png", 300);
}
document.close();

在构建之前,不要忘记阅读 1.8 依赖项页面.

Don't forget to read the 1.8 dependencies page before doing your build.

2.0 版本的解决方案:

Solution for the 2.0 version:

PDDocument document = PDDocument.load(new File(pdfFilename));
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{ 
    BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);

    // suffix in filename will be used as the file format
    ImageIOUtil.writeImage(bim, pdfFilename + "-" + (page+1) + ".png", 300);
}
document.close();

ImageIOUtil 类位于单独的下载/工件 (pdf-tools) 中.在构建之前阅读 2.0 依赖项页面,您需要额外的 PDF jar 文件使用 jbig2 图像,用于保存到 tiff 图像,以及读取加密文件.

The ImageIOUtil class is in a separate download / artifact (pdf-tools). Read the 2.0 dependencies page before doing your build, you'll need extra jar files for PDFs with jbig2 images, for saving to tiff images, and reading of encrypted files.

确保使用您正在使用的任何 JDK 版本的最新版本,即如果您使用的是 jdk8,则不要使用 1.8.0_5 版本,使用 1.8.0_191 或您当时的最新版本读.早期版本非常慢.

Make sure to use the latest version of whatever JDK version you are using, i.e. if you are using jdk8, then don't use version 1.8.0_5, use 1.8.0_191 or whatever is the latest at the time you're reading. Early versions were very slow.

这篇关于使用 PDFBox 将 PDF 文件转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆