java - 如何使用 thymeleaf 作为模板引擎生成 pdf 报告?

标签 java spring pdf thymeleaf

<分区>

我想在 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/

相关文章:

java - .properties-file 中的特殊字符 ("\")

ios - XCode: MasterDetailsView - 景观中没有分屏的 DetailsView?

vba - 将多张工作表保存为 PDF

java - 尝试使用 ArrayList<Integer> 创建冒泡排序时出现问题

java - JOptionPane - 检查用户输入并防止在满足条件之前关闭

spring - 远程/进程内服务

java - Spring 安全 "authorities-by-username-query"错误

php - 使用php搜索pdf中的文本

java - 如何使用 Java Swing 将选项卡拖到新窗口中?

java - 彼得森锁/解锁java实现