合并PDF文件在Python中可以通过多种库实现,以下是使用`Spire.PDF`和`PyPDF2`两个库的示例代码。
使用Spire.PDF合并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合并PDF
from PyPDF2 import PdfFileMergerimport os列出目录中的所有文件files = os.listdir()创建PdfFileMerger对象merger = PdfFileMerger()遍历所有文件,合并PDF文件for file in files:只合并PDF文件if file.endswith(".pdf"):merger.append(open(file, 'rb'))将合并后的内容写入新文件with open('newfile.pdf', 'wb') as fout:merger.write(fout)
以上代码展示了如何使用`Spire.PDF`和`PyPDF2`库合并PDF文件。请根据你的需要选择合适的库进行操作。
