Carlos Belardo
Carlos Belardo

Reputation: 1

Creating a table in python and printing to a PDF

I know some similar questions have been asked but none have been able to answer my question or maybe my python programming skills are not that great(they are not). Ultimately I'm trying to creating a table to look like the one below, all of the "Some values" will be filled with JSON data which I do know how to import but creating the table to then export it to a PDF using FPDF is what is stumping me. I've tried pretty table and wasn't able to achieve this I tried using html but really I dont know too much html to build a table from scratch like this. so if some one could help or point in the right direction it would be appreciated.

Header for FPDF Document

Upvotes: 0

Views: 2628

Answers (1)

atomicfruitcake
atomicfruitcake

Reputation: 375

I would recommend the using both the Pandas Library and MatplotLib

Firstly, with Pandas you can load data in from a JSON, either from a JSON file or string with the read_json(..) function documented here.

Something like:

import pandas as pd

df = pd.read_json("/path/to/my/file.json")

There is plenty of functionality withing the pandas library to manipulate your dataframe (your table) however you need.

Once you're done, you can then use MatplotLib to generate your PDF without needing any HTML

This would then become something like

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

df = pd.read_json("/path/to/my/file.json")

# Manipulate your dataframe 'df' here as required.

# Now use Matplotlib to write to a PDF

# Lets create a figure first
fig, ax = plt.subplots(figsize=(20, 10))

ax.axis('off')

the_table = ax.table(
    cellText=df.values,
    colLabels=df.columns,
    loc='center'
)

# Now lets create the PDF and write the table to it
pdf_pages = PdfPages("/path/to/new/table.pdf")
pdf_pages.savefig(fig)
pdf_pages.close()

Hope this helps.

Upvotes: 1

Related Questions