js实现在线预览。
pdf.js是开源项目,github的地址:
https://github.com/mozilla/pdf.js
创建一个pdf.jsp 做跳转
<%@page language="java" pageEncoding="UTF-8"%>
<%@include file="/WEB-INF/include/taglibs.jsp"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<%@include file="/WEB-INF/include/meta.jsp"%>
<%-- <%@include file="/WEB-INF/include/s.jsp"%> --%>
<script type="text/javascript" src="${ctx}/libs/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="${ctx}/libs/pdf/build/pdf.js"></script>
<script type="text/javascript" src="${ctx}/libs/pdf/build/pdf.worker.js"></script>
<script type="text/javascript">
$(function() {
$("#pdf").attr("height", $(document).height());
var url = "../libs/pdf/web/viewer.html?file=" + encodeURIComponent("${ctx}" + "/book/display.do?id=" + "${bookId}");
$("#pdf").attr("src", url);
})
</script>
</head>
<body>
<div class="main">
<iframe id="pdf" width="100%"></iframe>
</div>
</body>
</html>
后台 读取pdf
/**
*〈简述〉流输出pdf
*〈详细描述〉
* @author sjk
* @param id Long id
* @param response HttpServletResponse response
*/
@RequestMapping("/display")
public void display (Long id, HttpServletResponse response) {
Book book = bookService.findOne(id);
String path = book.getBookDownPath();
File pdfFile = new File(path);
response.setContentType("application/pdf");
try {
FileInputStream in = new FileInputStream(pdfFile);
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
while ((in.read(b)) != -1) {
out.write(b);
}
out.flush();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
完事 !