使用Python将word转换为PDF

 运行cmd, 在cmd中切换到word_to_pdf.py所在的目录,运行如下命令:

 选择word文档所在的目录,如下图所示:

 

 转换后的文档如下图所示:

 

 word_to_pdf.py 的源码如下:

from win32com.client import constants,gencache
import os
import fitz
import tkinter as tk
from tkinter import filedialog
import msvcrt

pdf_dir = []
Word_files = []

def get_file():
    root = tk.Tk()
    root.withdraw()
    # 想要选中文件的,可以使用这个方法直接获取文件路径
    dir_path = filedialog.askdirectory(initialdir='./')
    #print("dir_path:"+dir_path)
    docunames = os.listdir(dir_path)
    
    for file in docunames:
        print("file:"+file)
    # 找出所有后缀为doc或者docx的文件
        if file.endswith(('.doc','.docx')):
            Word_files.append(file)
    
    print(Word_files)
    
    for file in Word_files:
        file_path = os.path.abspath(dir_path+"/"+file)
        index = file_path.rindex('.')
        pdf_path = file_path[:index] + '.pdf'
        Word_to_Pdf(file_path,pdf_path)

# Word转pdf方法,第一个参数代表word文档路径,第二个参数代表pdf文档路径
def Word_to_Pdf(Word_path,Pdf_path):
    print("Word_path:"+Word_path)
    print("Pdf_path:"+Pdf_path)
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(Word_path)
    # 转换方法
    doc.ExportAsFixedFormat(Pdf_path,constants.wdExportFormatPDF)
    #word.Quit()

if __name__ == '__main__':
    get_file()

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值