两个方法,跨域加载服务端pdf文件和加载静态pdf文件,调用代码见下方:
1.跨域加载pdf
window.open("pdf/web/viewer.html?file=http://xxx.xxx.xxx.xxx:8082//test/test.pdf");
里面的xxx是服务端ip,应该都能看懂。
把附件文件夹放入工程中即可使用
跨域加载需要导入的文件太多,占用空间太大
2.加载静态pdf,代码贴在最下方,说明在下面:
静态加载pdf需要先将pdf文件放入工程中,同时需要导入pdf.js 和pdf.worker.js
scale = 2,//清晰度,越大清晰度越高
- 可在页面中嵌入pdf文件,页面中需要有以下样式:
<div>
<button id="prev">上一页</button>
<button id="next">下一页</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas" style="width: 100%; overflow-y: auto;"></canvas>
静态加载代码:
owner.loadPdfLocal = function(url){
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 2,//清晰度,越大清晰度越高
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* @param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
if(pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
// Update page counters
document.getElementById('page_num').textContent = num;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if(pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if(pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if(pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
PDFJS.getDocument(url).then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
}