如何使用Thymeleaf作为模板引擎生成PDF报告?

17
我想在Spring MVC应用程序中创建pdf报告。 我想使用Themeleaf设计HTML报告页面,然后将其转换为PDF文件。 我不想使用XSLT样式化PDF。 这种方式可行吗?
注意:这是客户要求。

4
请参考此链接:https://dev59.com/p2Ag5IYBdhLWcg3wyNhv - ccheneson
2个回答

9
您可以使用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,请确保从临时目录中删除文件后再使用。

无法在模板中获取变量 - zhuochen shen
3
在示例中使用的 PdfRendererBuilder 是什么?该提供的库中并不包含它。 - vkirilichev
@zhuochenshen 变量包括您的 Html 正文。开始和结束字符串 <html> ... </html>,头部、正文和页脚信息。您还可以使用模型设置变量。final Context ctx = new Context(); ctx.setVariable("model", pdfModel); - Vijay
5
PdfRendererBuilder用于将XHTML/XML转换为PDF并输出到由toStream设置的输出流中。您需要添加以下依赖项: <dependency> <groupId>com.openhtmltopdf</groupId> <artifactId>openhtmltopdf-pdfbox</artifactId> <version>0.0.1-RC7</version> </dependency> 请注意,此依赖项是必需的。 - Vijay

5

您需要使用类似飞碟-pdf的工具,创建一个类似以下组件的组件:

@Component
public class PdfGenaratorUtil {
    @Autowired
    private TemplateEngine templateEngine;
    public void createPdf(String templateName, Map<String, Object> map) throws Exception {
        Context ctx = new Context();
        Iterator itMap = map.entrySet().iterator();
        while (itMap.hasNext()) {
            Map.Entry pair = (Map.Entry) itMap.next();
            ctx.setVariable(pair.getKey().toString(), pair.getValue());
        }

        String processedHtml = templateEngine.process(templateName, ctx);
        FileOutputStream os = null;
        String fileName = UUID.randomUUID().toString();
        try {
            final File outputFile = File.createTempFile(fileName, ".pdf");
            os = new FileOutputStream(outputFile);

            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(processedHtml);
            renderer.layout();
            renderer.createPDF(os, false);
            renderer.finishPDF();

        }
        finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) { /*ignore*/ }
            }
        }
    }
}

然后,只需在您的控制器/服务组件中将此组件@Autowire,并执行以下操作:

Map<String,String> data = new HashMap<String,String>();
    data.put("name","James");
    pdfGenaratorUtil.createPdf("greeting",data); 

其中"greeting"是您模板的名称。

详见http://www.oodlestechnologies.com/blogs/How-To-Create-PDF-through-HTML-Template-In-Spring-Boot


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接