PDFJS:在 NodeJS 中使用 async/await 读取所有页面
PDFJS 有一个官方示例 - 除其他功能外,它从 PDF 文档读取所有页面。
但是,他们基于 promise 的方法相当复杂,难以理解和编写。幸运的是,使用 async/await(从 NodeJS 8.x 开始支持)有更简单的方法。
我使用 bereich 库(bereich 是德语中的范围)来生成页码数组(1..numPages)。
使用以下命令安装所需的库
install_pdfjs.sh
npm install pdfjs-dist bereich以下是源代码示例:
read_pdf_pages.js
const pdfjs = require('pdfjs-dist');
const bereich = require('bereich');
async function readPDFPages() {
const pdf = await pdfjs.getDocument('mypdf.pdf');
const numPages = pdf.numPages;
const pageNumbers = Array.from(bereich(1, numPages));
// 开始读取所有页面 1...numPages
const promises = pageNumbers.map(pageNo => pdf.getPage(pageNo));
// 等待所有页面被读取
const pages = await Promise.all(promises);
// 你可以在此对页面做些处理。
return pages;
}
readPDFPages().then(pages => {
console.log(pages)
}).catch(err => {
console.error(`Error while reading PDF: ${err}`)
})Check out similar posts by category:
Javascript, PDF
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow