我想在画布html标签中显示具有多个页面的PDF文件,如下所示:
<canvas class="pdfViewer hidden" style="border: solid 1px black;width: 100%;"></canvas>
我正在使用的库是jsPDF。但是,仅使用此代码即可显示单页预览。
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
$("input[type='file']").on("change", function (e) {
$("button[name='Preview']").removeClass("hidden");
var file = e.target.files[0]
if (file.type == "application/pdf") {
var fileReader = new FileReader();
fileReader.onload = function () {
var pdfData = new Uint8Array(this.result);
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({ data: pdfData });
loadingTask.promise.then(function (pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function (page) {
console.log('Page loaded');
var scale = 1.5;
var viewport = page.getViewport({ scale: scale });
// Prepare canvas using PDF page dimensions
var canvas = $(".pdfViewer")[0];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
console.log('Page rendered');
});
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
};
fileReader.readAsArrayBuffer(file);
}
});
我希望它分多页显示,例如PDF为5-10页,那么应该显示很多页。
答案 0 :(得分:0)
<canvas>
来呈现多个页面。我修改了您的代码,它的工作原理如下:
HTML
<div id='pdf-viewer'></div>
JavaScript
var thePdf = null;
var scale = 1.5;
function renderPage(pageNumber, canvas) {
thePdf.getPage(pageNumber).then(function (page) {
viewport = page.getViewport({ scale: scale });
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({ canvasContext: canvas.getContext('2d'), viewport: viewport });
})
};
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
$("input[type='file']").on("change", function (e) {
$("button[name='Preview']").removeClass("hidden");
var file = e.target.files[0]
if (file.type == "application/pdf") {
var fileReader = new FileReader();
fileReader.onload = function () {
var pdfData = new Uint8Array(this.result);
var loadingTask = pdfjsLib.getDocument({ data: pdfData });
loadingTask.promise.then(function (pdf) {
thePdf = pdf;
viewer = document.getElementById('pdf-viewer');
for(page = 1; page <= pdf.numPages; page++) {
canvas = document.createElement("canvas");
canvas.className = 'pdf-page-canvas';
viewer.appendChild(canvas);
renderPage(page, canvas);
}
}, function (reason) {
// PDF loading error
console.error(reason);
});
};
fileReader.readAsArrayBuffer(file);
}
});