Search code examples
itextitext7html2pdf

How to load resources from classpath in itext7?


How to load resources like images, css and fonts from the classpath with iText 7?

Formerly I used the ITextRenderer to do so:

ITextRenderer renderer = createITextRenderer();
renderer.setDocumentFromString(htmlContent, "classpath:/templates/");

I tried it with the ConverterProperties, but that does not do the job.

ConverterProperties properties = new ConverterProperties().setBaseUri("classpath:/templates/");
HtmlConverter.convertToPdf(htmlContent, outputStream, properties);

Solution

  • Within Spring Boot Applications the classpath protocoll handler can be registered by using the TomcatURLStreamHandlerFactory. The baseURI can be set as stated in the question.

    org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.register();
    ConverterProperties properties = new ConverterProperties().setBaseUri("classpath:/templates/");