您可以使用SpringTemplateEngine
thymeleaf 提供的。下面是它的依赖:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
下面是我为生成 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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将文件存储在如下所示的 Java 临时目录中,并将文件发送到您想要的任何位置:
System.getProperty("java.io.tmpdir");
Run Code Online (Sandbox Code Playgroud)
注意:如果您生成 pdf 的频率很高,请确保从临时目录中删除曾经使用过的文件。
您需要使用诸如 Flying-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*/ }
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后简单地@Autowire
将此组件添加到您的控制器/服务组件中并执行以下操作:
Map<String,String> data = new HashMap<String,String>();
data.put("name","James");
pdfGenaratorUtil.createPdf("greeting",data);
Run Code Online (Sandbox Code Playgroud)
"greeting"
你的模板的名称在哪里
有关详细信息,请参阅http://www.oodlestechnologies.com/blogs/How-To-Create-PDF-through-HTML-Template-In-Spring-Boot
归档时间: |
|
查看次数: |
11601 次 |
最近记录: |