DEV Community

Jeremy K.
Jeremy K.

Posted on

Convert Excel to PDF with Python

Converting Excel files to PDF makes it easier to store tabular data. In addition, it ensures that the layout of an Excel document remains consistent across devices and operating systems when printing or sharing documents. It’s easy to save Excel documents directly to PDF format, but how to achieve this feature in Python? This article will share a simple way to convert Excel to PDF in Python using a third-party library - Spire.XLS for Python.

Steps to Convert Excel to PDF in Python

① First, install the Python libraries via the following pip command.

pip install Spire.XLS
Enter fullscreen mode Exit fullscreen mode

② After installation, import the required libraries

from spire.xls import *
from spire.common import *
Enter fullscreen mode Exit fullscreen mode

③ Load an Excel (.xls/ .xlsx) document, and then use the Workbook.SaveToFile() or Worksheet.SaveToPdf() to convert an Excel workbook or a specified worksheet to PDF format.

④ The PageSetup class can also be used to set the page (size, margins, etc.) during the conversion process.

----Sample Code-----

✍ Convert Excel files to PDF format in Python (each worksheet is displayed as a single PDF page).

from spire.xls import *
from spire.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("Sample.xlsx")

# Set the worksheet fit to page when converting
workbook.ConverterSetting.SheetFitToPage = True

# Convert Excel to PDF file
workbook.SaveToFile("ToPDF.pdf", FileFormat.PDF)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Excel2PDF

✍ Convert each worksheet in Excel to a separate PDF file with Python.

from spire.xls import *
from spire.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("Sample.xlsx")

# Loop through all worksheets in the Excel workbook
for sheet in workbook.Worksheets:

# Save each worksheet as a separate PDF file
    FileName =  sheet.Name + ".pdf"
    sheet.SaveToPdf(FileName)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

ConvertExceltoPDF

✍ Convert a specified Excel worksheet to PDF format with Python.

from spire.xls import *
from spire.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("Sample.xlsx")

# Get the second worksheet
sheet = workbook.Worksheets[1]

# Get the PageSetup object
pageSetup = sheet.PageSetup

# Set page margins
pageSetup.TopMargin = 0.3
pageSetup.BottomMargin = 0.3
pageSetup.LeftMargin = 0.3
pageSetup.RightMargin = 0.3

# Set the page size
pageSetup.PaperSize = PaperSizeType.PaperA3

# Set the worksheet fit to page when converting
workbook.ConverterSetting.SheetFitToPage = True

# Convert the worksheet to a PDF file
sheet.SaveToPdf("WorksheetToPDF.pdf")
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)