java 使用 pdf.js 在线查看 pdf 文档

大城市里の小女人 提交于 2019-12-17 05:23:34

1. 下载对应的 pdf.js 文件:

   推荐地址: 
            https://github.com/mozilla/pdf.js/
            http://mozilla.github.io/pdf.js/

2. 下载完成后打开对应的 viewer.js 文件。

可以看到,默认打开的是 compressed.tracemonkey-pldi-09.pd f文件,如果后面我们需要打开我们指定的地址,于是清空默认地址。

3. 这样,我们就可以使用传递 file 形参来动态指定打开的 pdf 文件,如:

1 http://localhost:8080/mypdf/web/viewer.html?file=123.pdf

Tips:必须加载到服务器访问

4. 现在我们利用 controller 来动态找到磁盘的 pdf 并加载显示:

 1    @RequestMapping(value = "showViewPDF")
 2     public void showViewPDF() throws IOException { 4         File f = new File("d:/aaa/123.pdf");
 5         getResponse().reset();
 6         getResponse().setContentType("multipart/form-data");
 7         getResponse().setHeader("Content-Disposition", "attachment;fileName=123.pdf");
 8         OutputStream out = getResponse().getOutputStream();
 9         try {
10             FileUtil.writeToStream(f, out);12         } catch (IOException e) {
13             e.printStackTrace();
14         } finally {
15             out.flush();
16             out.close();
17         }
18     }

现在访问的地址变为了如下地址:

1 http://localhost:8080/mypdf/web/viewer.html?file=http://localhost:8080/mypdf/pdfPageController/showViewPDF

5. 现在我们通过 ID 号显示对应 ID 的文件:

 1   @RequestMapping(value = "showViewPDF")
 2     public void showViewPDF(String id) throws IOException {
 3         TUploadFileBlfy tUploadFile = pdfPageService.getPDFById(id);  // 这个是根据 ID 号查询数据库对应储存文件的路径
 4         File f = new File(tUploadFile.getFilePath());  //  tUploadFile.getFilePath();  这是获得对应 ID 文件的路径
 5         getResponse().reset();
 6         getResponse().setContentType("multipart/form-data");
 7         getResponse().setHeader("Content-Disposition", "attachment;fileName=" + tUploadFile.getFileName());  // 获得对应文件名
 8         OutputStream out = getResponse().getOutputStream();
 9         try {
10             FileUtil.writeToStream(f, out);12         } catch (IOException e) {
13             e.printStackTrace();
14         } finally {
15             out.flush();
16             out.close();
17         }
18     }

于是,现在请求的地址变为了这样:

1 http://localhost:8080/mypdf/web/viewer.html?file=http://localhost:8080/mypdf/pdfPageController/showViewPDF?id%3d402881d35dcb410f015dcb455cfc0001  id 后面的参数详细介绍:     %3d:这是等号(=)的转义字符;    402881d35dcb410f015dcb455cfc0001:这是该文件的 UUID 号码,唯一标识符;

好了,大概就是这样了,希望能帮助到大家。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!