无法使用Python和LibreOffice将pdf转换为docx和doc转换为docx

时间:2018-04-09 18:18:43

标签: python docx libreoffice doc file-conversion

我花了很多时间尝试使用LibreOffice将我们用于将pdf转换为docx(以及doc转换为docx)的代码来确定出现了什么问题。

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

我在Windows上安装了LibreOffice v6.0.2。 我一直在使用此代码的变体来尝试将一些pdf转换为docx,其中特定的pdf文件并不真正相关:

    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 to docx转换方面遇到了类似的问题。

2 个答案:

答案 0 :(得分:2)

这里有很多问题。您应首先从@CristiFati注释的命令行中调用//,然后在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)

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

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

修改

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

"shaw"

filepath.odg

答案 1 :(得分:0)

在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()