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

How to fix an error during generating PDF: PdfBoxTextRenderer.getWidth(PdfBoxTextRenderer.java:300)

我使用 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: null at com.openhtmltopdf.pdfboxout.PdfBoxTextRenderer.getWidth(PdfBoxTextRenderer.java:300) at com.openhtmltopdf.layout.Breaker.doBreakText(Breaker.java:147) at com.openhtmltopdf.layout.Breaker.doBreakText(Breaker.java:115) at com.openhtmltopdf.layout.Breaker.breakText(Breaker.java:109) at com.openhtmltopdf.layout.InlineBoxing.layoutText(InlineBoxing.java:959)

...

我发现了问题。我使用托管在我们服务器上的 PDF 文件中的图像。 Openpdftohtml library tried to access the images by the our public URL but this URL was not available. After adding access PDF is successfully created. I've also opened the issue on Github: https://github.com/danfickle/openhtmltopdf/issues/267