How to Export File as PDF in Python

In this Python article we want to learn How to Export File as PDF in Python, for this purpose we are going to use PySide6 GUI Framework, so PySide6 is Python binding for Qt framework, which is popular C++ framework for building desktop applications. with PySide6 you can create beautiful and functional graphical user interfaces (GUIs) for your applications. in this article we want to learn how to export a file as PDF in PySide6.

 

How to Export File as PDF in Python

First of all we need to install this library, and for that we can use pip 

 

 

After installation we need to create our simple GUI application with Python PySide6.

 

 

If you run the code you will see simple GUI Window in Python.

How to Export File as PDF in Python
How to Export File as PDF in Python

 

 

 

Now that we have basic GUI let’s add menu item that allows the user to save their file as PDF. we do this by creating new menu item in the File menu:

This code creates new menu item called Save as PDF and connects it to new method called save_as_pdf(). this method is called whenever the user clicks on the Save as PDF menu item.

 

 

Run the code and you will see a menu item

How to Export File as PDF in Python
How to Export File as PDF in Python

 

 

Now that we have a menu item that allows the user to save their file as a PDF, let’s implement save_as_pdf() method. we do this using the QPrinter class which is part of the Qt framework:

In the above code we first get the file path using QFileDialog. if the user selects a file path, we creates new QPrinter object and set its output format to PDF using setOutputFormat(QPrinter.PdfFormat). after that we set the output file name using setOutputFileName(file_path).

next we creates new QPdfWriter object with the same file path, which we will use to create the PDF file. and at the end we print the contents of the text editor widget to the PDF file using self.text_edit.document().print_(printer).

 

 

So now this is the complete code for this article 

 

Run the complete code write something in QTextEdit and you can export that as PDF in Python.

 

 

Learn More on Python GUI

Leave a Comment