This short tutorial guides on how to convert Excel to PDF using Python by providing the steps to configure the environment and introduction to the necessary libraries. For converting Excel to PDF Python sample code is also provided where a workbook is created and sample data is filled into it however you can also load an existing Excel file say an XLSX. You will also have control over the output PDF by settings its properties and displaying the style of the source Excel file contents before generating the PDF file.
Steps to Export Excel to PDF in Python
- Install Python and Aspose.Cells for Python via Java
- Create and fill a workbook for testing this conversion
- Instantiate PdfSaveOptions class object to configure the output PDF created by Python
- Configure the output PDF to display the gridlines
- Auto-fit the worksheet columns to display entire contents properly in the output PDF file
- Save the workbook as a PDF using the above configurations
You should install Java and Python first on your system and then install Aspose-Cells and JPype1 using the PIP command to convert Excel to PDF in Python. A new workbook can be created or an existing Excel file can be loaded for the conversion to PDF. You can set display options and other properties of the output PDF file using the PdfSaveOptions class instance that can be passed as an argument in the Workbook save function.
Code to Convert Excel To PDF Using Python
When you convert Excel to PDF Python requires some libraries and environment that is why in this code we import the necessary classes and call jpype.startJVM() in the start and jpype.shutdownJVM() in the end for enabling the environment required to run the code. An empty workbook is created and filled with data however you may load any existing Excel file like XLSX, XLS, ODS, etc containing the desired data. Worksheet.PageSetup is used to set the flag to print gridlines in the source file and PdfSaveOptions is used to display grid lines in the output PDF file by setting the grid line type to HAIR.
In this quick tutorial, we have learned how to convert Excel to PDF using Python. If you want to learn how to save Excel file as HTML in Python, refer to the article on how to convert Excel to HTML using Python.