【问题标题】:Convert PDF files to images with PDFBox使用 PDFBox 将 PDF 文件转换为图像
【发布时间】:2014-06-13 03:24:34
【问题描述】:

谁能给我一个示例,说明如何使用 Apache PDFBox 将 PDF 文件转换为不同图像(PDF 的每一页一个)?

【问题讨论】:

  • 只能在一张图片中吗?

标签: pdfbox


【解决方案1】:

1.8.* 版本的解决方案:

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 dependencies page

2.0版本的解决方案:

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 工具)中。在进行构建之前阅读2.0 dependencies page,您需要额外的 jar 文件来保存带有 jbig2 图像的 PDF,用于保存到 tiff 图像以及读取加密文件。

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

【讨论】:

  • 对于本问答的未来读者,您可能还想发布 2.x 的解决方案(除非这方面的 API 更改尚未稳定,也就是说)。
  • 请注意,为了在 2.0 中使用 ImageIOUtil,您需要添加对 pdfbox-tools 的依赖项。
  • 很好的例子!谢谢。不过有两点说明: * 在 2.0 版本中,第五行中缺少 BufferedImage bim = * 请注意,“300”是缩放级别,而不是(如我所假设的)dpi 值或其他值。在我遇到大量 OutOfMemory 异常之前,我才想到要检查 API!
  • @Aeseir 你需要 pdfbox-tools。加上 levigo jbig2 解码器和 jai_imageio.jar。
  • 感谢 bud,发现他们将工具迁移到了不同​​的 jar。
【解决方案2】:

我今天用 PdfBox 2.0.15 试了一下。

import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.rendering.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;


public static void PDFtoJPG (String in, String out) throws Exception
{
    PDDocument pd = PDDocument.load (new File (in));
    PDFRenderer pr = new PDFRenderer (pd);
    BufferedImage bi = pr.renderImageWithDPI (0, 300);
    ImageIO.write (bi, "JPEG", new File (out)); 
}

【讨论】:

  • 就像一个魅力,只是一件事。如果 pdf 文档有多个页面,请使用: pd.getNumberOfPages() 为每一页执行循环。
  • 这给了我java堆空间是什么原因?
  • @GhostDede 你玩过 DPI 值吗?也许降低可以解决您的问题。
  • 是的,降低 DPI 值可以解决我的问题,但我需要 500 DPI
【解决方案3】:
public class PDFtoJPGConverter {

    public List<File> convertPdfToImage(File file, String destination) throws Exception {

    File destinationFile = new File(destination);

    if (!destinationFile.exists()) {
        destinationFile.mkdir();
        System.out.println("DESTINATION FOLDER CREATED -> " + destinationFile.getAbsolutePath());
    }else if(destinationFile.exists()){
        System.out.println("DESTINATION FOLDER ALLREADY CREATED!!!");
    }else{
        System.out.println("DESTINATION FOLDER NOT CREATED!!!");
    }

    if (file.exists()) {
        PDDocument doc = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(doc);
        List<File> fileList = new ArrayList<File>();

        String fileName = file.getName().replace(".pdf", "");
        System.out.println("CONVERTER START.....");

        for (int i = 0; i < doc.getNumberOfPages(); i++) {
        // default image files path: original file path
        // if necessary, file.getParent() + "/" => another path
        File fileTemp = new File(destination + fileName + "_" + i + ".jpg"); // jpg or png
        BufferedImage image = renderer.renderImageWithDPI(i, 200);
        // 200 is sample dots per inch.
        // if necessary, change 200 into another integer.
        ImageIO.write(image, "JPEG", fileTemp); // JPEG or PNG
        fileList.add(fileTemp);
        }
        doc.close();
        System.out.println("CONVERTER STOPTED.....");
        System.out.println("IMAGE SAVED AT -> " + destinationFile.getAbsolutePath());
        return fileList;
    } else {
        System.err.println(file.getName() + " FILE DOES NOT EXIST");
    }
    return null;
    }

