python实现word转pdf


环境:python3、工具pycharm、依赖包pywin32

例子:work转pdf(单个和批量转换当前目录的word文件)

from win32com.client import constants,gencache
import os #目录的操作
def createpdf(wordPath,pdfPath):
    word=gencache.EnsureDispatch('Word.Application')
    doc=word.Documents.Open(wordPath,ReadOnly=1)
    #转换方法
    doc.ExportAsFixedFormat(pdfPath,constants.wdExportFormatPDF)
    word.Quit()

#单个文件转换
#createpdf('C:/Users/Administrator/PycharmProjects/Project3/info.docx','C:/Users/Administrator/PycharmProjects/Project3/info.pdf')

#多个文件的转换
print(os.listdir('.')) #当前文件夹下的所有文件
wordfiles=[]
for file in os.listdir('.'):
    if file.endswith(('.doc','.docx')): #通过后缀找出所有的workd文件
        wordfiles.append(file)
print(wordfiles)

for file in wordfiles:
    #获取文件路径
    filepath=os.path.abspath(file)
    index=filepath.rindex('.')
    #通过截取获取pdfpath
    pdfpath=filepath[:index]+'.pdf'
    print(pdfpath)
    createpdf(filepath,pdfpath)

结果显示:

 

 

 

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM