批量转换word文档到pdf文件

时间:2024-10-21 09:03:56

最近在整理每周的工作记录。因为每周的工作记录大都是单独的word文件,有时候忘记了也不容易找出来,一个个打开查找太费劲,因此想着把这些文件通过word2016的另存为功能转换为pdf,然后永Acrobat合并起来。

思路如下:

(1)通过Python代码搜索指定输入目录下的所有word文档,调用word COM接口,将文件转存为pdf文件到指定输出目录;

(2)利用Acrobat将输出的目录中所有的pdf合并成单个pdf文件供存档查阅。

步骤(1)的代码如下:

 import os
#import comtypes.client
import win32com.client
import time wdFormatPDF = 17 # absolute path is needed
# be careful about the slash '\', use '\\' or '/' or raw string r"..."
in_dir=u'input directory'
out_dir=u'output directory' word = win32com.client.Dispatch('Word.Application')
word.Visible = True
time.sleep(3)
first_flag=True try:
for root, dirs, files in os.walk(in_dir):
for file in files:
if (file.endswith(".docx") or file.endswith(".doc")) and (not file.startswith('~')):
in_file=os.path.join(root, file)
out_file_temp=os.path.join(out_dir,file)
out_file=out_file_temp.rsplit('.',1)[0]+u'.pdf'
# print(in_file)
# print(out_file)
# skip existed files
if os.path.isfile(out_file):
continue
print "================================================"
print "convert\n'"+in_file+"' into\n"+ out_file +"'\n"
doc=word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
if first_flag:
word.Visible = False
first_flag = False
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly, word.Quit()
print "Coversion Done."

步骤(2):

批量转换word文档到pdf文件

批量转换word文档到pdf文件

可以看到每个文件的名字都变成了书签,方便查阅。

参考:

http://*.com/questions/6011115/doc-to-pdf-using-python