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

Having trouble using Python and LibreOffice to convert pdf to docx and doc to docx

我花了很多时间试图确定究竟出了什么问题,我使用的代码是使用 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 os 的 运行 界面和通过 python 使用上面的代码,但没有成功。我也尝试过不使用 outdir,以防万一我写错了,但总是得到 return 代码 1:

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

目录和 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)

在 python

中安装 pdf2docx 软件包
source      = r'C:\Users\sdDesktop\New Project/Document2.pdf'
destination = r'C:\Users\sd\Desktop\New Project/sample_6.docx'

def Converter_pdf2docx(source,destination):
    pdf_file  = source
    docx_file = destination
    cv = Converter(pdf_file)
    cv.convert(docx_file, start=0, end=None)
    cv.close()