提示: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
四、项目结构
五、使用方法
六、效果
总结
踩坑路漫漫长@~@
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » nodejs小工具--pdf拆分
发表评论 取消回复