教你用8行代码将word转换为pdf格式 及 6行代码实现批量将word转换为pdf格式--python实用小技能get起来

将word转换为pdf格式

安装pywin32

代码(Anaconda终端下)python

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn pywin32

运行结果
在这里插入图片描述web

上代码

在pycharm中输入代码svg

from win32com.client import Dispatch, constants, gencache

# 放入要转换的word格式路径
docx_path = 'G:\示例.docx'

# 放入要导出的pdf格式的路径,而且命名
pdf_path = 'G:\示例.pdf'

# 转换
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)

wd = Dispatch('Word.Application')

doc = wd.Documents.Open(docx_path, ReadOnly=1)

doc.ExportAsFixedFormat(pdf_path, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup,
                        CreateBookmarks=constants.wdExportCreateHeadingBookmarks)

wd.Quit(constants.wdDoNotSaveChanges)

运行结果

docx文件
在这里插入图片描述
pdf文件
在这里插入图片描述
我的感受pdf版本的真的看起来好舒服呀ui

批量实现word转pdf

安装docx2pdf

代码(Anaconda终端下)spa

pip install --user -i https://pypi.tuna.tsinghua.edu.cn/simple/ docx2pdf

如图所示
在这里插入图片描述code

上代码

from docx2pdf import convert
import os

#''放入你想要转换的文件路径
director = r'G:\eg'
FileList = map(lambda x: director + '\\' + x, os.listdir('G:\eg'))
for file in FileList:
    convert(file, f"{file.split('.')[0]}.pdf")

运行结果

在这里插入图片描述
这就是所有内容啦,但愿能够帮到你熬!在这里插入图片描述orm