多个word 文档 转化成 PDF 文件, 最后合并成一个PDF文件
|
import os |
|
from win32com import client |
|
from PyPDF2 import PdfMerger # 使用PdfMerger |
|
|
|
|
|
def wordToPdf(folder): # 将 多个word 文档 转化成 PDF 文件 |
|
os.chdir(folder) |
|
file_type = 'docx' |
|
out_folder = folder + "\\PDF" |
|
if not os.path.exists(out_folder): |
|
print('Creating output folder...') |
|
os.makedirs(out_folder) |
|
print(out_folder, 'created.') |
|
else: |
|
print(out_folder, 'already exists.\n') |
|
# print(os.listdir(".")) |
|
# exit() |
|
try: |
|
for files in os.listdir("."): |
|
if files.endswith(".docx"): |
|
out_name = files.replace(file_type, r"pdf") |
|
in_file = os.path.abspath(folder + "\\" + files) |
|
out_file = os.path.abspath(out_folder + "\\" + out_name) |
|
print(in_file, 'Exporting', out_file, "\n\n") |
|
word = client.DispatchEx("Word.Application") |
|
word.Visible = 0 # 后台运行 |
|
word.DisplayAlerts = 0 # 不显示,不警告 |
|
doc = word.Documents.Open(in_file, Encoding='gbk') |
|
doc.SaveAs(out_file, FileFormat=17) |
|
doc.Close() |
|
word.Quit() |
|
except Exception as e: |
|
print("出错了!", e) |
|
|
|
|
|
def mergePDF(folder): # 将多个 PDF 文件,合并成一个PDF文件 |
|
# 设置文件所在位置 |
|
target_path = folder + "\\PDF" # pdf文件所在文件夹绝对路径 |
|
pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')] |
|
pdf_lst = [os.path.join(target_path, filename) for filename in pdf_lst] |
|
|
|
os.chdir(target_path) |
|
out_folder = target_path + "\\MPDF" |
|
if not os.path.exists(out_folder): |
|
print('Creating output folder...') |
|
os.makedirs(out_folder) |
|
print(out_folder, 'created.') |
|
else: |
|
print(out_folder, 'already exists.\n') |
|
|
|
# 调用合并方法 |
|
file_merger = PdfMerger() # 调用 |
|
for pdf in pdf_lst: |
|
file_merger.append(pdf) # 合并pdf文件 |
|
# 选择合并后文件存储位置 |
|
out_name = "MergePDF.pdf" |
|
out_file = os.path.abspath(out_folder + "\\" + out_name) |
|
file_merger.write(out_file) # 合并后文件所在位置 |
|
print("合并完成") |
|
|
|
if __name__ == '__main__': |
|
folder = r"J:\1_7" |
|
wordToPdf(folder) |
|
mergePDF(folder) |