There are a lot of options for creating a pdf in python. Some of these options are ReportLab, pydf2, pdfdocument and FPDF.

The FPDF library is fairly stragihtforward to use and is what I've used in this example. FPDF Documentation can be found here.

It's perhaps also good to think about what python modules you might want to use to create graphs and tables. In my example, I use matplotlib (link to docs) and I also use Pandas to create a dataframe using pandas.dataframe().

I've posted a rather lengthy but fully reproducible example below, using pandas, matplotlib and fpdf. The data are a subset of what the OP provided in the question. I loop through the dataframe in my example to create the table, but there are alternative and perhaps more efficient ways to do this.

import pandas as pd
import matplotlib
from pylab import title, figure, xlabel, ylabel, xticks, bar, legend, axis, savefig
from fpdf import FPDF


df = pd.DataFrame()
df['Question'] = ["Q1", "Q2", "Q3", "Q4"]
df['Charles'] = [3, 4, 5, 3]
df['Mike'] = [3, 3, 4, 4]

title("Professor Criss's Ratings by Users")
xlabel('Question Number')
ylabel('Score')

c = [2.0, 4.0, 6.0, 8.0]
m = [x - 0.5 for x in c]

xticks(c, df['Question'])

bar(m, df['Mike'], width=0.5, color="#91eb87", label="Mike")
bar(c, df['Charles'], width=0.5, color="#eb879c", label="Charles")

legend()
axis([0, 10, 0, 8])
savefig('barchart.png')

pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 12)
pdf.cell(60)
pdf.cell(75, 10, "A Tabular and Graphical Report of Professor Criss's Ratings by Users Charles and Mike", 0, 2, 'C')
pdf.cell(90, 10, " ", 0, 2, 'C')
pdf.cell(-40)
pdf.cell(50, 10, 'Question', 1, 0, 'C')
pdf.cell(40, 10, 'Charles', 1, 0, 'C')
pdf.cell(40, 10, 'Mike', 1, 2, 'C')
pdf.cell(-90)
pdf.set_font('arial', '', 12)
for i in range(0, len(df)):
    pdf.cell(50, 10, '%s' % (df['Question'].iloc[i]), 1, 0, 'C')
    pdf.cell(40, 10, '%s' % (str(df.Mike.iloc[i])), 1, 0, 'C')
    pdf.cell(40, 10, '%s' % (str(df.Charles.iloc[i])), 1, 2, 'C')
    pdf.cell(-90)
pdf.cell(90, 10, " ", 0, 2, 'C')
pdf.cell(-30)
pdf.image('barchart.png', x = None, y = None, w = 0, h = 0, type = '', link = '')
pdf.output('test.pdf', 'F')

Expected test.pdf:

Update (April 2020): I made an edit to the original answer in April 2020 to replace use of pandas.DataFrame.ix() since this is deprecated. In my example I was able to replace it's use with pandas.DataFrame.iloc and the output is the same as before.

Answer from Patrick Long on Stack Overflow
Top answer
1 of 4
76

There are a lot of options for creating a pdf in python. Some of these options are ReportLab, pydf2, pdfdocument and FPDF.

The FPDF library is fairly stragihtforward to use and is what I've used in this example. FPDF Documentation can be found here.

It's perhaps also good to think about what python modules you might want to use to create graphs and tables. In my example, I use matplotlib (link to docs) and I also use Pandas to create a dataframe using pandas.dataframe().

I've posted a rather lengthy but fully reproducible example below, using pandas, matplotlib and fpdf. The data are a subset of what the OP provided in the question. I loop through the dataframe in my example to create the table, but there are alternative and perhaps more efficient ways to do this.

import pandas as pd
import matplotlib
from pylab import title, figure, xlabel, ylabel, xticks, bar, legend, axis, savefig
from fpdf import FPDF


df = pd.DataFrame()
df['Question'] = ["Q1", "Q2", "Q3", "Q4"]
df['Charles'] = [3, 4, 5, 3]
df['Mike'] = [3, 3, 4, 4]

title("Professor Criss's Ratings by Users")
xlabel('Question Number')
ylabel('Score')

c = [2.0, 4.0, 6.0, 8.0]
m = [x - 0.5 for x in c]

xticks(c, df['Question'])

bar(m, df['Mike'], width=0.5, color="#91eb87", label="Mike")
bar(c, df['Charles'], width=0.5, color="#eb879c", label="Charles")

legend()
axis([0, 10, 0, 8])
savefig('barchart.png')

pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 12)
pdf.cell(60)
pdf.cell(75, 10, "A Tabular and Graphical Report of Professor Criss's Ratings by Users Charles and Mike", 0, 2, 'C')
pdf.cell(90, 10, " ", 0, 2, 'C')
pdf.cell(-40)
pdf.cell(50, 10, 'Question', 1, 0, 'C')
pdf.cell(40, 10, 'Charles', 1, 0, 'C')
pdf.cell(40, 10, 'Mike', 1, 2, 'C')
pdf.cell(-90)
pdf.set_font('arial', '', 12)
for i in range(0, len(df)):
    pdf.cell(50, 10, '%s' % (df['Question'].iloc[i]), 1, 0, 'C')
    pdf.cell(40, 10, '%s' % (str(df.Mike.iloc[i])), 1, 0, 'C')
    pdf.cell(40, 10, '%s' % (str(df.Charles.iloc[i])), 1, 2, 'C')
    pdf.cell(-90)
pdf.cell(90, 10, " ", 0, 2, 'C')
pdf.cell(-30)
pdf.image('barchart.png', x = None, y = None, w = 0, h = 0, type = '', link = '')
pdf.output('test.pdf', 'F')

Expected test.pdf:

Update (April 2020): I made an edit to the original answer in April 2020 to replace use of pandas.DataFrame.ix() since this is deprecated. In my example I was able to replace it's use with pandas.DataFrame.iloc and the output is the same as before.

2 of 4
9

A slightly heretical answer: RMarkdown (in RStudio), with Python code chunks, via reticulate (the default way now) that gives you a long-lived Python "session" just like in a Jypiter notebook. The RMarkdown document can then be "knit" into PDF, html, Word, html-slides, and even PowerPoint.

Seriously, the R world is streets ahead in this area.

๐ŸŒ
Anvil
anvil.works โ€บ blog โ€บ generate-pdf-with-python
Generating PDF Reports from a Python Script - Anvil Works
# Build a pie chart breaking down revenue sources self.plot_1.layout.title="Revenue Sources" self.plot_1.data = go.Pie(labels=[r['category'] for r in records], values=[r['revenue'] for r in records]) # Build a graph chart with last month and this month's revenue # for each category self.plot_2.layout.title = "Month-On-Month" self.plot_2.data = [go.Bar(x=[r['category'] for r in records], y=[r['revenue_last_month'] for r in records], name="Last month"), go.Bar(x=[r['category'] for r in records], y=[r['revenue'] for r in records], name="This month")] If we run our script, we have created a complete sales report in PDF form! You now have a Python script that will generate a beautiful PDF report โ€“ and you know how to design more!
Discussions

