是否可以使用node js将pdf文件拆分为其所拥有的页数并将这些文件保存在文件夹中?
eol*_*eol 23
使用pdf-lib这应该相当简单。这段代码应该可以帮助您入门,当然它仍然需要一些错误处理:
const fs = require('fs');
const PDFDocument = require('pdf-lib').PDFDocument;
async function splitPdf(pathToPdf) {
const docmentAsBytes = await fs.promises.readFile(pathToPdf);
// Load your PDFDocument
const pdfDoc = await PDFDocument.load(docmentAsBytes)
const numberOfPages = pdfDoc.getPages().length;
for (let i = 0; i < numberOfPages; i++) {
// Create a new "sub" document
const subDocument = await PDFDocument.create();
// copy the page at current index
const [copiedPage] = await subDocument.copyPages(pdfDoc, [i])
subDocument.addPage(copiedPage);
const pdfBytes = await subDocument.save()
await writePdfBytesToFile(`file-${i + 1}.pdf`, pdfBytes);
}
}
function writePdfBytesToFile(fileName, pdfBytes) {
return fs.promises.writeFile(fileName, pdfBytes);
}
(async () => {
await splitPdf("./path-to-your-file.pdf");
})();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10528 次 |
最近记录: |