我正在尝试使用 PDF.js 阅读整个 .pdf 文档,然后在单个画布上呈现所有页面。
我的想法:将每个页面渲染到画布上并获取 ImageData (context.getImageData()),清除画布做下一页。我将所有 ImageDatas 存储在一个数组中,一旦所有页面都在那里,我想将数组中的所有 ImageDatas 放到一个画布上。
var pdf = null;
PDFJS.disableWorker = true;
var pages = new Array();
//Prepare some things
var canvas = document.getElementById('cv');
var context = canvas.getContext('2d');
var scale = 1.5;
PDFJS.getDocument(url).then(function getPdfHelloWorld(_pdf) {
pdf = _pdf;
//Render all the pages on a single canvas
for(var i = 1; i <= pdf.numPages; i ++){
pdf.getPage(i).then(function getPage(page){
var viewport = page.getViewport(scale);
canvas.width = viewport.width;
canvas.height = viewport.height;
page.render({canvasContext: context, viewport: viewport});
pages[i-1] = context.getImageData(0, 0, canvas.width, canvas.height);
context.clearRect(0, 0, canvas.width, canvas.height);
p.Out("pre-rendered page " + i);
});
}
//Now we have all 'dem Pages in "pages" and need to render 'em out
canvas.height = 0;
var start = 0;
for(var i = 0; i < pages.length; i++){
if(canvas.width < pages[i].width) canvas.width = pages[i].width;
canvas.height = canvas.height + pages[i].height;
context.putImageData(pages[i], 0, start);
start += pages[i].height;
}
});
所以从我理解的方式来看,这应该有效,对吧?当我运行它时,我最终得到的画布足够大,可以包含 pdf 的所有页面,但不显示 pdf ......
感谢您的帮助。