python - How to automatically build a high-quality dynamic PDF report? - Data Science Stack Exchange
Some texts will be static and some ... position of the charts may vary. Does anybody has any suggestion or experience in providing a dynamic data report PDF in production that would look similar to the above? Perhaps also with other technologies like Python or LaTeX... More on datascience.stackexchange.com
๐ŸŒ datascience.stackexchange.com
August 7, 2022
How can I set up graph layouts for including into a pdf report
Reportlab may be the best pure Python option. https://docs.reportlab.com/ More on reddit.com
๐ŸŒ r/learnpython
8
1
June 27, 2023
Best library for creating graphic PDF documents?
i would check out quarto, it supports python code natively and has support for cross-references, TOC, etc. that makes for really polished docs More on reddit.com
๐ŸŒ r/Python
46
64
September 18, 2024
Get Charts From Non Searchable PDFs
yes!! lookin forward to checking this out. More on reddit.com
๐ŸŒ r/Python
7
30
October 11, 2023
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ creating-pdf-reports-with-python-a53439031117
Creating PDF Reports with Python. Introduction | by Alexander Obregon | Medium
June 26, 2024 - ReportLab is a powerful and versatile open-source library for creating PDF documents using Python. It provides a wide range of functionalities that allow you to generate complex PDFs with text, images, tables, and charts.
๐ŸŒ
Plus2Net
plus2net.com โ€บ python โ€บ pdf-report.php
Generating PDF report using charts,tables, images and paragraphs by using Python ReportLab
February 5, 2019 - from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.lib.units import inch from chart_verticalbar_chart import d from table_1_basic import t from chart_linechart import line_chart from paragraph1 import p1,p2,p3 from chart_2_circle import d_circle my_path='G:\\My drive\\testing\\pypdf2\\my_pdf.pdf' c = canvas.Canvas(my_path, pagesize=letter) width, height = letter c.drawImage('D:\\top2.jpg',.1*inch,10*inch) # image at left side top d.wrapOn(c,400,400) d.drawOn(c, 3*inch,7.5*inch) # vertical bar chart t.wrapOn(c, width, height) t.drawOn(c,3.6*inch, 5.6*i
๐ŸŒ
Medium
david-kyn.medium.com โ€บ workplace-automation-generate-pdf-reports-using-python-fa75c50e7715
Workplace Automation: Generate PDF Reports Using Python | by David-kyn | Medium
August 6, 2021 - The reason we do so is because it is much easier to add an image than a table with the FPDF library. The above code uses the dataframe_image library to export the dataframe as an image, and store it in your local folder of choice. For this particular report, we are intending to add 2 charts to the PDF: (1) line chart to show trend, and (2) pie chart to show component breakdown.
๐ŸŒ
Mouse Vs Python
blog.pythonlibrary.org โ€บ home โ€บ reportlab: adding a chart to a pdf with python
ReportLab: Adding a Chart to a PDF with Python - Mouse Vs Python
September 3, 2021 - Most developers would want to be able to create some text, perhaps a table and insert the chart along with those elements. You would also usually have additional text following the chart. For this article, you will learn how to do just that. Letโ€™s create a simple Pie Chart and add it a simple PDF. This PDF that you will be creating will have a sentence before and after the chart. ... from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.validators import Auto from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.piecharts import Pie from report
๐ŸŒ
Xlwings
xlwings.org โ€บ blog โ€บ reporting-with-python
5 Python Libraries for Reporting and Factsheets - Xlwings
June 3, 2020 - The charts look great by default ... in Python: You can choose the year by clicking on the slider below the chart. In the background, every change to our year-slider will trigger the update_figure callback function and hence update the chart. By arranging your documents properly, you could create an interactive web dashboard that can also act as the source for your PDF factsheet, see for example their financial factsheet demo together with itโ€™s source ...
Find elsewhere
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ integrating-matplotlib-charts-in-a-pdf-in-python-with-borb
Integrating Matplotlib Charts in a PDF in Python With borb
July 16, 2023 - The gcf() function of the PyPlot instance returns the current figure (get current figure). This figure can be embedded into a PDF document, by injecting it in a Chart constructor, alongside your customization arguments such as the width, height and horizontal_alignment.
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ how to create pdf reports with python โ€“ the essential guide
How to Create PDF Reports with Python - The Essential Guide | Towards Data Science
March 5, 2025 - Creates a PDF matrix from the visualizations โ€“ a 2-dimensional matrix where a row represents a single page in the PDF report ... Itโ€™s possibly a lot to digest, so go over it line by line. The comments should help. The idea behind sorting is to obtain the month integer representation from the string โ€“ e.g., 3 from "3.png" and use this value to sort the charts. Delete this line if the order doesnโ€™t matter, but thatโ€™s not the case with months.
๐ŸŒ
Advsofteng
advsofteng.com โ€บ doc โ€บ cdpydoc โ€บ pdfreport.htm
PDF Report
Each page will also have a # header ... : # A page contains up to two charts m = MultiChart(760, 920) # Use addTitle to add a header m.addTitle("ChartDirector PDF Report Demonstration", "Arial Bold", 20) # Create the first chart c = drawXYChart(chartTime(yyyy, 1, 1), chartTime(yyyy ...
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ how to create a pdf report for your data analysis in python
How to Create a PDF Report for Your Data Analysis in Python | Towards Data Science
March 5, 2025 - pdf.image('./example_chart.png', x = 10, y = None, w = 100, h = 0, type = 'PNG') pdf.ln(ch) pdf.multi_cell(w=0, h=5, txt=lorem.paragraph()) pdf.output(f'./example.pdf', 'F') Matplotlib plot added to PDF report in Python (Image by the author) Unfortunately, there is no simple way to add a pandas DataFrame to a PDF report with the FPDF library.
Top answer
1 of 1
3

One interesting solution is to use plotly because it can generate good charts, and it can also write formulas with latex. Used with a HTML library like xhtml2pdf, you can generate any report.

In addition to that, it is a python library, so you can collect data from anywhere (database, excel file, etc.)

To install it:

pip install plotly

pip install xhtml2pdf

Example of pdf generation report from HTML:

import plotly
import xhtml2pdf

from xhtml2pdf import pisa             # import python module

graph_block = (''
            '<a href="{graph_url}" target="_blank">' # Open the interactive graph when you click on the image
                '<img style="height: 400px;" src="{graph_url}.png">'
            '</a>')
