To write a small tool used to batch convert word to pdf, use:
The complete code is copied to the document and change the name to words2pdfs.py
the file copied to the need to convert the file directory
input python words2pdfs.py in the terminal
the terminal will be listed in the following documents need to convert, you can enter yes.
Note: After running pdfs will generate a folder in the current directory, which is all converted files
Import OS, the shutil from the win32com Import Client DEF doc2pdf (DOC_NAME, pdf_name): "" " : Word file transfer pdf : param DOC_NAME Word file name : the file name param pdf_name convert pdf " "" the try : Word = client.DispatchEx ( " the Word.Application " ) IF os.path.exists (pdf_name): The os.remove (pdf_name) WordDoc = word.Documents.Open (DOC_NAME, the ReadOnly =. 1 ) worddoc.SaveAs (pdf_name, the FileFormat =. 17 ) return pdf_name the except Exception AS E: Print (E) return . 1 the finally : worddoc.Close () word.Quit () DEF doc2docx (DOC_NAME, docx_name): "" " : doc turn docx " "" the try : # first converted into doc docx = client.Dispatch Word ( " the Word.Application " ) doc = word.Documents.Open (DOC_NAME) # parameters represents 16 to convert doc docx doc.SaveAs (docx_name, 16 ) the except : Pass the finally : doc.Close() word.Quit() def createDirs(basePath=os.getcwd()): # 存放转化后的pdf文件夹 pdfs_dir = basePath + '/pdfs' if not os.path.exists(pdfs_dir): os.mkdir(pdfs_dir) return pdfs_dir def getFileNames(basePath=os.getcwd()): filenames=[] # move all .words files to words_dir for file in os.listdir(basePath): if file.endswith('.docx'): filenames.append(file) elif file.endswith('.doc'): filenames.append(file) else: pass return filenames def convert(basePath=os.getcwd(),filenames=[]): pdfs_dir=createDirs(basePath) for filename in filenames: pdfName='.'.join(filename.split('.')[:-1])+'.pdf' doc2pdf(os.path.join(basePath,filename),os.path.join(pdfs_dir,pdfName)) if __name__ == '__main__': basePath=os.getcwd() lfileNames=getFileNames(basePath) print('are you going to convert these files to pdf?') for filename in lfileNames: print(filename) print("yes/no?") while True: command=input() if command=='yes': convert(basePath,lfileNames) break elif command=='no': break else: print('wrong command,input yes or no please')
---------------------
Disclaimer: This article is CSDN blogger "Fantastic_Liar 'original article, follow the CC 4.0 by-sa copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/Fantastic_Liar/article/details/90452928