Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PDF to .docx with Python

I'm trying to find a 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!

like image 483
Also Avatar asked Jul 16 '26 05:07

Also


2 Answers

I use this for multiple files

####
from pdf2docx import Converter
import os

# # # dir_path for input reading and output files & a for loop # # #

path_input = '/pdftodocx/input/'
path_output = '/pdftodocx/output/'

for file in os.listdir(path_input):
    cv = Converter(path_input+file)
    cv.convert(path_output+file+'.docx', start=0, end=None)
    cv.close()
    print(file)

like image 114
simon Avatar answered Jul 17 '26 19:07

simon


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

like image 37
Rolf of Saxony Avatar answered Jul 17 '26 17:07

Rolf of Saxony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!