如何使用 Python 在 Mac 操作系统上将 docx 转换为 pdf?

Jem*_*Jem 8 python pdf docx converters python-3.x

我查过几个 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')
Run Code Online (Sandbox Code Playgroud)

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

from docx2pdf import convert

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

但它说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.'}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 8

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

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

pip install docx2pdf
Run Code Online (Sandbox Code Playgroud)

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

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

convert(inputFile, outputFile)
Run Code Online (Sandbox Code Playgroud)