我的应用程序具有显示pdf收据的功能。收据是动态生成的。我为此目的使用了pdf.js插件。
我要求为pdf页面设置缩放。这里是生成没有缩放因子的pdf文件的工作代码。但是设置缩放系数很困难。
pdfData: function() {
$("#pdfContainer").empty();
scale = 3.5; //Set this to whatever you want. This is basically the "zoom" factor for the PDF.
var pdfBase64 = pdfBase64Res;
currentPage = 1;
pages = [];
// Converts a base64 string into a Uint8Array
function base64ToUint8Array(base64) {
var base64New = base64.replace(/\s/g, '');
var raw = atob(base64New); //This is a native function that decodes a base64-encoded string.
var uint8Array = new Uint8Array(new ArrayBuffer(raw.length));
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
function loadPdf(pdfData) {
PDFJS.disableWorker = true; //Not using web workers. Not disabling results in an error. This line is
//missing in the example code for rendering a pdf.
var pdf = PDFJS.getDocument(pdfData);
pdf.then(renderPdf);
}
function renderPdf(pdf) {
alert("total page numbers :" + pdf.numPages);
totalPages = pdf.numPages;
pdf.getPage(currentPage).then(renderPage);
function renderPage(page) {
pagesNew = page;
height = 768;
viewport = page.getViewport(1);
scale = height / viewport.height;
scaledViewport = page.getViewport(scale);
canvas = document.createElement('canvas');
// canvas = document.createElement("<canvas>");
context = canvas.getContext('2d');
canvas.height = scaledViewport.height;
canvas.width = scaledViewport.width;
// element=document.getElementById("pdfContainer");
renderContext = {
canvasContext: context,
viewport: scaledViewport
};
pagesNew.render(renderContext).then(function() {
if (totalPages == 1) {
jQuery("#pdfContainer").append(canvas);
} else if (currentPage <= pdf.numPages) {
//alert('Current page'+currentPage);
pdf.getPage(currentPage).then(renderPage);
pages[currentPage] = canvas;
console.log(pages[currentPage]);
++currentPage;
// alert("before for loop");
} else {
//alert('in else');
//alert("alert(pages.length);"+pages.length);
for (var i = 1; i < pages.length; i++) {
//alert(i);
var element = document.getElementById("pdfContainer");
element.appendChild(pages[i]);
console.log(element.appendChild(pages[i]));
}
}
});
}
}
var pdfData = base64ToUint8Array(pdfBase64);
loadPdf(pdfData);