PDFBox pdf to image生成重叠文本

CRS*_*CRS 1 pdf pdfbox

对于侧面项目,我开始使用PDFBox将pdf文件转换为图像.这是我用来转换为图像文件https://bitcoin.org/bitcoin.pdf的pdf文件.

这是我正在使用的代码.这是一个非常简单的代码,它调用PDFToImage.但输出jpg图像文件看起来非常糟糕,插入了大量逗号和一些重叠文本.

    String [] args_2 =  new String[7];
    String pdfPath = "C:\\bitcoin.pdf";
    args_2[0] = "-startPage";
    args_2[1] = "1";
    args_2[2] = "-endPage";
    args_2[3] = "1";
    args_2[4] = "-outputPrefix";
    args_2[5] = "my_image_2";
    //args_2[6] = "-resolution";
    //args_2[7] = "1000";
    args_2[6] = pdfPath;
    try {
        PDFToImage.main(args_2);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

mkl*_*mkl 5

如果查看日志记录输出(可能需要在您的环境中激活日志记录).你会看到很多像这样的条目(使用PDFBox 1.8.5生成):

Jun 16, 2014 8:40:43 AM org.apache.pdfbox.pdmodel.font.PDSimpleFont drawString
Warnung: Changing font on <t> from <Century Schoolbook Fett> to the default font
Jun 16, 2014 8:40:43 AM org.apache.pdfbox.pdmodel.font.PDSimpleFont drawString
Warnung: Changing font on <S> from <Times New Roman> to the default font
Jun 16, 2014 8:40:46 AM org.apache.pdfbox.pdmodel.font.PDSimpleFont drawString
Warnung: Changing font on <c> from <Arial> to the default font
Jun 16, 2014 8:40:52 AM org.apache.pdfbox.pdmodel.font.PDSimpleFont drawString
Warnung: Changing font on <i> from <Courier New> to the default font
Run Code Online (Sandbox Code Playgroud)

因此,PDFBox使用与PDF指示的字体不同的字体来呈现文本.这解释了插入大量逗号重叠文本:

  1. 不同的字体可能有不同的编码.看起来您的示例PDF使用的编码具有逗号,其中PDFBox假定的默认字体具有空格字符;
  2. 不同的字体具有不同的字形宽度.在示例PDF中,不同的字形宽度会导致重叠文本.

这导致了 使用PDFBox 1.8.5呈现的示例文档的第一页

所有这一切的原因是PDFBox 1.8.x不能正确支持所有类型的渲染字体.您可能想要尝试PDFBox 2.0.0-SNAPSHOT,这是目前正在开发的新PDFBox.但请注意,渲染类已更改.

使用PDFBox 2.0.0-SNAPSHOT

使用当前(2014年6月中旬)PDFBox 2.0.0-SNAPSHOT状态,您可以像这样呈现PDF:

PDDocument document = PDDocument.loadNonSeq(resource, null);
PDDocumentCatalog catalog = document.getDocumentCatalog();
@SuppressWarnings("unchecked")
List<PDPage> pages = catalog.getAllPages();

PDFRenderer renderer = new PDFRenderer(document);

for (int i = 0; i < pages.size(); i++)
{
    BufferedImage image = renderer.renderImage(i);
    ImageIO.write(image, "png", new File("bitcoin-convertToImage-" + i + ".png"));
}
Run Code Online (Sandbox Code Playgroud)

此代码的结果是: 使用当前PDFBox 2.0.0-SNAPSHOT呈现的示例文档的第一页

其他PDFRenderer.renderImage重载允许您明确设置所需的分辨率.

PS:正如Tilman Hausherr所提议的那样,你可能想要替换这个ImageIO.write电话

    ImageIOUtil.writeImage(image, "bitcoin-convertToImage-" + i + ".png", 72);
Run Code Online (Sandbox Code Playgroud)

ImageIOUtil是一个PDFBox助手类,它尝试优化编写器的选择ImageIO并向图像文件添加DPI属性.

如果使用不同的PDFRenderer.renderImage重载来设置分辨率,请记住在72此相应地更改最终参数.