python实现批量Word转PDF

使用说明:
《python实现批量Word转PDF》
代码:

from win32com.client import Dispatch
from PyPDF2 import PdfFileMerger

import os
import sys
import getopt


def doc2pdf(filePath, file, output):
    print("正在转换:", file)
    word = Dispatch('Word.Application')
    doc = word.Documents.Open(filePath)
    outFile = os.path.join(output, file.split('.')[0]) + ".pdf"  # 生成pdf文件路径名称
    doc.SaveAs(outFile, FileFormat=17)
    doc.Close()
    word.Quit()


def mergeToOnePdf(output, fileName):
    print("正在合并pdf....")
    merger = PdfFileMerger()  # 调用PDF文件合并模块
    filelist = os.listdir(output)  # 读取文件夹所有文件
    for file in filelist:
        if file.endswith(".pdf"):
            merger.append(os.path.join(output, file))  # 合并PDF文件
    fileName = fileName if fileName.endswith(".pdf") else fileName + ".pdf"
    merger.write(fileName)  # 写入PDF文件
    print("pdf合并完成: ", fileName)


def getCommandLineOptions():
    options = { 
        "input": os.getcwd(),
        "output": os.getcwd(),
        "merge": False,
        "name": "merged.pdf",
    }
    # 获取当前文件名
    options["self_name"] = sys.argv[0]
    # 解析命令行选项
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:o:mn:", [
            "help", "input=", "output=", "merge", "name="])
    except getopt.GetoptError:
        print("输入选项有误")
        printHelpInfo()
        sys.exit(2)

    # print(opts)
    for opt, value in opts:
        opt = opt.replace("-", "")
        if opt in ["h", "help"]:
            printHelpInfo()
            sys.exit(0)
        elif opt in ["i", "input"]:
            options["input"] = value
            pass
        elif opt in ["o", "output"]:
            options["output"] = value
            pass
        elif opt in ["m", "merge"]:
            options["merge"] = True
            pass
        elif opt in ["n", "name"]:
            options["name"] = value
            pass
        else:
            printHelpInfo()
            sys.exit(0)

    return options


def printHelpInfo():
    print("""提示: 目前仅支持 .doc 和 .docx 后缀的Word文件 -h | --help , 显示当前帮助信息 -i | --input <input_path> , 指定Word文件目录,默认为当前目录 -o | --output <output_path>, 指定输出目录,默认为当前路径 -m | --merge , 设置则在转换完成后同时将生成的PDF文件合并到一个文件中 -n | --name <file_name> , 指定合并后文件的名称,默认为merged.pdf(不合并则忽略该参数) """)
    pass


if __name__ == "__main__":
    options = getCommandLineOptions()

    filelist = os.listdir(options["input"])
    for file in filelist:
        if (file.endswith(".doc") or file.endswith(".docx")) and ("~$" not in file):
            filePath = os.path.join(options["input"], file)
            doc2pdf(filePath, file, options["output"])
    print("所有word文件转PDF文件已完成")
    if options["merge"]:
        mergeToOnePdf(options["output"], options["name"])

核心代码来自:https://blog.csdn.net/ayouleyang/article/details/108283956

    原文作者:失去同步
    原文地址: https://blog.csdn.net/lose_synchronization/article/details/120339601
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