pdf.js 連續分頁展示pdf內容
阿新 • • 發佈:2018-11-25
如何使用pdf.js 將所有內容在同一頁中展示。本文將作出相應的展示,這類需求一般適用於手機,pad 等移動端。
前面部落格中,演示的內容。都是點選下一頁進行翻頁。後面有網友問,如何在一頁中展示出來,所以我把這塊補充上。
其實呢,只要知道展示一頁,如果要展示多個頁,核心就是增加個迴圈,建立canvas 物件接受每一頁的pdf檔案繪製。其他的流程和每頁顯示一篇pdf,在流程上是一樣的。
1:迴圈建立canvas 的程式碼
var canvasList = document.getElementById('canvas_list');
var canvas = document .createElement('canvas');
canvasList.appendChild(canvas);
canvasList.appendChild(document.createElement('hr'))
2: 迴圈繪製pdf 的 核心程式碼
document.getElementById('page_count').textContent = '總頁數:' + pdfDoc.numPages;
for(var $i =1 ; $i <= pdfDoc.numPages ; $i++) {
// Initial/first page rendering
renderPage($i );
}
3:注意事項:
本文只是展示,沒有使用懶載入等效能優化手段,對體積較大的pdf,不太使用。
4:demo 下載地址
https://download.csdn.net/download/niedewang/10571405
5:完整html程式碼如下:
<html>
<head>
<meta charset="utf-8">
<title>pdf.js展示1,上一頁,下一頁</title>
</head>
<h1>PDF.js連續分頁展示</h1>
<div>
<span id="page_count"></span></span>
</div>
<div id="canvas_list">
<canvas id="the-canvas"></canvas>
</div>
<script src="js/pdfjs/pdf.js"></script>
<script src="js/pdfjs/pdf.worker.js"></script>
<script>
var url = '/pdf/demo1.pdf';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 0.8;
/**
* 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 canvasList = document.getElementById('canvas_list');
var canvas = document.createElement('canvas');
canvasList.appendChild(canvas);
canvasList.appendChild(document.createElement('hr'))
var ctx = canvas.getContext('2d');
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;
}
});
});
}
/**
* 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);
}
}
/**
* Asynchronously downloads PDF.
*/
PDFJS.getDocument(url).then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = '總頁數:' + pdfDoc.numPages;
for(var $i =1 ; $i <= pdfDoc.numPages ; $i++) {
// Initial/first page rendering
renderPage($i);
}
});
</script>
</html>