Python实现ppt与word批量转pdf

环境依赖:
操作系统:win10
Python:3.8.10(注意3.9安装pyinstaller插件插件,不在支持win7环境,必须降级到3.8)
IDE:PyCharm 2021.3

源码如下:

#coding=utf-8
#!/usr/bin/python
import msvcrt
import os
import datetime
import subprocess

import comtypes.client
import traceback
import logging

ppts = set()
docs = set()
flvs = set()
pdf = 'pdf'

logging.basicConfig(filename='log.txt', level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')


def open_app(app_dir):
    os.startfile(app_dir)


def close_app(name):
    # 解决控制台乱码
    os.system('chcp 65001')
    os.system("taskkill /f /im \""+name+"\"")


# 遍历指定文件夹的文件名称
def list(path):
    # print('当前文件路径: %s' % path)
    fileList = os.listdir(path)
    # print(fileList)
    for file in fileList:
        # 先过滤文件夹
        if file.find('.') == -1:
            continue
        # 再过滤文件名第一位是.的特殊文件夹
        if file[0:1] == '.':
            continue
        f = os.path.splitext(file)[-1][1:]
        if f.find('pptx') > -1 or f.find('ppt') > -1:
            # print('ppt类型 -> %s' % file)
            ppts.add(file)
        if f.find('docx') > -1 or f.find('doc') > -1:
            # print('doc类型 -> %s' % file)
            docs.add(file)
        if f.find('flv') > -1:
            # print('flv类型 -> %s' % file)
            flvs.add(file)

def open_ppt_or_word(app_dir):
    list(app_dir)
    # 打开ppt
    for ppt in ppts:
        open_app(app_dir + ppt)

class Office():
    def batch_ppt_to_pdf(app_dir):
        list(app_dir)
        inputFileName = ''
        outputFileName = ''
        for ppt in ppts:
            # print("ppt File => %s" % ppt)
            inputFileName = app_dir + ppt
            outputFileName = Office.office_extension_rename_file(app_dir + ppt, pdf)
            Office.ppt_to_pdf(inputFileName, outputFileName)
            print("已完成 %s 转换pdf任务" % ppt)

    def batch_doc_to_pdf(app_dir):
        list(app_dir)
        inputFileName = ''
        outputFileName = ''
        for doc in docs:
            # print("ppt File => %s" % ppt)
            inputFileName = app_dir + doc
            outputFileName = Office.office_extension_rename_file(app_dir + doc, pdf)
            Office.word_to_pdf(inputFileName, outputFileName)
            print("已完成 %s 转换pdf任务" % doc)

    def ppt_to_pdf(input_file_name, output_file_name, format_type = 32):
        try:
            powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
            powerpoint.Visible = 1

            if output_file_name[-3:] != 'pdf':
                output_file_name = output_file_name + ".pdf"
            deck = powerpoint.Presentations.Open(input_file_name)
            deck.SaveAs(output_file_name, format_type)  # formatType = 32 for ppt toExtMeth.txt pdf
            deck.Close()
            powerpoint.Quit()
        except:
            logging.error(traceback.format_exc())

    def word_to_pdf(input_file_name, output_file_name, format_type = 17):
        try:
            word = comtypes.client.CreateObject("Word.Application")
            word.Visible = 1
            if output_file_name[-3:] != 'pdf':
                output_file_name = output_file_name + ".pdf"
            deck = word.Documents.Open(input_file_name)
            deck.SaveAs(output_file_name, format_type)  # formatType = 17 for doc toExtMeth.txt pdf
            deck.Close()
            word.Quit()
        except:
            logging.error(traceback.format_exc())

    def office_extension_rename_file(old_name, new_extension_name):
        # 先过滤文件夹,默认文件夹不重命名
        if old_name.find('.') == -1:
            return old_name
        # 再过滤文件名第一位是.的特殊文件夹,默认不重命名
        if old_name[0:1] == '.':
            return old_name
        # 取扩展名.右侧的字符
        # os.path.splitext(oldname)[1][1:]
        name = os.path.splitext(old_name)[1][1:]
        if name == 'pptx' or name == 'ppt' \
                or name == 'docx' or name == 'doc':
            return os.path.splitext(old_name)[0] + '.' + new_extension_name
        else:
            return old_name

if __name__ == '__main__':
    startTime = datetime.datetime.now()
    print('开始时间:%s \n' %(startTime))
    # 固定某个目录
    # app_dir = 'c:\demo\\'
    # 自动获取当前目录
    app_dir = os.getcwd() + "\\"
    # open_ppt_or_word(app_dir)
    # 在关闭ppt
    # close_app('POWERPNconvert("input.docx", "output.pdf")T.EXE')
    # ppt 转 pdf
    Office.batch_ppt_to_pdf(app_dir)
    Office.batch_doc_to_pdf(app_dir)
    # Video.batch_video_to_mp4(app_dir)
    endTime = datetime.datetime.now()
    print('\n结束时间:%s' % (endTime))
    print('\n用时:%s 秒' % (endTime - startTime))
    print("\n按任意键退出 :)")
    ord(msvcrt.getch())

最后把代码打包成EXE,方便在win环境运行
1)现在pycharm安装pyinstaller插件
2)在项目根目录,执行:pyinstaller -F main.py

完成

最终功能效果,功能gif演示

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

*

code