python - 使用 Python 和 LibreOffice 将 pdf 转换为 docx 以及将 doc 转换为 docx 时遇到问题

标签 python docx libreoffice doc file-conversion

我花了很多时间试图确定究竟出了什么问题,我使用的代码是使用 LibreOffice 将 pdf 转换为 docx(以及将 doc 转换为 docx)。

我已经使用了 windows 运行界面来测试运行一些我发现相关的代码,并且也在 python 上进行了尝试,但都不起作用。

我在 Windows 上安装了 LibreOffice v6.0.2。

我一直在使用此代码的变体来尝试将一些 pdf 文件转换为与特定 pdf 文件无关的 docx:

    import subprocess
    lowriter='C://Program Files/LibreOffice/program/swriter.exe'
    subprocess.run('{} --invisible --convert-to docx --outdir "{}" "{}"'
                   .format(lowriter,'dir',
                                
    'filepath.pdf',),shell=True)

我再次在 Windows 操作系统的运行界面中尝试过代码,并使用上述代码通过 python 尝试过代码,但没有成功。我也尝试过不使用 outdir,以防万一我写错了,但总是得到 1 的返回码:

    CompletedProcess(args='C://Program Files/LibreOffice/program/swriter.exe 
    --invisible --convert-to docx --outdir "{dir}" 
    {filepath.pdf}"', returncode=1)

dir 和 filepath.pdf 是我放置的占位符。

我对 doc 到 docx 的转换有类似的问题。

最佳答案

这里有很多问题。您应该首先像@CristiFati 评论的那样从命令行获取 --convert-to 调用,然后在 python 中实现。

这是在我的系统上运行的代码。路径中没有 //,需要引号。此外,该文件夹在我的系统上是 LibreOffice 5

import subprocess
lowriter = 'C:/Program Files (x86)/LibreOffice 5/program/swriter.exe'
subprocess.run(
    '"{}" --convert-to docx --outdir "{}" "{}"'
    .format(lowriter,'dir', 'filepath.doc',), shell=True)

最后,似乎不支持从 PDF 转换为 DOCX。 LibreOffice Draw 可以打开 PDF 文件并保存为 ODG 格式。

编辑:

这是从 PDF 转换的工作代码。我升级到 LO 6,因此路径中不再需要版本号(“LibreOffice 5”)。

import subprocess
loffice = 'C:/Program Files/LibreOffice/program/soffice.exe'
subprocess.run(
    '"{}" --convert-to odg --outdir "{}" "{}"'
    .format(loffice,'dir', 'filepath.pdf',), shell=True)

filepath.odg

关于python - 使用 Python 和 LibreOffice 将 pdf 转换为 docx 以及将 doc 转换为 docx 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49739245/

相关文章:

python - 高效地将列中的函数应用到其他列

c# - Mono-LibreOffice System.TypeLoadException

regex - 左边最小的匹配表达式?

ruby - 您将如何解析/存储/修改/保存 docx 文件

linux - 将一个多页 docx 文件拆分为多个单页 docx 文件

python - 如何在python docx中更改句子的字体样式

utf-8 - 将 HTML 表作为 UTF8 导入 OO Calc 而不转换为实体

python - 使用 Python 3.x 从网站中提取 JSON 数据

python - 在 Django View 中显示一对多关系

javascript - 通过 Django 模板将对象传递给 javascript