python完成文件夹批量word转pdf文件及pdf文件合并+word文件合并

2020-11-10 10:06发布

前言:有同学问我,如何把文件夹中的文件一次性完成打印,由于文件太多,单个打印着实麻烦。这些文件主要有三种类型,分别为PDF,word(.doc和.docx),我决定把他们全部变为PDF文件,然后再合并所有的pdf文件为一个PDF文件,分两个步骤完成!

1.把所有word转化为PDF

from win32com.client import Dispatchimport os

pdfRoot = "D:\Desktop\wordToPDF\pdf" #保存pdf结果的文件夹wordRoot = "D:\Desktop\wordToPDF\word" #读取word的文件夹def doc2pdf(filePath, file):
    print("正在转换:",file)
    word = Dispatch('Word.Application')
    doc = word.Documents.Open(filePath)
    outFile = pdfRoot +"\\"+ file.split('.')[0] + ".pdf" #生成pdf文件路径名称
    doc.SaveAs(outFile, FileFormat=17)
    doc.Close()
    word.Quit()if __name__ == "__main__":
    filelist = os.listdir(wordRoot)
    for file in filelist:
        if (file.endswith(".doc") or file.endswith(".docx")) and ("~$" not in file):
            filePath = wordRoot+"\\"+file
            doc2pdf(filePath, file)
    print ("所有word文件转PDF文件已完成!!!")12345678910111213141516171819202122


2.合并所有PDF文件

from PyPDF2 import PdfFileMergerimport os

pdfRoot = "D:\Desktop\wordToPDF\pdf" #保存pdf结果的文件夹merger = PdfFileMerger() #调用PDF文件合并模块filelist=os.listdir(pdfRoot) #读取文件夹所有文件for file in filelist:
    if file.endswith(".pdf"):
        merger.append(pdfRoot+"\\"+file)#合并PDF文件merger.write("result.pdf") #写入PDF文件12345678910

在这里插入图片描述


3.多个word文件合并

from os.path import abspathfrom win32com import clientimport os

wordRoot = "D:\Desktop\Ada\word" #读取word的文件夹final_docx = r"D:\Desktop\Ada\result\word文件合并结果2.docx"files = list()filelist = os.listdir(wordRoot)for file in filelist:
    if (file.endswith(".doc") or file.endswith(".docx")) and ("~$" not in file):
        filePath = wordRoot+"\\"+file
        files.append(filePath)# 启动word应用程序word = client.gencache.EnsureDispatch("Word.Application")word.Visible = True# 新建空白文档new_document = word.Documents.Add()for fn in files[::-1]:
    print ("正在合并:", fn)
    fn = abspath(fn)
    new_document.Application.Selection.Range.InsertFile(fn)# 保存最终文件,关闭Word应用程序new_document.SaveAs(final_docx)new_document.Close()word.Quit()1234567891011121314151617181920212223242526

在这里插入图片描述



作者:阿优乐扬

链接:https://blog.csdn.net/ayouleyang/article/details/108283956

来源:CSDN
著作权归作者所有,转载请联系作者获得授权,切勿私自转载。