Monday, November 23, 2015

Convert XLSX to PDF with Python and xtopdf

By Vasudev Ram


This is a simple application of my xtopdf toolkit, showing how to use it to convert XLSX data, i.e. Microsoft Excel data, to PDF (Portable Document Format). It only converts text data, not the formatting, colors, fonts, etc., that may be present in the Excel file.

For the input, I will use this small Excel file, fruits2.xlsx, which I created. A screenshot of it is below (click to enlarge):

Here is the code for

# Program to convert the data from an XLSX file to PDF.
# Uses the openpyxl library and xtopdf.

# Author: Vasudev Ram -
# Copyright 2015 Vasudev Ram.

from openpyxl import load_workbook
from PDFWriter import PDFWriter

workbook = load_workbook('fruits2.xlsx', guess_types=True, data_only=True)
worksheet =

pw = PDFWriter('fruits2.pdf')
pw.setFont('Courier', 12)
pw.setHeader(' - convert XLSX data to PDF')
pw.setFooter('Generated using openpyxl and xtopdf')

ws_range = worksheet.iter_rows('A1:H13')
for row in ws_range:
    s = ''
    for cell in row:
        if cell.value is None:
            s += ' ' * 11
            s += str(cell.value).rjust(10) + ' '
And here is a screenshot of the PDF output in fruits2.pdf:

There are some points worth mentioning in connection with conversion of data to and from PDF. I will discuss them in a follow-up post.

- Vasudev Ram - Online Python training and programming

Signup to hear about new products and services I create.

Posts about Python  Posts about xtopdf

My ActiveState recipes


Vasudev Ram said...

Just realized the title of the post should really be:

Convert XLSX to PDF with Python, openpyxl and Xtopdf.

(though I do mention openpyxl in the comments in the code, and in the body of the post).

Joel Varma said...

import error PDFWriter
how to solve this

Vasudev Ram said...

You need to be a programmer or at least to know how to install needed libraries used by the program. In this case the one giving the error is PDFWriter. That file ( is part of xtopdf. You have to install the xtopdf package before you can run the program (and also other libraries it uses, such as openpyxl). Search for this in Google:

jugad2 guide to installing and using xtopdf

and the first result or so should be the link you want - instructions on how to install xtopdf (on Windows).

The place to get xtopdf is here: