最近项目需要实现在线预览pdf文件功能,找来找去,发现有个pdf.js的类库挺好用,直接用js实现在线预览。
pdf.js是开源项目,github的地址:
https://github.com/mozilla/pdf.js
根据教程指引,有以下几个步骤:
185.31.16.184 github.global.ssl.fastly.net
PS:其实我们使用pdf.js,只需要构建后的内容,大家可以到我的百度云盘下载:http://pan.baidu.com/s/1bDK8Zs ,下载后复制generic到tomcat的webapps下,这样访问 http://localhost:8080/web/viewer.html 能看到demo效果,跳过以下步骤,直接到项目集成。
npm install -g gulp-cli
安装好gulp之后在源代码使用npm安装模块:
npm install
安装好模块后使用gulp构建本地web服务器:
gulp server
效果如下:
接着访问 http://localhost:8888/web/viewer.html 就能看到效果:
接下来使用gulp构建pdf.js,如下:
gulp generic
构建完成后项目目录下生成build文件夹:
generic/web/viewer.html渲染pdf阅读器页面,而generic/web/viewer.js则是打开指定的pdf文件,打开viewer.js
可以看到,默认打开的是generic/web/compressed.tracemonkey-pldi-09.pdf文件,再来看下面这段代码:
这样,我们就可以使用传递file形参来动态指定打开的pdf文件,如:
http://localhost:8080/generic/web/viewer.html?file=file.pdf
先写一个简单的jsp页面,使用iframe标签来加载pdf:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <iframe src="<c:url value="/res/pdf/web/viewer.html" />?file=/displayPDF.do" width="100%" height="800"></iframe> </body> </html>
接着写个controller读取pdf文件并返回:
import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; /** * 在线预览pdf * @Auothor wzx * @Date 2016/12/18 0018 */ @Controller public class DisplayPDFController { @RequestMapping("/displayPDF.do") public void displayPDF(HttpServletResponse response) { try { File file = new File("F:/资料/pdf/JVM基础.pdf"); FileInputStream fileInputStream = new FileInputStream(file); response.setHeader("Content-Disposition", "attachment;fileName=test.pdf"); response.setContentType("multipart/form-data"); OutputStream outputStream = response.getOutputStream(); IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream); } catch(Exception e) { e.printStackTrace(); } } }
运行,在浏览器访问以下地址:
http://localhost:8080/res/pdf.jsp
效果如下:
本质是访问generic/web/viewer.html,通过指定的file形参打开指定pdf文件。