我正面临一个需要处理HTML模板(index.html)的场景,该模板通过Thymeleaf TemplateEngine与Data POJO从ZIP文件(通过ZipInputStream)解压缩。 因此,我现在所拥有的是解压缩后的模板文件的InputStream。 我相信TemplateResolver将帮助我解决此问题。
TemplateResolver是一个通用实现,允许您指定自己的IResourceResolver实现,该实现以所需的任何方式获取输入流。您可以创建自己的资源解析器(实现IResourceResolver)并将其设置为TemplateResolver实例。
如何完成此任务?有任何见解吗?
// index.html is the byte[] here, 'resourceData'
InputStream fileinputStream = new ByteArrayInputStream(resourceData);
FileResourceResolver fileResourceResolver = new FileResourceResolver();
TemplateResolver resolver = new TemplateResolver();
resolver.setTemplateMode("XHTML");
resolver.setSuffix(".html");
resolver.setResourceResolver(fileResourceResolver);
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(resolver);
Context context = new Context(Locale.US);
context.setVariable("data", myDataPojo);
return engine.process("index", context);
答案 0 :(得分:1)
我找到了方法:)希望遇到相同问题的任何人都可以使用此解决方案。
private static class CustomTemplateResolver implements IResourceResolver {
private InputStream inputStream;
private String templateName;
public CustomTemplateResolver(String templateName, InputStream inputStream) {
this.templateName = templateName;
this.inputStream = inputStream;
}
@Override
public String getName() {
return templateName;
}
@Override
public InputStream getResourceAsStream(TemplateProcessingParameters templateProcessingParameters, String resourceName) {
return inputStream;
}
}
测试班
@Test
public void createPdfFromZip() throws Exception {
String fileBundleZipFile = "sample.zip";
String templateFileName = "index";
String fileExt = ".html";
ClassPathResource resourceZip = new ClassPathResource(fileBundleZipFile);
ZipFile zipFile = new ZipFile(new File(this.getClass().getResource("/" + fileBundleZipFile).getFile()));
ZipInputStream zipInputStream = new ZipInputStream(resourceZip.getInputStream());
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
if (zipEntry.getName().equals(templateFileName + fileExt)) {
TemplateResolver resolver = new TemplateResolver();
resolver.setTemplateMode("XHTML");
resolver.setSuffix(fileExt);
resolver.setResourceResolver(new CustomTemplateResolver(templateFileName, zipFile.getInputStream(zipEntry)));
MyPojo data= getData();
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(resolver);
Context context = new Context(Locale.US);
context.setVariable("data", data);
String dataHTMLString = engine.process(templateFileName, context);
Path tempFile = Files.createTempFile("unzipped-data-html", ".pdf");
createDataPdfWithCss(tempFile, dataHTMLString);
}
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.closeEntry();
zipInputStream.close();
}