java实现在线浏览PDF文档功能
实现在线浏览pdf文档功能(本代码适用于项目服务中固定的并且少量的pdf浏览,比如注册时的注册条款在线浏览等):
//设置响应内容类型为PDF类型 response.setContentType("application/pdf"); ServletOutputStream sos = response.getOutputStream(); //不在网页中打开,而是直接下载该文件,下载后的文件名为“Example.pdf” //response.setHeader("Content-disposition", "attachment;filename=Example.pdf"); File pdf = null; FileInputStream fis = null; byte[] buffer = new byte[1024*1024]; pdf = new File("D:\\test.pdf"); response.setContentLength((int) pdf.length()); fis = new FileInputStream(pdf); int readBytes = -1; while((readBytes = fis.read(buffer, 0, 1024*1024)) != -1){ sos.write(buffer, 0, 1024*1024); } sos.close(); fis.close();