Python—docx 批量处理 docx2pdf 文件

 2023-09-05 阅读 103 评论 0

摘要:使用Python3.X 批量将文件夹中的所有docx文档转为PDF 代码示例: 以下处理的.docx文件由这篇文章代码产生:https://blog.csdn.net/wsp_1138886114/article/details/96508728 from win32com import client as wc import osdef get_docx(input_Docxs):DocxPaths &#

使用Python3.X 批量将文件夹中的所有docx文档转为PDF

代码示例:
以下处理的.docx文件由这篇文章代码产生:https://blog.csdn.net/wsp_1138886114/article/details/96508728

from win32com import client as wc
import osdef get_docx(input_Docxs):DocxPaths = []for root,dirs,filenames in os.walk(input_Docxs):for filename in filenames:if filename.endswith(('.docx','.doc')):DocxPaths.append(root+'/'+filename)return DocxPathsdef docx2pdf(input_Docxs,pdf_path):DocxPaths = get_docx(input_Docxs)print('DocxPaths',DocxPaths)word = wc.Dispatch('Word.Application')word.Visible = 0for docx_path in DocxPaths:pdf_name = pdf_path+'/'+docx_path.split('/')[-1][:-5]+'.pdf'try:doc = word.Documents.Open(docx_path)doc.SaveAs(pdf_name, 17)  # 直接保存为PDF文件doc.Close()except:print('%s 转换失败' % docx_path)word.Quit()if __name__ == '__main__':input_Docxs = 'D:\\python_script\\office_docx_pdf'pdf_path = 'D:\\python_script\\office_docx_pdf'docx2pdf(input_Docxs, pdf_path)

使用以下写法,代码报错,暂时未找到原因,望各位看官不吝赐教

from win32com.client import Dispatch, constants, gencache, DispatchEx
import osdef get_docx(input_Docxs):DocxPaths = []for root, dirs, filenames in os.walk(input_Docxs):for filename in filenames:if filename.endswith(('.docx', '.doc')):DocxPaths.append(root + '/' + filename)return DocxPathsdef docx2pdf(input_Docxs, pdf_path):DocxPaths = get_docx(input_Docxs)for docx_path in DocxPaths:gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)word = Dispatch('Word.Application')word.Visible = 0doc = word.Documents.Open(docx_path, ReadOnly=1)pdf_name = pdf_path + '/' + docx_path.split('/')[-1][:-4] + '.pdf'try:doc.ExportAsFixedFormat(pdf_name, constants.wdExportFormatPDF,Item=constants.wdExportDocumentWithMarkup,CreateBookmarks=constants.wdExportCreateHeadingBookmarks)word.Quit(constants.wdDoNotSaveChanges)except:print('%s 转换失败' % docx_path)if __name__ == '__main__':input_Docxs = '../office_docx_pdf'pdf_path = '../office_docx_pdf'docx2pdf(input_Docxs, pdf_path)'''
pywintypes.com_error: (-2147352567, '发生意外。', (0, 'Microsoft Word', '很抱歉,找不到您的文件。
该项目是否已移动、重命名或删除?\r(C:\\Users\\XXX\\...\\demo_张三.docx)', 'wdmain11.chm', 24654, -2146823114), None)
'''

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/211.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息