python实现word文档转PDF

用Python实现word转PDF操作

import os
import comtypes.client

'''
Word转换成PDF的本质,就是模拟我们在Windows上打开Word文档并另存为.pdf 的操作过程
'''
def get_path():
    path = os.getcwd()         #获取当前运行路径
    filename_list = os.listdir(path)
    wordname_list = [filename for filename in filename_list if filename.endswith((".doc",".docx"))]
    for wordname in wordname_list:
        #分离word文件名称和后缀,转化为PDF名称
        pdfname = os.path.splitext(wordname)[0] + '.pdf'
        #如果当前word文件对应的PDF文件存在则不转化
        if pdfname in filename_list:
            continue
        wordpath = os.path.join(path,wordname)      #word所在目录
        pdfpath = os.path.join(path,pdfname)        #存放生成的PDF目录
        #生成器
        yield wordpath,pdfpath
if __name__ == '__main__':
    word = comtypes.client.CreateObject("Word.Application")
    word.Visiable=0    #设置可见性,不可见

    for w,p in get_path():
        newpdf = word.Documents.Open(w)
        newpdf.SaveAs(p,FileFormat=17)     #17表示PDF格式
        newpdf.Close()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Python实现Word无损PDF,可以使用Python-docx库和PyPDF2库。首先,使用Python-docx库将Word文档换为PDF格式,然后使用PyPDF2库将PDF文件合并为一个PDF。以下是实现的步骤: 1. 安装Python-docx库和PyPDF2库。 2. 使用Python-docx库打开Word文档。 3. 创建一个空的PDF文件。 4. 遍历Word文档的每一页,将每一页的内容添加到PDF文件中。 5. 保存并关闭PDF文件。 6. 使用PyPDF2库将所有生成的PDF文件合并为一个PDF文件。 以下是一个示例代码: ```python from docx import Document from PyPDF2 import PdfWriter def word_to_pdf(word_file, pdf_file): # 打开Word文档 doc = Document(word_file) # 创建一个空的PDF文件 pdf_writer = PdfWriter() for page_num, page in enumerate(doc.pages): # 将每一页的内容添加到PDF文件中 pdf_writer.add_page(page) # 保存PDF文件 with open(pdf_file, 'wb') as f: pdf_writer.write(f) # 关闭Word文档 doc.close() # 调用函数进行word_to_pdf('input.docx', 'output.pdf') ``` 请将`input.docx`替换为要换的Word文档的路径,将`output.pdf`替换为保存PDF的路径。 这样,您就可以使用Python实现Word无损PDF了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [太方便了!利用Python对批量PdfWord](https://blog.csdn.net/lyc2016012170/article/details/117719980)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Python实用功能之pdf文件png图片数据](https://blog.csdn.net/Together_CZ/article/details/126335438)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值