依赖如下
<!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-pdf -->
<dependency><groupId>org.xhtmlrenderer</groupId><artifactId>flying-saucer-pdf</artifactId><version>9.1.22</version>
</dependency>
测试本地导出时一切正常,代码如下
public static void main(string[] args) throws Exception {
String html ="<html><body><h1>Hello World!</h1></body></html>";
File file = new File("output.pdf");
ITextRenderer renderer = new TextRenderer();
renderer.setDocumentFromstring(html);
renderer.layout();
try(Outputstream os= Files.newOutputstream(file.toPath())) {renderer.createPDF(os);
}
导出的文件打开是正常的,然后尝试接口导出了,代码如下
public void export(HttpServletResponse response, string html) throws Exception {iITextRenderer renderer = new ITextRenderer():renderer.setDocumentFromstring("<html><body><h1>Hello World!</h1></body></html>"),renderer.layout();response.setContentType("application/pdf");response.setCharacterEncoding("UTF-8");response.setHeader(s:"Content-Disposition";renderer.createPDF(response.getOutputstream(), false):renderer.finishPDF():response.getoutputstream().flush();
}
然后导出后打不开了
解决方案:删除最后一行代码
删除这行代码
response.getoutputstream().flush();
删除后重启项目导出没问题了
最新测试,原来不是上面的问题。而是没调用下面这行代码时就会报错,上面代码也可以移除
要有这行代码,不然导出的PDF有问题
renderder.finishPDF();