我想从 Thymeleaf 模板渲染 PDF。我在指定存储在 resources/static/images/writing.png
<img th:src="@{/images/writing.png}" alt=""></img>
如果我在网络浏览器中打开页面,上面的代码运行良好,但当我尝试使用 TemplateEngine 处理它时,它会抛出异常
Link base "/images/writing.png" cannot be context relative (/...) unless the context used for executing the engine implements the org.thymeleaf.context.IWebContext interface (template: "TimetablePDF" - line 64, col 26)
我可以选择在 src 上指定完整路径,例如 http://localhost/images/...
但我认为这很糟糕,我不想这样做。
那么如何在不进行硬编码的情况下指定它呢?
最佳答案
您可以执行以下操作:
按照 Thymeleaf 开发人员的建议创建一个覆盖以下方法的自定义类:
This method can be overridden by any subclasses that want to change this behaviour (e.g. in order to avoid using the Servlet API for resolving context path or to allow context-relative URLs in non-web contexts).
public class CustomLinkBuilder extends StandardLinkBuilder {
@Override
protected String computeContextPath(
final IExpressionContext context, final String base, final Map<String, Object> parameters) {
if (context instanceof IWebContext) {
return super.computeContextPath(context, base, parameters);
}
return "./app/src/main/resources/static"; //assuming css and images are here
}
}
在创建模板引擎时添加这个新的 LinkBuilder,例如:
@Bean
public TemplateEngine springTemplateEngine(){
final TemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
templateEngine.addTemplateResolver(stringTemplateResolver());
templateEngine.setLinkBuilder(linkBuilder());
return templateEngine;
}
...
private ILinkBuilder linkBuilder(){
return new CustomLinkBuilder();
}
我使用相同的引擎解析为 html 页面(来自 WebContext)以及解析为字符串(来自 Context),然后转换为 pdf。因此这两种情况都会正确呈现:
<head>
...
<link rel="stylesheet" type="text/css" th:href="@{/css/cat_wanted.css}">
</head>
关于java - Thymeleaf 中图像的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67145533/