8

I am using thymeleaf as my template engin to map XHTML to HTML and flying saucer to generate a pdf file afterwards.

Now i failed to display my static images located at /src/main/resources/ inside y generated pdf file. The file itsself will be displayed fine only images disapear.

Even other locations like /src/main/resources/static or /src/main/resources/public didnt help.

My HTML / XHTML looks like:

<img src="images/logo_black.png"></img>
        <img src="/images/logo_black.png"></img>
        <img alt="mastercard" th:src="@{classpath:static/images/logo_black.png}" />

        <div data-src="images/logo_black.png"></div>
        <div data-src="/images/logo_black.png"></div>
        <div data-src="@{classpath:static/images/logo_black.png}"></div>

none of them is working properly.

The Images itself are visible by localhost:8048/logo_black.png

I dont want to refer my images with a full url (http://...)

2 Answers2

1

You can include resources from any URL (from the Internet or from your file system). Either way, there are several steps involved:

When generating the HTML from the Thymeleaf template, you can use

  • @{/some/url} to resolve a path relative to your Web context (assuming you have a Web context), or
  • @{classpath:/some/url} with will just leave the URL as classpath:/some/url, or
  • simply a string value constant or a value from a variable (${var}), doesn't matter if it's an absolute URL https://some/url or relative, Thymleaf will leave them unchanged in the resulting HTML.

Before you pass the HTML to Flying Saucer, make sure the URLs are correct. Then Flying Saucer will process all URLs with a UserAgentCallback, by default ITextUserAgent.

The relevant methods in UserAgentCallBack are resolveURI and setBaseURL.

There is some weird logic going on in the default resolveURI method of ITextUserAgent (inherited from NaiveUserAgent). If the baseURL is null, it will try to set it, so it's best to always set it yourself. I had better results with overriding the resolveURI, the following is enough to keep absolute URLs and resolve relative URLs relative to the baseURL:

@Override
public String resolveURI(String uri) {
   if (URI(uri).isAbsolute())
       return uri;
   else
       return Paths.get(getBaseURL(), uri).toUri().toString();
}

Finally, in order to resolve the classpath: protocol, you need to define an URLStreamHandler unless there is already one defined (for example, the embedded Tomcat of Spring Boot already does supports this).

Dario Seidl
  • 4,140
  • 1
  • 39
  • 55
0

You can render image with the help of base 64 .You just convert your image on base 64 and it will show on your web page as well as mobile view.The tags are:

<img th:src="@{data:image/png ;base64,your base 64}"/>