pdf.js是一款基于HTML5的PDF(Portable Document Forma)格式文件的网页阅读器。pdf.js由 Mozilla Labs 社区支持,目标是创建一个通用的、基于WEB平台的解析和阅读PDF文件的阅读器。
在网页中使用pdf.js
pdf.js是一个开源项目。要在你的网页中应用pdf.js有两种方式:预建模式和从源文件中创建模式。
预建pdf.js
通过npm
通过该方法在安装pdf.js文件后使用pdfjs-dist/build/pdf.js来创建阅读器。
npm install pdfjs-dist
通过webpack
如果你使用webpack或browserify,你可以很容易的安装所需的文件。
// In your webpack config:
//
// Install `npm install url-loader` first.
// This will enable you to get the url of the worker and the pdf to use in the index.js.
// Notice that for the build process it might need some extra work.
webpackConfig.module.loaders = {
test: /\.pdf$|pdf\.worker\.js$/,
loader: "url-loader?limit=10000"
}
// in index.js
//
// `var PDFJS = require('pdfjs-dist/build/pdf');` would be better but
// somehow the PDFJS becomes an empty object.
// Without any special config, requiring the file and letting it to pollute
// the global namespace is the way to go:
require('pdfjs-dist/build/pdf');
require('pdfjs-dist/web/pdf_viewer'); // Only if you need `PDFJS.PDFViewer`
// Webpack returns a string to the url because we configured the url-loader.
PDFJS.workerSrc = require('pdfjs-dist/build/pdf.worker.js');
var url = require('assets/books/my book.pdf');
PDFJS.getDocument(url).then(function(pdf) {/* Continue the normal tutorial from the official readme.*/})
从下载包中安装
下载压缩包文件。
将压缩包文件解压到文件夹中,例如:pdf.js-gh-pages目录。
然后拷贝下列目录文件到你的网站中:
pdf.js-gh-pages/build/
pdf.js-gh-pages/web/
要查看PDF文件,可以简单的打开viewer.html,并在其后添加参数指定打开的PDF文件。Open yourpdf.pdf with PDF.js