pdf.js 网页在线浏览PDF文件

想浏览自己的服务器的pdf文件,

或者查看远程pdf文件,需要跨域设置,稍后我会讲跨域问题。

使自己的网站有百度文库那样的浏览pdf文档的能力。

适用于,看书、制作打印模版或者生成办公文档。

原代码直接放上服务器就可以使用,支持现流行的大部分浏览器

firefox、edge、chrome、360浏览器、qq浏览器等等。

https://github.com/mozilla/pdf.js

使用时,访问

http://yourserver/pdfjs/web/viewer.html?file=filepath(PDF文件的本地相对路径或远程访问路径)

远程路径记得用encodeURIComponent()编辑一下。

比如:var viewerUrl = 'web/viewer.html?file=' + encodeURIComponent(url);

或者viewer.js 修改 var DEFAULT_URL = 'document.pdf';

远程访问不同域名或端口需要做跨域处理,主要两个方面。

1、需要远程文件服务器的跨域声明,以nginx为例,

server
{
    listen 80;
    server_name tool.freebasic.cn;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/tool.freebasic.cn;
# * 米符号可替换为某域名
add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods GET,POST,DELETE;
add_header Access-Control-Allow-Header Content-Type,*;
}

2、pdf.js中的pdfjs/web/viewer.js修改,测试时版本号PDF.js v2.2.228

找到以下类似的行

if (origin !== viewerOrigin && protocol !== 'blob:') {
throw new Error('file origin does not match viewer\'s');
}

注释掉即可

if (origin !== viewerOrigin && protocol !== 'blob:') {
//throw new Error('file origin does not match viewer\'s');
}

这样pdfjs就有了跨域的能力。

或者找到HOSTED_VIEWER_ORIGINS

var HOSTED_VIEWER_ORIGINS = [null,'tool.freebasic.cn', 'http://mozilla.github.io', 'https://mozilla.github.io'];

var LOCAL_AUTO_DETECT_ORIGIN = window.location.origin;
  var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];
  HOSTED_VIEWER_ORIGINS.push(LOCAL_AUTO_DETECT_ORIGIN);

当然还支持hash锚的定义

http://yourserver/pdfjs/web/viewer.html?file=filepath(PDF文件路径)#page=2&zoom=page-fit,0,792
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注