PDF预览
第一种:直接预览
@GetMapping(value = "preview") public void preview(HttpServletRequest request, HttpServletResponse response) throws IOException { FileInputStream in = null; OutputStream out = null; try { in = new FileInputStream(new File("D:\\test\\有效需求分析.pdf")); out = response.getOutputStream(); byte[] b = new byte[512]; while ((in.read(b))!=-1) { out.write(b); } out.flush(); }catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
第二种:使用pdf-box
引入依赖,这个依赖可以修改预览时在页面上显示的PDF的名称
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.26</version> </dependency>
生成预览
@GetMapping(value = "preview") public void previewTemplate(HttpServletRequest request,HttpServletResponse response) throws Exception { try { response.reset(); response.setContentType("application/pdf"); //设置可iframe嵌套 response.setHeader("X-Frame-Options", "ALLOWALL"); OutputStream out = response.getOutputStream(); //加载PDF String file = "D:\\test\\template.pdf"; PDDocument pdDocument = PDDocument.load(new FileInputStream(file)); //获得文档属性对象 PDDocumentInformation info = pdDocument.getDocumentInformation(); //设置名称 info.setTitle("自定义PDF名称"); pdDocument.setDocumentInformation(info); pdDocument.save(out); pdDocument.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
效果