javaWeb文档预览之PDF.js实现PDF文件跨域预览(附测试实例)

来源:互联网 发布:mac单机游戏迅雷下载 编辑:程序博客网 时间:2024/05/29 17:41

1、项目结构(测试使用的是springboot的工程)
这里写图片描述
这里写图片描述
2、核心代码
(1)前台代码

<body><div tabindex="-1" class="modal fade in" id="my-showpdf">    <div class="modal-dialog info">        <div class="modal-content">            <div class="modal-body tc picshow">-->                <iframe id="pdfjsshow" src="/static/web/viewer.html?file=/pdfStreamHandeler" width="100%" height="750"></iframe>                <!--file通过调用接口获得后台的流数据-->            </div>        </div>    </div></div><script>    function pdfShow() {        $('#my-showpdf').modal({            backdrop: true,            keyboard: true,            show: true        });    }</script><button onclick="pdfShow()">PDF show</button><!--点击按钮显示模式对话框--></body>

(2)后台代码

 @RequestMapping(value = "/pdfStreamHandeler",method = RequestMethod.GET)    public void pdfStreamHandeler(HttpServletResponse response) {        try {            //这里添的是本地的流媒体服务的地址              String fullpath = "http://127.0.0.1:7999/test.pdf";            InputStream inputStream = null;            String strUrl = fullpath.trim();            URL url = new URL(strUrl);            //打开请求连接            URLConnection connection = url.openConnection();            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");            // 取得输入流,并使用Reader读取            inputStream = httpURLConnection.getInputStream();            response.setHeader("Content-Disposition", "attachment;fileName=test.pdf");            response.setHeader("Access-Control-Allow-Origin","*");            response.setContentType("multipart/form-data");            OutputStream outputStream = response.getOutputStream();//            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);            IOUtils.copy(inputStream, outputStream);        } catch (Exception e) {            logger.error("pdf文件处理异常:" + e.getMessage());        }    }

3、PDF.JS 修改默认预览页面
这里写图片描述
我这里将默认的预览页面改成了第一页,在函数pdfViewSetInitialView中添加了以下一行代码:

 this.pdfViewer.currentPageNumber = 1;//pdf初始显示第一页

文档预览之OpenOfiice踩过的坑:
http://blog.csdn.net/coding13/article/details/77246339
文档预览之office转pdf(附详细代码):
http://blog.csdn.net/Coding13/article/details/77010545

参考博文: http://blog.csdn.net/achuo/article/details/51736983
配置参考博文: http://blog.csdn.net/zzh_meng520/article/details/76020949
Git PDF.js: https://github.com/mozilla/pdf.js/

实例下载地址:http://download.csdn.net/detail/coding13/9925310