提示:pdf拆分

前言

一、pdf-lib

pdf-lib

npm install pdf-lib --save-dev

在这里插入图片描述

二、pdf拆分功能

index.js

// 启动express服务
const express = require('express');
const app = express();

app.listen(3000,()=>{
    console.log('http://localhost:3000');
});

// 文件读写
const fs = require('fs');
// 路径
const path = require('path');
// pdf-lib
const pdfLib = require('pdf-lib');
// PDFDocument
const pdfDoc = pdfLib.PDFDocument;

// 拆分pdf文件
const splitPdf = async (pdfPath,name) => {
    // 文件bytes
    const bytes = await fs.promises.readFile(pdfPath);
    // pdf数据
    const pdfData = await pdfDoc.load(bytes)
    // pdf页数
    const pages = pdfData.getPages().length;
    for (let i = 0; i < pages; i++) {
        const doc = await pdfDoc.create();
        const [ page ] = await doc.copyPages(pdfData, [i])
        doc.addPage(page);
        const pdfBytes = await doc.save()
        await fs.promises.writeFile(`./output/${name||'pdf'}-${i + 1}.pdf`, pdfBytes);
    }
    console.log(`拆分为${pages}个pdf文件`)
}

// 扫描文件夹下的.pdf文件
const searchPdf =  (dir, callback) => {
    // 读取文件夹下数据
    fs.readdir(dir, (fileErr, files) => {
        if (fileErr)return console.error('Error:', fileErr);
        // 遍历文件夹下的文件
        files.forEach((file) => {
            // file路径
            let fullPath = path.join(dir, file);
            fs.stat(fullPath, async (err, state) => {
                if (err)return console.error('Error:', err);
                // 如果是文件夹,继续扫描读取到的文件夹
                if (state.isDirectory()) return searchPdf(fullPath);
                // 是否为.pdf文件
                if (path.extname(file).toLowerCase() == '.pdf') {
                    console.log('扫描到pdf文件,路径:', fullPath,file);
                    // 拆分pdf文件
                    let name = file.split('.pdf')[0];
                    await splitPdf(fullPath,name);
                    
                }
            });
        });
    });
}

searchPdf('./source');

三、双击运行bat文件

run.bat

@echo off
cd /d "%~dp0"
node index.js

四、项目结构

在这里插入图片描述

五、使用方法

在这里插入图片描述

六、效果

在这里插入图片描述

总结

踩坑路漫漫长@~@

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部