其中 freemarker 生成 html 片段省略,本文直接用 html 生成 pdf 为例。
1、添加 itextpdf 依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>5.0.0</version>
</dependency>
2、Java 代码
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping(value = "/html2pdf")
public String html2pdf() {
String html = file2str("e:\\demo.html", "UTF-8");
this.html2Pdf(html, "e:\\test.pdf");
return Instant.now().toString();
}
/**
* 读取 demo.html 文件内容(这里只是为了测试,直接写了 html 文件,实际应用中需要使用 freemarker 生成 html )
*
* @param path
* @param encoder
* @return
*/
public String file2str(String path,String encoder){
StringBuilder sb=new StringBuilder();
try {
BufferedReader in =new BufferedReader(new InputStreamReader(new FileInputStream(path),encoder));
String str;
while ((str=in.readLine())!=null) {
sb.append(str);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* HTML 转 PDF
*
* @param content html内容
* @param outPath 输出pdf路径
* @return 是否创建成功
*/
public boolean html2Pdf(String content, String outPath) {
try {
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setCharset("UTF-8");
FontProvider fontProvider = new FontProvider();
fontProvider.addSystemFonts();
converterProperties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(content, new FileOutputStream(outPath), converterProperties);
} catch (Exception e) {
log.error("生成模板内容失败,{}", e);
return false;
}
return true;
}
}
(END)