如何用Python为多文件夹下的大量PDF添加指定页面
解决方案:批量合并固定PDF页面到单页PDF(无Python PDF库依赖)
由于服务器难以安装Python PDF处理库,我们可以用Python调用Ghostscript(轻量免费的PDF处理工具,易部署)来实现需求。以下是完整脚本及步骤:
前置准备
- 下载Ghostscript对应服务器系统的版本,安装后将
gswin64c.exe(64位)或gswin32c.exe(32位)所在路径加入系统环境变量,也可以在脚本里直接指定工具绝对路径 - 确认目标PDF均为单页格式(脚本会自动校验,仅处理单页文件)
Python脚本
import os import subprocess import tempfile # 配置参数 FIXED_PAGE_PDF = r"C:\Files\page2.pdf" TARGET_ROOT = r"C:\Folders" # 如果Ghostscript未加入环境变量,直接指定绝对路径,示例:GS_PATH = r"C:\Program Files\gs\gs10.02.1\bin\gswin64c.exe" GS_PATH = "gswin64c.exe" def get_pdf_page_count(pdf_path): """调用Ghostscript获取PDF页数""" cmd = [ GS_PATH, "-q", "-dNODISPLAY", "-c", f"('{pdf_path.replace('\\', '/')}') (r) file runpdfbegin pdfpagecount = quit" ] try: result = subprocess.run(cmd, capture_output=True, text=True, check=True) return int(result.stdout.strip()) except (subprocess.CalledProcessError, ValueError): print(f"无法获取文件页数:{pdf_path}") return 0 def merge_pdfs(source_pdf, fixed_pdf, output_pdf): """调用Ghostscript合并两个PDF""" cmd = [ GS_PATH, "-dBATCH", "-dNOPAUSE", "-q", "-sDEVICE=pdfwrite", "-dPDFSETTINGS=/prepress", # 保留原PDF高质量输出 "-sOutputFile=" + output_pdf, source_pdf, fixed_pdf ] try: subprocess.run(cmd, check=True) return True except subprocess.CalledProcessError: print(f"合并失败:{source_pdf}") return False def main(): # 遍历目标目录及所有子文件夹的PDF for root, _, files in os.walk(TARGET_ROOT): for file in files: if file.lower().endswith(".pdf"): pdf_path = os.path.join(root, file) # 校验是否为单页PDF page_count = get_pdf_page_count(pdf_path) if page_count != 1: print(f"跳过非单页PDF:{pdf_path}") continue # 创建临时文件存储合并结果,避免直接覆盖原文件导致异常 with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file: temp_pdf = temp_file.name # 执行合并操作 if merge_pdfs(pdf_path, FIXED_PAGE_PDF, temp_pdf): # 替换原文件 os.replace(temp_pdf, pdf_path) print(f"处理完成:{pdf_path}") else: # 合并失败,清理临时文件 os.remove(temp_pdf) if __name__ == "__main__": main()
使用说明
- 将脚本保存为
merge_pdfs.py - 根据服务器实际情况调整
FIXED_PAGE_PDF、TARGET_ROOT和GS_PATH参数 - 在服务器终端运行:
python merge_pdfs.py
注意事项
- 建议先在测试文件夹验证脚本,避免误操作
- 脚本会直接覆盖原PDF文件,如需保留原文件可自行添加备份逻辑(例如复制原文件到指定备份目录)
- 处理大量文件时,可添加进度统计代码优化体验
- Ghostscript的
-dPDFSETTINGS参数可按需调整:/screen(低质量)、/ebook(中等质量)、/prepress(高质量)
内容的提问来源于stack exchange,提问作者Maxence MELIN
相关产品推荐
相关产品推荐

