合并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 PdfFileMerger
import 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文件。请根据你的需要选择合适的库进行操作。