图像未显示在使用 Spring Boot、飞碟和 Thymeleaf 的 PDF 模板中

din*_*0t4 5 html spring flying-saucer thymeleaf

我使用 Spring Boot、飞碟、百里香从 html 模板创建了一个文件 pdf。但是图像没有显示在我的文件中。

项目结构:

项目结构

代码html:

<div class="col-xs-6 invoice-col-2">
   <img src="../static/images/mastercard.png" alt="mastercard"></img>
</div>
Run Code Online (Sandbox Code Playgroud)

当我将 img 标签更改为:

<img src="../static/images/mastercard.png" alt="mastercard" th:src="@{static/images/mastercard.png}"></img>
Run Code Online (Sandbox Code Playgroud)

创建 PDF 文件时,出现错误:

org.thymeleaf.exceptions.TemplateProcessingException:链接基“static/images/mastercard.png”不能是上下文相关的(/)或页面相关的,除非你实现了 org.thymeleaf.context.IWebContext 接口(上下文是类:org.thymeleaf .context.Context)

ssc*_*ep3 13

尝试使用 Spring 的classpath:前缀。无论您是从.jarIDE 还是在 IDE中运行,这都会直接从类路径加载您的文件。下面是一个例子:

<img alt="mastercard" th:src="@{classpath:static/images/mastercard.png}" />
Run Code Online (Sandbox Code Playgroud)

更多信息classpath:可以在官方文档中找到。


LNT*_*LNT 1

我遇到了同样的问题,但从磁盘读取图像文件的成本很低,我建议您使用 uri-data

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

因为无论如何你都会读取图像来生成 PDF,所以最好将其保留在模板中。