天天看点

word excel ppt转pdf(把指定目录及其子目录中的文件转为pdf)

简介

本程序由python实现,在office中测试通过,没试过WPS。

使用教程

1.安装python(32位或64位)

2.打开cmd.exe输入pip install pywin32回车安装库

word excel ppt转pdf(把指定目录及其子目录中的文件转为pdf)

3.然后输入python FILEtoPDF.py 目录,并回车

word excel ppt转pdf(把指定目录及其子目录中的文件转为pdf)

运行效果

word excel ppt转pdf(把指定目录及其子目录中的文件转为pdf)
word excel ppt转pdf(把指定目录及其子目录中的文件转为pdf)

源码

import os
import sys
import time
from win32com import client

def wordToPdf(docname,pdfname):
    w = client.Dispatch("Word.Application")
    doc = w.Documents.Open(docname, False,Visible = False)
    doc.ExportAsFixedFormat(pdfname, client.constants.wdExportFormatPDF)
    w.Quit()
	
def excelToPdf(xlsname,pdfname):
    x = client.Dispatch("Excel.Application")
    books = x.Workbooks.Open(xlsname, ReadOnly = 1)
    books.ExportAsFixedFormat(0, pdfname)
    x.Quit()
 
def pptToPdf(pptname,pdfname):
    p = client.Dispatch("PowerPoint.Application")
    ppt = p.Presentations.Open(pptname,True, False, False)# Open (FileName, ReadOnly, Untitled, WithWindow)
    ppt.ExportAsFixedFormat(pdfname, 2, PrintRange=None)
    p.Quit()
	
file_list= []

def filesnum(directory):#计算directory目录及其子目录中办公文档的总数
    total= 0     
    for maindir, subdir, file_name_list in os.walk(directory):
        #print(maindir,'\n',subdir,'\n',file_name_list,'\n')
		#"当前主目录:",maindir "当前主目录下的所有子目录:",subdir "当前主目录下的所有文件:",file_name_list
        for filename in file_name_list:
            fullname = os.path.join(maindir, filename)
            if "~$" in fullname:continue
            ext = os.path.splitext(fullname)[1].lower()       
            if ".doc" in ext or ".xls" in ext or ".ppt" in ext:
                file_list.insert(total,fullname)
                total+=1
			
    return total
	
def fileToPdf(directory):

    for fullpath in file_list:
        if not os.path.isfile(fullpath):continue
        ext = os.path.splitext(fullpath)[1].lower()       #获取后缀

        if ".doc" in ext:
            pdfpath = os.path.splitext(fullpath)[0] + '.pdf'
            wordToPdf(fullpath,pdfpath)
        elif ".xls" in ext:
            pdfpath = os.path.splitext(fullpath)[0] + '.pdf'
            excelToPdf(fullpath,pdfpath)
        elif ".ppt" in ext:
            pdfpath = os.path.splitext(fullpath)[0] + '.pdf'
            pptToPdf(fullpath,pdfpath)
        
        time.sleep(3)
		
    print("转换完成!",'\n')

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print("请输入目录!",'\n')
    else:
        print("正在转换,预计需要",filesnum(sys.argv[1])/20,'分钟...\n')
        try:
            fileToPdf(sys.argv[1])
        except Exception as e:
            print("发生异常:",e)