You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用docx2pdf转换时,如何避免强制关闭其他已打开Word文档?

解决docx2pdf转换时关闭所有打开Word文档的问题

问题描述

使用Python的docx2pdf库实现Word转PDF功能时,执行转换操作会强制关闭所有处于打开编辑状态的Word文档,希望找到阻止该行为的方法,或替代库完成转换任务。

原代码示例

from docx2pdf import convert
import os

# 指定输入输出文件路径
input_file = self.nameProject + '.docx'
current_directory = os.getcwd()
output_file = os.path.join(current_directory, self.nameProject + '.pdf')

# 执行转换并保存到指定路径
convert(input_file, output_file)

解决方案

一、修改转换逻辑(避免关闭现有Word)

docx2pdf底层依赖Windows COM接口调用Microsoft Word,默认逻辑会强制终止所有Word进程。可以跳过库的封装,直接用pywin32手动控制Word实例,避免影响现有打开的文档:

import os
import win32com.client
from win32com.client import constants

def docx_to_pdf(docx_path, pdf_path):
    # 优先获取已运行的Word实例,不存在则新建
    try:
        word = win32com.client.GetActiveObject("Word.Application")
    except:
        word = win32com.client.Dispatch("Word.Application")
    word.Visible = False  # 后台运行,不显示Word界面
    
    try:
        # 打开目标文档
        doc = word.Documents.Open(os.path.abspath(docx_path))
        # 另存为PDF格式
        doc.SaveAs(os.path.abspath(pdf_path), FileFormat=constants.wdFormatPDF)
        doc.Close()
        # 不调用word.Quit(),避免关闭现有打开的Word文档
    except Exception as e:
        print(f"转换失败: {str(e)}")
        # 若为新建的Word实例,异常时退出避免残留进程
        try:
            win32com.client.GetActiveObject("Word.Application")
        except:
            word.Quit()

# 使用示例
input_file = self.nameProject + '.docx'
current_directory = os.getcwd()
output_file = os.path.join(current_directory, self.nameProject + '.pdf')
docx_to_pdf(input_file, output_file)

二、替代库推荐

1. pywin32(Windows专属,可控性强)

上述代码已使用该库,直接调用Microsoft Word的COM接口,完全自定义转换逻辑,不会强制关闭现有Word进程。安装命令:

pip install pywin32

2. libreoffice-convert(跨平台,无需Microsoft Office)

依赖LibreOffice/OpenOffice,支持Windows、Linux、Mac,适合无Office环境。需先安装LibreOffice,再安装库:

pip install libreoffice-convert

代码示例:

import os
import libreoffice_convert

def docx_to_pdf_libre(docx_path, pdf_path):
    with open(docx_path, 'rb') as docx_file:
        docx_content = docx_file.read()
    # 转换为PDF,需确保LibreOffice在系统PATH中,或指定libreoffice_path参数
    pdf_content = libreoffice_convert.convert(
        docx_content, 
        'pdf', 
        'docx',
        libreoffice_path=r"C:\Program Files\LibreOffice\program\soffice.exe"  # Windows示例路径
    )
    with open(pdf_path, 'wb') as pdf_file:
        pdf_file.write(pdf_content)

# 使用示例
docx_to_pdf_libre(input_file, output_file)

3. unoconv(跨平台,基于LibreOffice命令行)

通过调用LibreOffice的命令行工具实现转换,适合自动化脚本场景。需先安装unoconv和LibreOffice,再通过subprocess调用:

import subprocess

def docx_to_pdf_unoconv(docx_path, pdf_path):
    # 执行unoconv命令转换
    subprocess.run(
        ['unoconv', '-f', 'pdf', '-o', pdf_path, docx_path],
        check=True,
        capture_output=True
    )

总结

  • 若使用Windows且有Microsoft Word,优先用pywin32手动实现,完全避免关闭现有文档;
  • 跨平台或无Office环境,选择libreoffice-convert或unoconv,依赖LibreOffice完成转换。

内容的提问来源于stack exchange,提问作者TariqShah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:43:13