如何在生成PDF期间修复错误:PdfBoxTextRenderer.getWidth(PdfBoxTextRenderer.java:300)

时间:2019-03-22 17:51:31

标签: java html-to-pdf openhtmltopdf

我使用openhtmltopdf库将html模板转换为PDF:

    try (OutputStream os = new FileOutputStream(filePath);
            PDDocument doc = new PDDocument()) {
        for (String html : htmlPagesWithValues) {
            PdfRendererBuilder builder = new PdfRendererBuilder();
            builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR);
            builder.useDefaultPageSize(210, 297, BaseRendererBuilder.PageSizeUnits.MM);
            builder.useProtocolsStreamImplementation(new InternalFSStreamFactory(), "localProtocol");
            builder.withHtmlContent(html, "");
            builder.useSVGDrawer(new BatikSVGDrawer());
            builder.usePDDocument(doc);
            PdfBoxRenderer renderer = builder.buildPdfRenderer();
            renderer.createPDFWithoutClosing();
        }
        doc.save(os);
    } catch (Exception ex) {
        log.debug("Stacktrace: ", ex);
    }

在生成PDF文件期间,我得到以下堆栈跟踪:

  

java.lang.NullPointerException:空       在com.openhtmltopdf.pdfboxout.PdfBoxTextRenderer.getWidth(PdfBoxTextRenderer.java:300)       在com.openhtmltopdf.layout.Breaker.doBreakText(Breaker.java:147)       在com.openhtmltopdf.layout.Breaker.doBreakText(Breaker.java:115)       在com.openhtmltopdf.layout.Breaker.breakText(Breaker.java:109)       在com.openhtmltopdf.layout.InlineBoxing.layoutText(InlineBoxing.java:959)

     

...

1 个答案:

答案 0 :(得分:0)

我发现了问题。我在服务器上托管的PDF文件上使用图像。 Openpdftohtml库尝试通过我们的公共URL访问图像,但是该URL不可用。添加访问权限后,将成功创建PDF。我还在Github上发布了此问题:https://github.com/danfickle/openhtmltopdf/issues/267