Search code examples
javahtml-to-pdfopenhtmltopdf

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


I use openhtmltopdf library to convert my html templates to 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);
    }

During generating PDF file I am getting the following stacktrace:

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)

...


Solution

  • I found the issue. I use images on PDF file that hosted on our server. The 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