Python合并两个PDF文件 - 详解

引言

在办公自动化场景中,合并多个PDF文件是常见需求。本文将介绍如何使用Python实现PDF合并功能,重点对比PyPDF2和pdfplumber两种实现方案,并提供完整可运行的代码示例。

方案一:使用PyPDF2库(推荐)

特性

  • 官方维护的成熟库
  • 支持PDF1.4到PDF2.0标准
  • 自动处理页面尺寸适配

安装方法

pip install pypdf2

完整代码示例

from PyPDF2 import PdfFileMerger
def merge_pdfs(pdf_list, output_path):
merger = PdfFileMerger()
for pdf in pdf_list:
try:
with open(pdf, 'rb') as f:
merger.append(f)
except Exception as e:
print(f"处理文件 {pdf
} 时出错: {
str(e)
}")
with open(output_path, 'wb') as outfile:
merger.write(outfile)
merger.close()
# 使用示例
merge_pdfs(['file1.pdf', 'file2.pdf'], 'merged.pdf')

方案二:使用pdfplumber库

特性

  • 支持更复杂的PDF解析
  • 可同时提取文本和表格数据
  • 适合需要预处理的场景

安装方法

pip install pdfplumber

完整代码示例

import pdfplumber
def merge_pdfs_advanced(input_paths, output_path):
with pdfplumber.PDF.open(input_paths[0]) as first_pdf:
writer = first_pdf.copy()
for path in input_paths[1:]:
with pdfplumber.PDF.open(path) as pdf:
for page in pdf.pages:
writer.add_page(page)
with open(output_path, 'wb') as outfile:
writer.write(outfile)
# 使用示例
merge_pdfs_advanced(['doc1.pdf', 'doc2.pdf'], 'combined.pdf')

方案对比

特性PyPDF2pdfplumber
代码复杂度简单中等
执行效率
特殊格式支持良好优秀
内存占用

高级技巧

  1. 处理加密文件
# PyPDF2示例
merger.append(pdf_path, password='your_password')
  1. 保留书签
# 需要使用PyPDF2的Bookmark特性
merger.addBookmark("Chapter 1", 0)
  1. 异常处理增强
try:
# 合并操作
except PyPDF2.utils.PdfMetricsError as e:
print("页面尺寸不匹配:", e)
except Exception as e:
print("未知错误:", e)

最佳实践建议

  1. 优先使用PyPDF2方案,其性能和稳定性经过长期验证
  2. 处理超过50个文件时建议分批合并
  3. 合并前检查文件是否加密
  4. 输出文件建议使用.pdf扩展名
  5. 测试合并效果时建议先合并前两个文件验证

常见问题解答

Q1: 合并后的文件乱码怎么办?
A: 检查原始文件是否包含特殊字体,建议使用pdfplumber方案并指定字体编码

Q2: 如何保持原文件质量?
A: 两种方案都会保留原始质量,但建议不要重复合并已合并的文件

Q3: 支持PDF/A格式吗?
A: PyPDF2 3.0.0+ 版本支持PDF/A-1b标准

总结

对于大多数常规合并需求,推荐使用PyPDF2方案。当需要处理复杂PDF结构或需要精细控制时,可以选择pdfplumber方案。两种方案都提供了基础的异常处理机制,实际使用时可根据具体需求进行扩展。

posted @ 2025-08-09 21:09  yjbjingcha  阅读(152)  评论(0)    收藏  举报