    public static void main(String[] args) {

    try {
        PDFtoJPGConverter converter = new PDFtoJPGConverter();
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your destination folder where save image \n");
        // Destination = D:/PPL/;
        String destination = sc.nextLine();

        System.out.print("Enter your selected pdf files name with source folder \n");
        String sourcePathWithFileName = sc.nextLine();
        // Source Path = D:/PDF/ant.pdf,D:/PDF/abc.pdf,D:/PDF/xyz.pdf
        if (sourcePathWithFileName != null || sourcePathWithFileName != "") {
        String[] files = sourcePathWithFileName.split(",");
        for (String file : files) {
            File pdf = new File(file);
            System.out.print("FILE:>> "+ pdf);
            converter.convertPdfToImage(pdf, destination);
        }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    }
}

======================================

我在这里使用 Apache pdfbox-2.0.8 、 commons-logging-1.2 和 fontbox-2.0.8 库

编码愉快 :)

【讨论】:

    【解决方案4】:

    没有任何额外的依赖项,您可以使用 PDFToImage 已经包含在 PDFBox 中的类。

    科特林:

    PDFToImage.main(arrayOf&lt;String&gt;("-outputPrefix", "newImgFilenamePrefix", existingPdfFilename))

    其他配置选项:https://pdfbox.apache.org/docs/2.0.8/javadocs/org/apache/pdfbox/tools/PDFToImage.html

    【讨论】:

    • 会有依赖。当您拥有具有受限权限的 PDF 或具有 JPEG 2000 图像或 JBIG2 图像的 PDF 时,您会看到它。
    • 那种的情况下“会有依赖关系”。对于我的用例,我们正在将我们创建的 pdf 转换为 img,因此不存在受限权利或那些不同的 img 类型的问题。
    • 此类图像在 PDF 中。示例:issues.apache.org/jira/secure/attachment/12865265/jbig2.pdf 只有事先知道您的输入 PDF 中没有这些类型的图像,您才是安全的。
    【解决方案5】:
    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;
    import java.nio.file.Path;
    
    public class Pdf2Image {
    
        public String convertPdf2Img(String fileInput, Path path) {
            String destDir = "";
            try {
                String destinationDir = path.toString();
                File sourceFile = new File(fileInput);
                File destinationFile = new File(destinationDir);
    
                if (!destinationFile.exists()) {
                    destinationFile.mkdir();
                    System.out.println("Folder Created -> " + destinationFile.getAbsolutePath());
                }
    
                if (sourceFile.exists()) {
                    PDDocument document = PDDocument.load(sourceFile);
                    PDFRenderer pdfRenderer = new PDFRenderer(document);
    
                    String fileName = sourceFile.getName().replace(".pdf", "");
    
                    // int pageNumber = 0;
    
                    // for (PDPage page : document.getPages()) {
                    for (int pageNumber = 0; pageNumber < document.getNumberOfPages(); ++pageNumber) {
                        BufferedImage bim = pdfRenderer.renderImage(pageNumber);
    
                        destDir = destinationDir + File.separator + fileName + "_" + pageNumber + ".png";
    
                        ImageIO.write(bim, "png", new File(destDir));
                    }
    
                    document.close();
    
                    System.out.println("Image saved at -> " + destinationFile.getAbsolutePath());
                } else {
                    System.err.println(sourceFile.getName() + " File does not exist");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return destDir;
        }
    
    }
    

    【讨论】:

    • 与其他所有解决方案相比,您的解决方案有什么优势?
    【解决方案6】:

    这是我将 pdf 从多部分文件转换为 jpg 缩略图的代码的一部分。我将图像保存为 base64 字符串。使用的是pdfbox 2.0.21版本。

    private static String generatePdfThumbnail(byte[] imageInBytesArray) throws IOException {
        PDDocument document = PDDocument.load(imageInBytesArray);
        PDFRenderer renderer = new PDFRenderer(document);
        BufferedImage bufferedImage = renderer.renderImage(0);
        Graphics2D bufImageGraphics = bufferedImage.createGraphics();
        bufImageGraphics.drawImage(bufferedImage, 0, 0, null);
    
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos);
        byte[] fileContent = null;
        if (!foundWriter) {
          return "";
        }
    
        fileContent = baos.toByteArray();
        return Base64.getEncoder().encodeToString(fileContent);
      }
    

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      相关资源
      最近更新 更多