将pdf拆分为多个页面,最好将其拆分为多个页面,并使用node js将各种文件保存在文件夹中

You*_*per 7 pdf node.js

是否可以使用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)