我正在Web应用程序中使用pdf.js呈现pdf文件。
我注意到,只有当devicePixelRatio大于1时,查看器才会部分渲染图像。
我的目标是在保留devicePixelRatio的同时呈现pdf文件。
请帮助。
PDF.js版本: 稳定(v2.1.266)
这是我的代码:
index.html
<div class="pdf-viewer">
<div id="pageContainer" class="pdf-page"></div>
</div>
index.js
pdfjsLib.workerSrc = '/vendor/assets/pdfjs/build/pdf.worker.js'
var pdfDoc;
var scale = 1;
var loadingTask = pdfjsLib.getDocument({
url: #{pdf-url},
cMapUrl: '/cmaps/',
cMapPacked: true
})
loadingTask.promise.then(function(pdf){
pdfDoc = pdf;
var viewer = document.getElementById('pageContainer')
for(page = 1; page <= pdf.numPages; page++){
var canvas = document.createElement('canvas');
if(page == pdf.numPages){
canvas.className = 'pdf-page-canvas d-block m-auto'
}else{
canvas.className = 'pdf-page-canvas d-block m-auto pb-2'
}
viewer.appendChild(canvas);
renderPage(page, canvas, viewer)
}
})
function renderPage(pageNum, canvas, container){
pdfDoc.getPage(pageNum).then(function(page){
var originalViewPort = page.getViewport({scale: scale})
var aspectScale;
var isLandscape = true;
if(originalViewPort.height > originalViewPort.width){
isLandscape = false;
}
if(isLandscape){
aspectScale = Math.max((container.clientWidth / originalViewPort.width), (container.clientHeight / originalViewPort.height))
}else{
aspectScale = Math.min((container.clientWidth / originalViewPort.width), (container.clientHeight / originalViewPort.height))
}
var viewport = page.getViewport({scale: aspectScale})
var ctx = canvas.getContext('2d')
canvas.width = (originalViewPort.width * aspectScale) * window.devicePixelRatio
canvas.height = (originalViewPort.height * aspectScale) * window.devicePixelRatio
canvas.style.width = String(originalViewPort.width * aspectScale) + "px";
canvas.style.height = String(originalViewPort.height * aspectScale) + "px";
ctx.scale(window.devicePixelRatio,window.devicePixelRatio)
page.render({canvasContext: ctx, viewport: viewport});
})
}
预期行为的屏幕截图: image1
实际行为的屏幕截图: image2