拆分PDF.html 办公小工具
将下面的脚本拷贝放到一个空白的html文件中,然后保存,通过浏览器打开后就可以拆分pdf文件了。
拆分PDF.html
<!DOCTYPE html>
<html>
<head><title>PDF拆分工具</title><script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.17.1/pdf-lib.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script> <style>.container { max-width: 800px; margin: 20px auto; padding: 20px; }.drop-zone { border: 2px dashed #ccc; padding: 20px; text-align: center; }#pageInput { width: 300px; padding: 5px; margin: 10px 0; }#status { color: #666; margin: 10px 0; }#splitBtn { background: #2196F3; color: white; padding: 10px 20px; border: none; cursor: pointer; }</style>
</head>
<body><div class="container"><div class="drop-zone" id="dropZone">拖拽PDF文件至此 或 <input type="file" id="fileInput" accept=".pdf"></div><input type="text" id="pageInput" placeholder="输入页码范围 (如: 1-5,7,9-12)"><div id="status">等待文件上传...</div><button id="splitBtn" onclick="splitPDF()">开始拆分</button></div><script>
let selectedFile = null;// 文件处理
document.getElementById('dropZone').ondragover = (e) => {e.preventDefault(); e.target.style.borderColor = '#2196F3';
};document.getElementById('dropZone').ondrop = (e) => {e.preventDefault(); const file = e.dataTransfer.files[0]; if(file.type === 'application/pdf') {selectedFile = file;updateStatus(`已选择文件: ${file.name}`); }
};document.getElementById('fileInput').onchange = (e) => {const file = e.target.files[0]; if(file.type === 'application/pdf') {selectedFile = file;updateStatus(`已选择文件: ${file.name}`); }
};// 核心拆分逻辑
async function splitPDF() {if(!selectedFile) return alert('请先选择PDF文件');const pages = parsePageRange(document.getElementById('pageInput').value); if(pages.length === 0) return alert('请输入有效页码范围');try {const pdfBytes = await selectedFile.arrayBuffer(); const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes); const newPdf = await PDFLib.PDFDocument.create(); // 复制指定页面 const copiedPages = await newPdf.copyPages(pdfDoc, pages.map(p => p-1));copiedPages.forEach(page => newPdf.addPage(page)); // 生成新文件 const newPdfBytes = await newPdf.save(); saveAs(new Blob([newPdfBytes], {type: 'application/pdf'}), `拆分结果_${selectedFile.name}`); updateStatus("拆分完成,开始下载...");} catch (error) {console.error(' 拆分失败:', error);alert('文件处理失败,请检查PDF格式');}
}// 页码解析器 (支持格式: 1-5,7,9-12)
function parsePageRange(input) {const pages = new Set();const ranges = input.split(','); ranges.forEach(range => {const match = range.match(/^(\d+)(?:-(\d+))?$/); if(match) {const start = parseInt(match[1]);const end = match[2] ? parseInt(match[2]) : start;for(let i = start; i <= end; i++) {pages.add(i); }}});return Array.from(pages).sort((a,b) => a - b);
}function updateStatus(text) {document.getElementById('status').innerHTML = text;
}
</script>
</body>
</html>