java集成pdf.js实现pdf文件在线预览

js实现在线预览。
在这里插入图片描述
pdf.js是开源项目,github的地址:
https://github.com/mozilla/pdf.js

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();
        }
    }

完事 !

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值