合并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 PdfFileMerger
import 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)