Table of contents
- Let's Build the App -
- Starting the Code -
- Importing the Modules -
- Defining the page window height , width , title and theme -
- Output -
- Defining the function which will fetch and convert the file -
- Passing the on-click function into the FilePicker method of the Flet module -
- Adding a button and TextField in our Window -
- Finally calling the app method and passing the main function as the target -
- Full Code -
We have seen many websites that convert a PDF file into a DOCX (Word Document). Now what if we can build those on our own?
Well, it is now possible to build a small application that converts a PDF into DOCX with very few lines of code. Thanks to Python and one of its newest modules named Flet.
Brief Introduction to Flet: Flet is a Python library that is used to develop Flutter-like Apps in Python by using Python Code. Developers who don't know a single line of Dart can use this library to build Flutter-like apps. Developers don't need to have any front-end experience too. Everything can be done using Python and the functions, and methods provided by the Flet Module. Developers can build Web Applications, Desktop Applications and as well as Mobile Applications using Flet.
Users must be familiar with Python syntax, especially the OOPS concept.
Let's Build the App -
Installing the Flet Module:
To install the Flet Module, the user must have Python installed on their device alongside the pip command.
Installation command for Windows Users -
pip install flet
For Linux users -
To use Flet in Linux systems (Ubuntu/Debian) developers need to have the GStreamer library installed on their device. Mostly that comes pre-installed. But if the developers get any error whilst using Flet then use the following commands to install GStream libraries -
sudo apt-get update
sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libgstreamer-plugins-bad1.0-dev gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav gstreamer1.0-doc gstreamer1.0-tools gstreamer1.0-x gstreamer1.0-alsa gstreamer1.0-gl gstreamer1.0-gtk3 gstreamer1.0-qt5 gstreamer1.0-pulseaudio
Apart from Flet we will need two more Modules -
PDF2DOCX - This will handle the conversion operation. This can be installed using pip.
pip install pdf2docx
OS - Os Module is pre-installed, we will use this module to open the file, save the file, rename the file etc.
Starting the Code -
Importing the Modules -
We will first import all our required modules -
Python3
import flet as ft
from pdf2docx import Converter
import os
Note : If the user is using Python's latest version i.e 3.11 then below the pdf2docx module there could be a warning line saying "module not found" even after installing the module using pip. Don't worry many of the modules in Python are not been made compatible for the 3.11 version but they work as expected. Even the tensorflow shows warning like this in Python 3.11, but works exactly as expected.
Defining the page window height , width , title and theme -
Python
import flet as ft
from pdf2docx import Converter
import os
def main(page: ft.Page):
page.window_height = 500
page.window_width = 500
page.title = "Flet App to Convert PDF file to Docx"
page.theme_mode = "light"
ft.app(target=main)
Output -
Defining the function which will fetch and convert the file -
Now inside the main() function, we will define a function that will fetch the file that we want to convert, rename the file, and then save it in the same directory. Here we will use the try-catch block just to handle any kind of unnecessary exception.
def onclick(ele : ft.FilePickerResultEvent):
path = os.getcwd()
for i in ele.files:
# print("Your Current Path",i.path)
pdf = i.path
docx = path + f"/convertedfile/{rename.value}.docx"
try:
result = Converter(pdf)
result.convert(docx)
result.close()
except:
print("Conversion Failed")
else:
print("Conversion Successful !!!!")
page.snack_bar = ft.SnackBar(
ft.Text("Successfully Converted", size=30),
bgcolor = "blue"
)
page.snack_bar.open = True
page.update()
Explanation -
Firstly, we are using a variable path to store the current working directory using the os module's getcwd() method.
Then we are using a for loop to iterate over the files in that path and storing it in another variable named pdf.
Also creating another variable named docx, which will store the path and the name of the converted file, which the user will provide later.
Then enclosing the section on converting the pdf file into docx into a try-catch block so that if the user provides any kind of file except PDF, then it will show an error message.
Then use the snack_bar method of the Flet module to display a message below our window.
Passing the on-click function into the FilePicker method of the Flet module -
Now we will pass our newly created on-click method into the FilePicker method of the Flet module, which will let the user pick a file of their choice, and the passed function will handle the work of converting and saving it.
file_picker = ft.FilePicker(on_result=onclick)
page.overlay.append(file_picker)
Adding a button and TextField in our Window -
Now we will define a button and a text field in which the user can provide the new name of the converted file and press the button to convert it. We will also define the size of the text as well as its color. Finally, we will use the add() method of Flet to add it to our window.
page.add(
ft.Column([
ft.Text("Convert PDF to Docx ????",size=30,color="red"),
rename,
ft.ElevatedButton('Convert to Docx',
bgcolor='green',color='white',
on_click=lambda _ : file_picker.pick_files())
])
)
Finally calling the app method and passing the main function as the target -
Now, after everything, we will call the app() method of Flet and then pass the main function as the target. We also have to pass the folder name from which we will fetch the file and store the converted one.
Python3
ft.app(target=main,assets_dir='convertedfile')
Here, the directory from which we will fetch the file is named convertedfile, user can use any name of their choice.
Full Code -
Below is the Full Code of the Application -
import flet as ft
from pdf2docx import Converter
import os
def main(page: ft.Page):
rename = ft.TextField(label="Enter the new name of the Converted File")
page.window_height = 500
page.window_width = 500
page.title = "Flet App to Convert PDF file to Docx"
page.theme_mode = "light"
def onclick(ele : ft.FilePickerResultEvent):
path = os.getcwd()
for i in ele.files:
# print("Your Current Path",i.path)
pdf = i.path
docx = path + f"/convertedfile/{rename.value}.docx"
try:
result = Converter(pdf)
result.convert(docx)
result.close()
except:
if not pdf.endswith('.pdf'):
page.snack_bar = ft.SnackBar(
ft.Text("Unsupported File Format",size=30),
bgcolor = "red"
)
page.snack_bar.open = True
print("Conversion Failed")
else:
print("Conversion Successful !!!!")
page.snack_bar = ft.SnackBar(
ft.Text("Successfully Converted", size=30),
bgcolor = "green"
)
page.snack_bar.open = True
page.update()
file_picker = ft.FilePicker(on_result=onclick)
page.overlay.append(file_picker)
page.add(
ft.Column([
ft.Text("Convert PDF to Docx ????",size=30,color="red"),
rename,
ft.ElevatedButton('Convert to Docx',
bgcolor='green',color='white',
on_click=lambda _ : file_picker.pick_files())
])
)
ft.app(target=main,assets_dir='convertedfile')
Final Output window -
Success message after conversion -
Unsuccessful message after conversion -
So that's the end of this blog. Hope you all will find it useful.