PDF.js 超简单使用教程,一看就会!

pdfjs 可以在线预览pdf文件,提供丝滑流畅的预览效果,支持缩放、页数控制、文档内检索等强大功能。

1 下载

官网下载Prebuilt版本
在这里插入图片描述
下载后解压,文件结构为:
在这里插入图片描述

2 启动项目

项目在本地环境(url以file://开头)无法运行,需要服务器环境。

使用nginx,修改配置文件 nginx安装目录/conf/nginx.conf

server {
      listen 8888;      
      location / {
        root   D:/pdfjs-2.2.228-dist;
      }      
}

启动 nginx,访问 http://localhost:8888/web/viewer.html
在这里插入图片描述

3 预览指定的pdf文件

默认加载的文件是:
在这里插入图片描述
想要加载别的文件,应该怎么做呢?

web/viewer.js 文件中找到 webViewerInitialized 方法:
在这里插入图片描述
以上代码说明:如果地址栏参数中有file字段,就使用file字段的地址;如果没有,就用 defaultUrl

3.1 预览pdfjs服务器内部的文件

先试试简单的:把文件放到pdfjs服务器的内部,看看能否预览:

把文件放到 web 目录下:
在这里插入图片描述
添加地址栏参数 file=能看吗.pdf后访问,预览成功!
在这里插入图片描述

3.2 预览其他服务器中的文件

在真实的场景中,要预览的文件不会在pdfjs服务器的内部,一般都在另外一个业务服务器中。


// 另外一个业务服务器(10.10.10.100)的文件接口(返回文件流)
var anotherServerPreviewUrl ="http://10.10.10.100/doc/preview?fileId=11111";

// 拼到file参数中,需要 encodeURIComponent 转译
const `http://localhost:8888/web/viewer.html?file=${encodeURIComponent(anotherServerPreviewUrl )}`;

注意要用 encodeURIComponent 转译:

encodeURIComponent() 函数 与 encodeURI() 函数的区别之处,前者假定它的参数是 URI 的一部分(比如协议、主机名、路径或查询字符串)。因此 encodeURIComponent() 函数将转义用于分隔 URI 各个部分的标点符号。

pdfjs服务器会请求 anotherServerPreviewUrl 获取文件流。

这个请求是 跨域 的,所以要 nginx 代理

代码改为:

// /api/代理到
var anotherServerPreviewUrl ="/api/doc/preview?fileId=11111";
const `http://localhost:8888/web/viewer.html?file=${encodeURIComponent(anotherServerPreviewUrl )}`;

在 nginx 配置中中添加对 /api/ 的代理,:

server {
      listen 8888;      
      location / {
        root   D:/pdfjs-2.2.228-dist;
      }  
      location /api/ {
        proxy_pass   http://10.10.10.100/;
      }    
}

预览成功:
在这里插入图片描述

4 页面改样式

web/viewer.html 中,样式可以随便修改,比如把操作栏移动到下面,改成粉色:
在这里插入图片描述
需要注意的是:

  • 元素的class可以改,都是控制样式的,和功能无关。
  • 元素的id和功能相关,不要改也不要删。
  • 想要隐藏某个功能的时候,不能直接从页面删除元素,而是要隐藏(display:none)。

因为:pdfjs 在进行初始化(绑定事件)的时候,是根据 id 来找元素的。如果找不到DOM元素,就会报错:在这里插入图片描述

发布了7 篇原创文章 · 获赞 9 · 访问量 2733

猜你喜欢

转载自blog.csdn.net/tangran0526/article/details/103274303