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

将word转换为pdf格式

安装pywin32

代码(Anaconda终端下)

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

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

上代码

在pycharm中输入代码

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版本的真的看起来好舒服呀

批量实现word转pdf

安装docx2pdf

代码(Anaconda终端下)

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

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

上代码

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")

运行结果

在这里插入图片描述
这就是全部内容啦,希望可以帮到你熬!在这里插入图片描述
这边找了一个exe文件,打开就直接可以word转换pdf文件
https://download.csdn.net/download/hanhanwanghaha/12810795
要是没有积分下载的话可私我,我分享给你嘿嘿嘿

猜你喜欢

转载自blog.csdn.net/hanhanwanghaha/article/details/108253704
今日推荐