report_block = ('' +
    graph_block +
    '{caption}' + # Optional caption to include below the graph
    '<br>'      + # Line break
    '<a href="{graph_url}" style="color: rgb(190,190,190); text-decoration: none; font-weight: 200;" target="_blank">'+
        'Click to comment and see the interactive graph' + # Direct readers to Plotly for commenting, interactive graph
    '</a>' +
    '<br>' +
    '<hr>') # horizontal line                       



# Utility function
def convert_html_to_pdf(source_html, output_filename):
    # open output file for writing (truncated binary)
    result_file = open(output_filename, "w+b")

    # convert HTML to PDF
    pisa_status = pisa.CreatePDF(
            source_html,                # the HTML to convert
            dest=result_file)           # file handle to recieve result

    # close output file
    result_file.close()                 # close output file

    # return True on success and False on errors
    return pisa_status.err


convert_html_to_pdf(report_block , 'report.pdf')

Example of text in Latex:

import plotly.express as px

fig = px.line(x=[1, 2, 3, 4], y=[1, 4, 9, 16], title=r'$\alpha_{1c} = 352 \pm 11 \text{ km s}^{-1}$')
fig.update_layout(
    xaxis_title=r'$\sqrt{(n_\text{c}(t|{T_\text{early}}))}$',
    yaxis_title=r'$d, r \text{ (solar radius)}$'
)
fig.show()

Sources:

https://plotly.com/python/v3/pdf-reports/

https://plotly.com/python/LaTeX/

๐ŸŒ
Just into Data
justintodata.com โ€บ home โ€บ how to generate reports with python (3 formats/4 tools)ย as excel, html, pdf
How to generate Reports with Python (3 Formats/4 Tools) - Just into Data
August 23, 2021 - Now we have everything needed (sp500_history, sp500_history_summary, chart.png) to generate reports. Further learning: Please note we generated the above simple report quickly for demonstration only. To learn about using Python for data analysis, please check out our course Python for Data Analysis with projects.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Creating PDFs with Charts and Tables using Python Reportlab Library - YouTube
Using the Matplotlib and Reportlab libraries we generate a pdf containing a simple line chart and a customized table.Full Code: https://github.com/patrickjlo...
Published ย  November 19, 2024
๐ŸŒ
DNMTechs
dnmtechs.com โ€บ creating-pdf-reports-with-charts-from-a-database-in-python-3
Creating PDF Reports with Charts from a Database in Python 3 โ€“ DNMTechs โ€“ Sharing and Storing Technology Knowledge
Creating PDF reports with charts ... and organized manner. By using libraries such as pandas, matplotlib, and fpdf, developers can easily retrieve data from a database, create charts, and generate PDF reports with just a few lines of code....
๐ŸŒ
Python Forum
python-forum.io โ€บ Thread-Generate-PDF-reports
Generate PDF reports
August 26, 2018 - Hello, I need to generate nice-looking pdf reports with charts and tables. Right now i am looking at three different solutions, but can't figure out which is the most appropriate. -1 Using Matplot lib to generate charts and then using PyLatex t...
๐ŸŒ
Bytescrum
blog.bytescrum.com โ€บ how-to-create-pdf-reports-using-python
How to Create PDF Reports Using Python
September 13, 2024 - Graphics and Charts: Draw shapes, lines, and even create dynamic charts. Interactive Elements: Add hyperlinks, bookmarks, and form elements to your PDFs. Custom Fonts and Styles: Use custom fonts and styles to match your brand. For more detailed documentation and examples, you can explore the ReportLab User Guide. ... Generating PDF reports with Python and ReportLab is a versatile way to create professional documents programmatically.
๐ŸŒ
Aspose
products.aspose.com โ€บ aspose.words โ€บ python via .net โ€บ report โ€บ reporting for pdf
Generate PDF report in Python
Create appealing reports from PDF templates and custom data with Python. Empower your reports with lists, tables, charts, images, barcodes, and other document elements with Python via .NET.
๐ŸŒ
Nutrient
nutrient.io โ€บ blog โ€บ sdk โ€บ top 10 ways to generate pdfs in python
Top 10 Python PDF generator libraries: Complete guide for developers (2025)
December 17, 2025 - ReportLab works well for detailed reports with charts, graphs, and complex page layouts. For simpler PDFs, consider FPDF or img2pdf. PDFKit(opens in a new tab) is a thin Python wrapper around wkhtmltopdf(opens in a new tab), letting you generate ...