如何使用Python在Mac OS上将docx转换为pdf?

问题描述 投票:0回答:3

我查了几个SO和其他网页,但没有找到任何有用的东西。

我编写的脚本,打开一个docx,更改一些单词,然后将其作为docx保存在某个文件夹中。但是,我希望将其另存为 pdf,但我不知道如何保存。

这是我正在使用的代码示例:

# Opening the original document
doc = Document('./myDocument.docx')

# Some code which changes the doc

# Saving the changed doc as a docx
doc.save('/my/folder/myChangedDocument.docx')

我尝试将其另存为 pdf 时所做的事情:

from docx2pdf import convert

# This after it was saved as a docx
    convert('/my/folder/myChangedDocument.docx', '/my/folder/myChangedDocument.pdf')

但是它说Word需要权限才能打开保存的文件,我必须选择该文件才能授予它权限。之后,它只是说:

0%|          | 0/1 [00:03<?, ?it/s]
{'input': '/my/folder/contractsomeVariable.docx', 'output': '/my/folder/contractsomeVariable.pdf', 'result': 'error', 'error': 'Error: An error has occurred.'}

当我保存文档时,我尝试简单地将 .pdf 而不是 .docx 放在文档名称后面,但这也不起作用,因为模块 docx 无法做到这一点。

有人知道如何使用 Python 将 docx 保存为 pdf 吗?

python python-3.x pdf docx converters
3个回答
8
投票

您可以通过先进行更改然后转换来使用docx2pdf。

在 mac 上使用 pip 安装(我猜你已经有了它,但包含它仍然很好)。

pip install docx2pdf

安装 docx2pdf 后,您可以将 docx 文件放入输入文件中,并在输出文件中放入一个空的 .pdf 文件。

from docx2pdf import convert
inputFile = "document.docx"
outputFile = "document2.pdf"
file = open(outputFile, "w")
file.close()

convert(inputFile, outputFile)

0
投票

一个简单的方法,你可以使用

libreoffice

参考:https://www.libreoffice.org/get-help/install-howto/macos/

和脚本示例:

def convert_word_to_pdf_local(folder, source, timeout=None):
    args = [
        LIBREOFFICE_BINARY_PATH,
        '--headless',
        '--convert-to',
        'pdf',
        '--outdir',
        folder,
        source,
    ]
    if check_libreoffice_exists() is False:
        raise Exception('Libreoffice not found')

    process = subprocess.run(
        args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout
    )
    filename = re.search('-> (.*?) using filter', process.stdout.decode())

    if filename is None:
        raise Exception('Libreoffice is not working')
    else:
        filename = filename.group(1)
        pdf_file = open(filename, 'rb')
        return pdf_file


def check_libreoffice_exists():
    s = os.system(f'{LIBREOFFICE_BINARY_PATH} --version')
    if s != 0:
        return False
    return True

0
投票

相信我,在尝试了所有选项之后,切换到 libreoffice 改变了游戏规则。无权限弹出窗口,可靠且快速。 👍

import subprocess

LIBREOFFICE_BINARY = '/Applications/LibreOffice.app/Contents/MacOS/soffice'

def word_to_pdf(input_file):
    subprocess.run([LIBREOFFICE_BINARY, '--convert-to', 'pdf', input_file])


word_to_pdf("example.docx")
© www.soinside.com 2019 - 2024. All rights reserved.