合并PDF文件内容可以通过使用Python的第三方库来实现,以下是使用Spire.PDF和PyPDF2库合并PDF文件的两种方法:
使用Spire.PDF库
1. 安装Spire.PDF库:
pip install Spire.PDF
2. 合并PDF文件的代码示例:
from spire.pdf.common import *from spire.pdf import *import os指定文件夹路径folder_path = "G:/文档/"遍历文件夹中的文件并创建文件路径列表pdf_files = []for file_name in sorted(os.listdir(folder_path)):if file_name.endswith(".pdf"):file_path = os.path.join(folder_path, file_name)pdf_files.append(file_path)合并PDF文档pdf = PdfDocument.MergeFiles(pdf_files)保存结果文档pdf.Save("output/合并PDF.pdf", FileFormat.PDF)pdf.Close()

使用PyPDF2库
1. 安装PyPDF2库:
pip install PyPDF2
2. 合并PDF文件的代码示例:
from PyPDF2 import PdfFileMergerimport os指定文件夹路径folder_path = "G:/文档/"创建PdfFileMerger对象merger = PdfFileMerger()遍历文件夹中的PDF文件for filename in os.listdir(folder_path):if filename.endswith(".pdf"):file_path = os.path.join(folder_path, filename)merger.append(open(file_path, 'rb'))合并PDF文件并保存with open('newfile.pdf', 'wb') as fout:merger.write(fout)
