代碼99%來源於http://blog.csdn.net/san1156/article/details/77885995python
import glob as gb
import sys
import imp
imp.reload(sys)
import sys, os
from win32com.client import Dispatch, constants, gencache
import tkinter as tk
from tkinter.filedialog import askdirectory
#REPORT_DOC_PATH = 'C:/Users/wululu/Desktop/report'
#REPORT_PDF_PATH = 'C:/Users/wululu/Desktop/report'
root = tk.Tk()
root.withdraw()
REPORT_DOC_PATH = askdirectory()
REPORT_PDF_PATH = REPORT_DOC_PATH
def word2pdf(filename, doc):
if doc == "Y":
input = filename + '.doc'
elif doc == "N":
input = filename + '.docx'
output = filename + '.pdf'
pdf_name = output
os.chdir(REPORT_DOC_PATH)
if not os.path.isfile(input):
print (u'%s not exist' % input)
return False
if (not os.path.isabs(input)):
input = os.path.abspath(input)
else:
print (u'%s not absolute path' % input)
return False
if (not os.path.isabs(output)):
os.chdir(REPORT_PDF_PATH)
output = os.path.abspath(output)
else:
print (u'%s not absolute path' % output)
return False
try:
print (input, output)
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
w = Dispatch("Word.Application")
try:
doc = w.Documents.Open(input, ReadOnly=1)
doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
except:
print (' exception')
finally:
w.Quit(constants.wdDoNotSaveChanges)
if os.path.isfile(pdf_name):
print ('translate success')
return True
else:
print ('translate fail')
return False
except:
print (' exception')
return -1
if __name__ == '__main__':
import os
for dirpath, dirnames, filenames in os.walk(REPORT_DOC_PATH):
for file in filenames:
fullpath = os.path.join(dirpath, file)
print (fullpath, file)
if 'docx' in file:
rc = word2pdf(filename = file.rstrip('.docx'), doc = "N")
else:
rc = word2pdf(filename = file.rstrip('.doc'), doc = "Y")
Reference
[1] http://blog.csdn.net/san1156/article/details/77885995
[2] http://blog.csdn.net/rumswell/article/details/7434302
[3] https://www.daniweb.com/programming/software-development/threads/206548/importerror-no-module-named-tkfiledialogweb