4

我想将 PDF 页面转换为图像文件。使用 java 将 PDF 页面转换为图像时缺少文本。

转换后我想转换46_2.pdf的文件向我显示46_2.png

代码:

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class ConvertPDFPageToImageWithoutText {
    public static void main(String[] args) {
        try {
            String oldPath = "C:/PDFCopy/46_2.pdf";
            File oldFile = new File(oldPath);
           if (oldFile.exists()) {

            PDDocument document = PDDocument.load(oldPath);
            List<PDPage> list = document.getDocumentCatalog().getAllPages();

            for (PDPage page : list) {
                BufferedImage image = page.convertToImage();
                File outputfile = new File("C:/PDFCopy/image.png");
                ImageIO.write(image, "png", outputfile);
                document.close();
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}
4

3 回答 3

2

由于您使用的是 PDFBox,请尝试使用PDFImageWriter.writeToImage而不是 PDPage.convertToImage。这篇文章似乎与您正在尝试做的事情有关。

于 2014-01-11T06:41:53.760 回答
1

我有同样的问题。我找到了一篇文章(不幸的是我不记得在哪里,因为我已经阅读了数百篇)。有作者抱怨将Java版本更新到7.21后PDFBox出现了这样的问题。所以我使用的是 7.17,它对我有用:)

于 2014-01-13T14:24:09.390 回答
0

使用最新版本的PDFBox(我使用的是 2.0.9)并从此处添加JAI Image I/O依赖项。这是在JAVA 7上运行的示例代码。

    public void pdfToImageConvertorUsingPdfBox(String inputPdfPath) throws Exception {
    File sourceFile = new File(inputPdfPath);
    String formatName = "png";
    if (sourceFile.exists()) {
        PDDocument document = PDDocument.load(sourceFile);
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        int count = document.getNumberOfPages();

        for (int i = 0; i < count; i++) {
            BufferedImage image = pdfRenderer.renderImageWithDPI(i, 200, ImageType.RGB);
            String output = FilenameUtils.removeExtension(inputPdfPath) + "_" + (i + 1) + "." + formatName;
            ImageIO.write(image, formatName, new File(output));
        }
        document.close();
    } else {
        logger.error(sourceFile.getName() + " File not exists");
    }
}
于 2018-05-04T10:45:18.983 回答