批量转换word文档到pdf文件

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

思路如下:

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

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

 

步骤(1)的代码如下:

 1 import os
 2 #import comtypes.client
 3 import win32com.client
 4 import time
 5 
 6 
 7 wdFormatPDF = 17
 8 
 9 # absolute path is needed
10 # be careful about the slash '\', use '\\' or '/' or raw string r"..."
11 in_dir=u'input directory'
12 out_dir=u'output directory'
13 
14 word = win32com.client.Dispatch('Word.Application')
15 word.Visible = True
16 time.sleep(3)
17 first_flag=True
18 
19 try:
20     for root, dirs, files in os.walk(in_dir):
21         for file in files:
22             if (file.endswith(".docx") or file.endswith(".doc")) and (not file.startswith('~')):
23                 in_file=os.path.join(root, file)
24                 out_file_temp=os.path.join(out_dir,file)
25                 out_file=out_file_temp.rsplit('.',1)[0]+u'.pdf'
26     #            print(in_file)
27     #            print(out_file)
28                 # skip existed files 
29                 if os.path.isfile(out_file):
30                     continue
31                 print "================================================"
32                 print "convert\n'"+in_file+"' into\n"+ out_file +"'\n" 
33                 doc=word.Documents.Open(in_file)
34                 doc.SaveAs(out_file, FileFormat=wdFormatPDF)
35                 doc.Close()
36                 if first_flag:
37                     word.Visible = False
38                     first_flag = False
39 except Exception as inst:
40     print(type(inst))    # the exception instance
41     print(inst.args)     # arguments stored in .args
42     print(inst)          # __str__ allows args to be printed directly,
43               
44 word.Quit()        
45 print "Coversion Done."

 

步骤(2):

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

 

参考:

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

 

posted @ 2016-12-14 04:53  ijustwanttorun  阅读(767)  评论(0编辑  收藏  举报