Convert examples/node/pdf2png/pdf2png.js to await/async

This commit is contained in:
Jane-Kotovich 2021-10-14 13:26:10 +10:00
parent f6d9d91965
commit 37d90ec378

View File

@ -70,41 +70,40 @@ const loadingTask = pdfjsLib.getDocument({
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
standardFontDataUrl: STANDARD_FONT_DATA_URL, standardFontDataUrl: STANDARD_FONT_DATA_URL,
}); });
loadingTask.promise
.then(function (pdfDocument) { (async function () {
try {
const pdfDocument = await loadingTask.promise;
console.log("# PDF document loaded."); console.log("# PDF document loaded.");
// Get the first page. // Get the first page.
pdfDocument.getPage(1).then(function (page) { const page = await pdfDocument.getPage(1);
// Render the page on a Node canvas with 100% scale. // Render the page on a Node canvas with 100% scale.
const viewport = page.getViewport({ scale: 1.0 }); const viewport = page.getViewport({ scale: 1.0 });
const canvasFactory = new NodeCanvasFactory(); const canvasFactory = new NodeCanvasFactory();
const canvasAndContext = canvasFactory.create( const canvasAndContext = canvasFactory.create(
viewport.width, viewport.width,
viewport.height viewport.height
); );
const renderContext = { const renderContext = {
canvasContext: canvasAndContext.context, canvasContext: canvasAndContext.context,
viewport, viewport,
canvasFactory, canvasFactory,
}; };
const renderTask = page.render(renderContext); const renderTask = page.render(renderContext);
renderTask.promise.then(function () { await renderTask.promise;
// Convert the canvas to an image buffer. // Convert the canvas to an image buffer.
const image = canvasAndContext.canvas.toBuffer(); const image = canvasAndContext.canvas.toBuffer();
fs.writeFile("output.png", image, function (error) { fs.writeFile("output.png", image, function (error) {
if (error) { if (error) {
console.error("Error: " + error); console.error("Error: " + error);
} else { } else {
console.log( console.log(
"Finished converting first page of PDF file to a PNG image." "Finished converting first page of PDF file to a PNG image."
); );
} }
});
});
}); });
}) } catch (reason) {
.catch(function (reason) {
console.log(reason); console.log(reason);
}); }
})();