转换为BufferedImage时出现PDFBox错误:NoClassDefFoundError:org / apache / fontbox / FontBoxFont

时间:2016-09-13 19:01:16

标签: java pdf bufferedimage pdfbox

我正在尝试使用PDFBox将PDF文档转换为.png文件。我跟着this answer来了解需要哪些依赖项并给出一个起点。当我尝试遍历页面并创建BufferedImage时,我收到NoClassDefFoundError错误。它正在寻找org/apache/fontbox/FontBoxFont,但通过一些广泛的谷歌搜索,我找不到关于FontBoxFont的事情。这是一个需要包含的独立罐子吗?导致此错误的原因是什么?以下.jar包含在项目中:

pdfbox-2.0.2.jar
levigo-jbig2-imageio-1.6.5.jar
pdfbox-tools-2.0.2.jar
jai-imageio-core-1.3.1.jar
commons-logging-1.2.jar

这是主要方法:

public static void main(String[] args) {

    String sourceDir = "C:/Dev/Workspace/PdfToPng/Stocks.pdf";
    String destinationDir = "C:/Dev/Workspace/PdfToPng/pages/";

    try {
        PDDocument document = PDDocument.load(new File(sourceDir));
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        for(int page = 0; page < document.getNumberOfPages(); ++page) {
            BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
            ImageIOUtil.writeImage(bim, destinationDir + (page+1) + ".png", 300);
        }
        document.close();
    } catch(Exception e) {
        System.out.println(e.getStackTrace());
    }
}

错误发生在BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/fontbox/FontBoxFont
    at org.apache.pdfbox.pdmodel.font.PDFontFactory.createFont(PDFontFactory.java:75)
    at org.apache.pdfbox.pdmodel.PDResources.getFont(PDResources.java:123)
    at org.apache.pdfbox.contentstream.operator.text.SetFontAndSize.process(SetFontAndSize.java:60)
    at org.apache.pdfbox.contentstream.PDFStreamEngine.processOperator(PDFStreamEngine.java:815)
    at org.apache.pdfbox.contentstream.PDFStreamEngine.processStreamOperators(PDFStreamEngine.java:472)
    at org.apache.pdfbox.contentstream.PDFStreamEngine.processStream(PDFStreamEngine.java:446)
    at org.apache.pdfbox.contentstream.PDFStreamEngine.processPage(PDFStreamEngine.java:149)
    at org.apache.pdfbox.rendering.PageDrawer.drawPage(PageDrawer.java:189)
    at org.apache.pdfbox.rendering.PDFRenderer.renderPage(PDFRenderer.java:208)
    at org.apache.pdfbox.rendering.PDFRenderer.renderImage(PDFRenderer.java:139)
    at org.apache.pdfbox.rendering.PDFRenderer.renderImageWithDPI(PDFRenderer.java:94)
    at PdfToPng.main(PdfToPng.java:25)
Caused by: java.lang.ClassNotFoundException: org.apache.fontbox.FontBoxFont
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 12 more

1 个答案:

答案 0 :(得分:9)

显然你需要在你的类路径中添加 Apache FontBox 2.0.2 ,你可以从here

获取它