由于pywin32库的限制,在Mac系统上无法利用python+pywin32调用office对word文件进行批量转换pdf的处理。为了解决该问题,将通过docx2pdf调用office 365对word文件进行批量pdf的转换,但是对比Windows系统上的pywin32,转换相对较慢,而且只支持docx格式,下面将方法进行简单介绍,并将两者进行结合,使得word文件的批量转换可以在Mac系统上进行。
由于pywin32是Windows系统下的库,不支持Mac系统,所以需要在Mac系统下将相关导入以及转换的代码注释掉;在Mac系统下则可以根据自身需求选择利用pywin32或者docx2pdf,一定要注意不同系统下路径的编写方式!!!
第一步:安装pywin32(只支持Windows下安装)、docx2pdf
pip3 install pywin32 -i https://pypi.douban.com/simple
pip3 install docx2pdf -i https://pypi.douban.com/simple
第二步:示例代码如下,可根据自身需求进行修改相应文件位置等操作
from win32com.client import constants, gencache # 导入win32com模块中相应函数,用来启动word
import platform
from os import walk
import os
from multiprocessing import Pool
from docx2pdf import convert
# 获取所有pdf文件(pdf保存目录、脚本所在目录)
def getPFiles():
global pdfPath
if plat == 'Darwin': # mac系统下修改后文件名
pdfPath = "/Users/hanyang/Desktop/pdf" # 所要保存pdf文件的位置
elif plat == 'win32': # windows系统下修改后文件名
pdfPath = "C:\\Users\\Administrator\\Desktop\\pdf"
else:
pass
pathList = [prePath, pdfPath]
pFiles = []
i = 0
if not os.path.exists(pdfPath):
os.makedirs(pdfPath) # 如果要保存pdf的目录不存在则进行创建
else:
while i < 2:
for root, dirs, Files in walk(pathList[i]):
for file in Files:
if file.endswith(".pdf"):
pFiles.append(file)
else:
pass
i += 1
return pFiles
# 获取脚本执行目录中所有word文件列表(不包含已存在pdf格式的word文件)
def getWFiles(pFiles):
"""
:param pFiles:所有的pdf文件(脚本所在目录的根目录下的pdf文件以及所要保存pdf文件的位置目录下的pdf文件)
"""
wFiles = []
for root, dirs, files in walk(prePath):
for file in files:
if file.endswith('doc') or file.endswith('docx'):
if (file.split('.')[0] + '.pdf') not in pFiles:
wFiles.append(os.path.join(root, file))
else:
pass
else:
pass
return list(set(wFiles))
# 修改pdf保存路径和名称,前缀和后缀可根据需求修改
def getNewName(prefix, suffix, file):
"""
:param prefix:修改后的pdf文件名前缀,例如原文件名为1,添加前缀?后为?1
:param suffix:修改后的pdf文件名后缀,例如原文件名为1,添加后缀-后为1-
:param file:需要保存的修改前pdf文件的完整路径
"""
if plat == 'Darwin': # mac系统下修改后文件名
newFile = prefix + file[file.rfind("/") + 1:file.find(".")] + suffix + file[file.rfind("."):]
elif plat == 'win32': # windows系统下修改后文件名
newFile = prefix + file[file.rfind("\\") + 1:file.find(".")] + suffix + file[file.rfind("."):]
else:
newFile = file
newName = newFile.replace(newFile.split('.')[1], 'pdf')
return newName
# 获取所有的word文件路径以及转换后的pdf文件路径
def resolvePath(pFiles):
"""
:param pFiles:所有的pdf文件(脚本所在目录的根目录下的pdf文件以及所要保存pdf文件的位置目录下的pdf文件)
"""
pAbPath = []
wAbPath = getWFiles(pFiles)
i = 0
while i < len(wAbPath):
# 判断修改pdf文件名后的文件是否已经存在,如果存在则把该文件路径从word文件列表中删除
if (getNewName(prefix, suffix, wAbPath[i])) in pFiles:
wAbPath.remove(wAbPath[i])
i -= 1
else:
newFile = getNewName(prefix, suffix, wAbPath[i])
pAbPath.append(os.path.join(pdfPath, newFile))
i += 1
return wAbPath, pAbPath
# windows系统下对word文件进行转换并保存
def d2p(input_file, newName):
try:
print("------" + input_file + "---Concert Start------")
word = gencache.EnsureDispatch('Word.Application')
wFile = word.Documents.Open(input_file, ReadOnly=1) # 打开word
wFile.SaveAs(newName, FileFormat=17) # 以pdf格式保存
word.Quit() # 退出word
print("------" + newName + "---Concert Finished!!!------")
except:
print("Please make sure that the word application has been successfully installed!!!")
# windows系统下word转换pdf进程池封装调用
def d2pAsyPool():
pools = Pool(3) # 定义进程池,最大进程池为3
global wAllFiles, pdfFiles
if wAllFiles != []:
for i in range(len(wAllFiles)):
# 调用word转换为pdf方法,并传递参数(异步执行)
pools.apply_async(d2p, args=(wAllFiles[i], pdfFiles[i],))
pools.close() # 关闭进程池,关闭后pools不再接受新的请求
pools.join() # 等待pool进程池的执行完毕
else:
print("No file need concert format!!!")
# mac系统下对word文件进行转换并保存
def mw2p():
if wAllFiles != []:
for i in range(len(wAllFiles)):
convert(wAllFiles[i], pdfFiles[i])
else:
print("No file need concert format!!!")
# 判断系统类型调用相应转换方法
def w2p():
if plat == 'Darwin': # mac系统下word转换为pdf
mw2p()
elif plat == 'win32': # windows系统下word转换pdf
d2pAsyPool()
else:
pass
if __name__ == '__main__':
plat = platform.system()
prePath = os.path.split(os.path.realpath(__file__))[0] # 脚本所在目录
pdfPath = "C:\\Users\\Administrator\\Desktop\\pdf" # 所要保存pdf文件的位置
prefix = "(2022)" # 修改后的pdf文件名前缀,例如原文件名为1,添加前缀?后为?1
suffix = "-" # 修改后的pdf文件名后缀,例如原文件名为1,添加后缀-后为1-
wAllFiles, pdfFiles = resolvePath(getPFiles())
w2p()
注:该代码未对Mac系统下的其它word应用以及其它系统下转换进行测试(理论上如果该word应用本身支持转换为pdf,则可以通过示例代码进行批量转换的操作)
仅以此作为学习笔记以及分享,如有需改进或者不妥之处,请多多指教。
1+0.01=1.01
1-0.01=0.99