java 如何使用 thymeleaf 作为模板引擎生成 pdf 报告?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35320438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate pdf report using thymeleaf as template engine?
提问by Anindya Chatterjee
I want to create pdf report in a spring mvc application. I want to use themeleaf for designing the html report page and then convert into pdf file. I don't want to use xlst for styling the pdf. Is it possible to do that way?
我想在 spring mvc 应用程序中创建 pdf 报告。我想使用themeleaf来设计html报告页面,然后转换成pdf文件。我不想使用 xlst 来设置 pdf 的样式。有可能这样做吗?
Note: It is a client requirement.
注意:这是客户的要求。
采纳答案by Vijay
You can use SpringTemplateEngine
provided by thymeleaf. Below is the dependency for it:
您可以使用SpringTemplateEngine
thymeleaf 提供的。下面是它的依赖:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
Below is the implementation I have done to generate the PDF:
以下是我为生成 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;
}
}
You can store the file in Java temp directory shown below and send the file wherever you want:
您可以将文件存储在如下所示的 Java 临时目录中,并将文件发送到您想要的任何位置:
System.getProperty("java.io.tmpdir");
Note: Just make sure you delete the file once used from the temp directory if your frequency of generating the pdf is high.
注意:如果您生成 pdf 的频率很高,请确保从临时目录中删除曾经使用过的文件。
回答by SilentICE
You'll need to use something like flying-saucer-pdf, create a component a bit like:
您需要使用类似 fly-saucer-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*/ }
}
}
}
}
Then simply @Autowire
this component in to your controller/service component and do something like:
然后@Autowire
将此组件简单地添加到您的控制器/服务组件中并执行以下操作:
Map<String,String> data = new HashMap<String,String>();
data.put("name","James");
pdfGenaratorUtil.createPdf("greeting",data);
where "greeting"
is the name of your template
"greeting"
你的模板名称在哪里
See http://www.oodlestechnologies.com/blogs/How-To-Create-PDF-through-HTML-Template-In-Spring-Bootfor details
有关详细信息,请参阅http://www.oodlestechnologies.com/blogs/How-To-Create-PDF-through-HTML-Template-In-Spring-Boot