【发布时间】:2019-04-11 17:39:04
【问题描述】:
我正在评估从模板生成 pdf 的 Thymeleaf 和 Flying Saucer,但在将 css 应用于我的 Thymeleaf 模板时遇到了问题。我已经阅读了相关问答here、here和here;但建议的解决方案都没有解决我的问题。
这是我的资源文件夹的样子:
所以我使用的是 Spring 将查找的默认目录。这就是我的 template.html 中 head 标签的样子:
<head>
<title>Spring Boot and Thymeleaf Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../static/css/style.css" th:href="@{/css/style.css}"/>
</head>
如果我在template.html 中内联我的 css,那么生成的 pdf 文件的样式将正确(因此我生成 pdf 的方式应该没有问题)。但是,当我尝试链接到如上所示的 css 文件时,生成的 pdf 未设置样式(因此未应用 css)。
最后,我可以通过 http://localhost:8080/css/style.css 访问我的 css 文件,因此 Spring 提供静态内容似乎没有问题。
为了完整起见,这就是我生成 pdf 的方式:
private final SpringTemplateEngine templateEngine;
private final Log log;
@Autowired
public PdfGenerator(SpringTemplateEngine templateEngine) {
this.templateEngine = templateEngine;
log = LogFactory.getLog(getClass());
}
public void generate(HttpServletRequest servletRequest, HttpServletResponse servletResponse, ServletContext servletContext) {
// Parse the pdf template with Thymeleaf
Locale locale = getLocale(servletRequest);
WebContext context = new WebContext(servletRequest, servletResponse, servletContext, locale);
context.setVariable("user", buildDummyUser());
context.setVariable("discounts", buildDummyDiscounts());
String html = templateEngine.process("template", context);
// Create the pdf with Flying Saucer
try (OutputStream outputStream = new FileOutputStream("generated.pdf")) {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(outputStream);
} catch (IOException | DocumentException e) {
log.error("Error while generating pdf", e);
}
}
我使用WebContext 而不是Context,因为Context 出现以下错误:
org.thymeleaf.exceptions.TemplateProcessingException: Link base "/css/style.css" cannot be context relative (/...) unless the context used for executing the engine implements the org.thymeleaf.context.IWebContext interface
我在这里缺少什么,为什么我的style.css 不适用于template.html?
【问题讨论】:
标签: css spring-boot thymeleaf