Convert PDF to .docx with Python

Also picture Also · Apr 22, 2018 · Viewed 15.4k times · Source

I'm trying very hard to find the way to convert a PDF file to a .docx file with Python.

I have seen other posts related with this, but none of them seem to work correctly in my case.

I'm using specifically

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)

This gives me Output[1], but then, I can't find any .docx document in my folder.

I have LibreOffice 5.3 installed.

Any clues about it?

Thank you in advance!

Answer

Rolf of Saxony picture Rolf of Saxony · May 7, 2018

I am not aware of a way to convert a pdf file into a Word file using libreoffice.
However, you can convert from a pdf to a html and then convert the html to a docx.
Firstly, get the commands running on the command line. (The following is on Linux. So you may have to fill in path names to the soffice binary and use a full path for the input file on your OS)

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

then

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

You should end up with:

my_pdf_file.pdf
my_pdf_file.html
my_pdf_file.docx

Now wrap the commands in your subprocess code