我想在Spring MVC应用程序中创建pdf报告。 我想使用Themeleaf设计HTML报告页面,然后将其转换为PDF文件。 我不想使用XSLT样式化PDF。 这种方式可行吗?
注意:这是客户要求。
注意:这是客户要求。
SpringTemplateEngine
。以下是它的依赖关系:<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
@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;
}
}
System.getProperty("java.io.tmpdir");
PdfRendererBuilder
是什么?该提供的库中并不包含它。 - vkirilichev您需要使用类似飞碟-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