import os
from PyPDF2 import PdfMerger
from datetime import datetime
"""
介绍:
将 merge_input_folder 文件夹下的所有pdf文件合并成为一个pdf文件
使用方法:
1.首先在本目录下新建一个 merge_input_folder 文件夹
2.将需要合并的pdf文件放入到其中(注意顺序)
3.修改 output_file_name 变量的值
4.运行代码
结果:
合并后的文件在 merge_output_folder 目录下
"""
cur_path = os.path.dirname(__file__)
def merge_pdfs(input_folder, output_pdf_path):
merger = PdfMerger()
for root, _, files in os.walk(input_folder):
for filename in files:
if filename.endswith(".pdf"):
file_path = os.path.join(root, filename)
merger.append(file_path)
with open(output_pdf_path, "wb") as output_file:
merger.write(output_file)
print(f"Merged PDF saved at {output_pdf_path}")
def get_output_file_name(output_file_name):
formatted_time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S_")
dir_path = cur_path + "/merge_output_folder/"
if not os.path.exists(dir_path):
os.makedirs(dir_path)
return dir_path + formatted_time + output_file_name + ".pdf"
if __name__ == "__main__":
output_file_name = "name"
input_folder = cur_path + "/merge_input_folder"
output_pdf_path = get_output_file_name(output_file_name)
merge_pdfs(input_folder, output_pdf_path)