image not displaying in PDF template using Spring Boot, flying saucer and Thymeleaf

耗尽温柔 提交于 2019-12-07 13:02:37

问题


I create a file pdf from html template using Spring Boot, flying saucer, thymeleaf. But image is not displaying in my file.

Project structure:

code html:

<div class="col-xs-6 invoice-col-2">
   <img src="../static/images/mastercard.png" alt="mastercard"></img>
</div>

When I change img tag to:

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

When I create PDF file, I get an error:

org.thymeleaf.exceptions.TemplateProcessingException: Link base "static/images/mastercard.png" cannot be context relative (/) or page relative unless you implement the org.thymeleaf.context.IWebContext interface (context is of class: org.thymeleaf.context.Context)


回答1:


Try using Spring's classpath: prefix. This loads your file directly from the classpath, no matter if you are running from a .jar or within your IDE. Here is an example:

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

More information about classpath: can be found in the official documentation.




回答2:


Use standard html src atribute and relative path from root of the project.

You can put your image in the root of the project and use it like this:

<img src="mastercard.png" />

If you want to resource folders you can set it like this:

<img src="src/main/resources/static/images/mastercard.png" />



回答3:


I faced the same issue but reading image file from disk is little costly, I would suggest you go with uri-data

http://www.tothenew.com/blog/using-data-urls-for-embedding-images-in-flying-saucer-generated-pdfs/

Because you anyway going to read image to generate PDF, better keep it in template.



来源:https://stackoverflow.com/questions/46418212/image-not-displaying-in-pdf-template-using-spring-boot-flying-saucer-and-thymel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!