Using pdfjs to extract pages as images from a PDF file and then making an AJAX call to send and receive data from the server is proving to be challenging. The implementation for iterating through the pages in the PDF was sourced from:
The issue lies in properly structuring the syntax for the promise that triggers the AJAX function only after all required details have been retrieved.
This is the current code snippet:
getDataUrlsAndSizesFromPdf(file).then(proceedAndCheckOnServer(file));
const getDataUrlsAndSizesFromPdf = function(file) {
PDFJS.disableWorker = true;
fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
return new Promise(function(resolve, reject) {
fileReader.onload = function(ev) {
PDFJS.getDocument(fileReader.result).then(function (pdf) {
var pdfDocument = pdf;
var pagesPromises = [];
for (var i = 0; i < pdf.pdfInfo.numPages; i++) {
var pageNum = i + 1;
pagesPromises.push(getImageUrl(pageNum, pdfDocument));
}
Promise.all(pagesPromises).then(function () {
console.log(pdfPagesInfo);
resolve();
}, function () {
console.log('failed');
reject();
});
}, function (reason) {
console.error(reason);
});
}
});
}
function getImageUrl() {
return new Promise(function (resolve, reject) {
PDFDocumentInstance.getPage(pageNum).then(function (pdfPage) {
var scale = 1;
var viewport = pdfPage.getViewport(scale);
var canvas = document.getElementById('dummy-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var task = pdfPage.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
var sizesArr = {
height : viewport.height,
width : viewport.width
}
pdfPagesInfo.sizes[pageNum.toString()] = sizesArr
pdfPagesInfo.images[pageNum.toString()] = canvas.toDataURL('image/jpeg');
resolve();
});
});
});
}
function proceedAndCheckOnServer() {
....
}
The main aim is to ensure that "proceedAndCheckOnServer()" gets executed only after all the necessary details have been fetched from "getImageUrl()". Currently, the execution jumps directly to "proceedAndCheckOnServer()" without waiting for the resolution of the promise from "getDataUrlsAndSizesFromPdf". As I am fairly new to JavaScript promises, any help with proper syntax would be greatly appreciated.