使用Python将PDF转换为.docx

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

我正在努力寻找使用Python将PDF文件转换为.docx文件的方法。

我看过其他与此相关的帖子,但在我的案例中似乎没有一个正常工作。

我是专门用的

import os
import subprocess

for top, dirs, files in os.walk('/my/pdf/folder'):
    for filename in files:
        if filename.endswith('.pdf'):
            abspath = os.path.join(top, filename)
            subprocess.call('lowriter --invisible --convert-to doc "{}"'
                            .format(abspath), shell=True)

这给了我输出[1],但是,我在我的文件夹中找不到任何.docx文件。

我安装了LibreOffice 5.3。

关于它的任何线索?

先感谢您!

python pdf docx libreoffice doc
2个回答
1
投票

我不知道使用libreoffice将pdf文件转换为Word文件的方法。 但是,你可以从pdf转换为html,然后将html转换为docx。 首先,在命令行上运行命令。 (以下是在Linux上。所以您可能必须填写soffice二进制文件的路径名并在操作系统上使用输入文件的完整路径)

soffice --convert-to html ./my_pdf_file.pdf

然后

soffice --convert-to docx:'MS Word 2007 XML' ./my_pdf_file.html

你最终应该:

my_pdf_file.pdf my_pdf_file.html my_pdf_file.docx

现在将命令包装在subprocess代码中


0
投票

这应该可以解决您的问题。

import os
import subprocess
path = '/my/pdf/folder'
for files in os.listdir(path):
    for filename in files:
        flipfilename = filename[::-1]
        ext,trash = flipfilename.split('.',1)
        if ext = 'pdf':
           abspath = os.path.join(path, filename)
           subprocess.call('lowriter --invisible --convert-to doc "{}"'
                            .format(abspath), shell=True)

也许试试subprocess.Popen?

© www.soinside.com 2019 - 2024. All rights reserved.