java 獲取檔案返回 pdf檔案並列印
阿新 • • 發佈:2019-01-26
<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> </head> <% out.clear(); out = pageContext.pushBody(); response.setContentType("application/pdf"); try { String _fileName=request.getAttribute("fileName").toString(); String strPdfPath = new String(_fileName); //判斷該路徑下的檔案是否存在File file = new File(strPdfPath); if (file.exists()) { DataOutputStream temps = new DataOutputStream(response .getOutputStream()); DataInputStream in = new DataInputStream( new FileInputStream(strPdfPath)); byte[] b = new byte[2048]; while ((in.read(b)) != -1) { temps.write(b); temps.flush(); } in.close(); temps.close(); } else { out.print(strPdfPath + " 檔案不存在!"); } } catch (Exception e) { out.println(e.getMessage()); } %> <body> <br> </body>
</html>
java程式碼只需要查詢當前的檔案,獲取到檔案的路徑+名稱 放入model,在頁面打印出來即可 生成pdf檔案打印出來