<分区>
我想在 spring mvc 应用程序中创建 pdf 报告。我想使用 themeleaf 设计 html 报告页面,然后转换为 pdf 文件。我不想使用 xlst 来设计 pdf 样式。有可能这样做吗?
注意:这是客户要求。
<分区>
我想在 spring mvc 应用程序中创建 pdf 报告。我想使用 themeleaf 设计 html 报告页面,然后转换为 pdf 文件。我不想使用 xlst 来设计 pdf 样式。有可能这样做吗?
注意:这是客户要求。
最佳答案
可以使用thymeleaf提供的SpringTemplateEngine
。下面是它的依赖关系:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
下面是我为生成 PDF 所做的实现:
@Autowired
SpringTemplateEngine templateEngine;
public File exportToPdfBox(Map<String, Object> variables, String templatePath, String out) {
try (OutputStream os = new FileOutputStream(out);) {
// There are more options on the builder than shown below.
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(getHtmlString(variables, templatePath), "file:");
builder.toStream(os);
builder.run();
} catch (Exception e) {
logger.error("Exception while generating pdf : {}", e);
}
return new File(out);
}
private String getHtmlString(Map<String, Object> variables, String templatePath) {
try {
final Context ctx = new Context();
ctx.setVariables(variables);
return templateEngine.process(templatePath, ctx);
} catch (Exception e) {
logger.error("Exception while getting html string from template engine : {}", e);
return null;
}
}
您可以将文件存储在如下所示的 Java 临时目录中,然后将文件发送到任何您想要的地方:
System.getProperty("java.io.tmpdir");
注意:如果您生成 pdf 的频率很高,请确保从临时目录中删除曾经使用过的文件。
关于java - 如何使用 thymeleaf 作为模板引擎生成 pdf 报告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35320438/