Generate Beautiful HTML and PDF Reports with Pretty HTML Table and WeasyPrint

Including Cython, Jython, IronPython, PyPy, Django framework, and interpreters: Ipython, IPython Jupyter/Notebook, CPython


Post Reply
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#1

Pretty-HTML-Table and WeasyPrint are Python packages that can be used in combination to generate pretty HTML and PDF reports. A while ago, we showed how to automate reports with Pandas and Python and save the resulting Pandas DataFrame to HTML, and how to generate PDF Reports with Pandas, Jinja and WeasyPrint. Today, we present the Python code below that illustrates the combined power of pretty_html_table and WeasyPrint to generate beautiful HTML and PDF reports using the global 2019 GDP Per Capita, Life Expectancy, and other Social Factors Dataset featured here.

  1. from pretty_html_table import build_table
  2. import pandas as pd
  3. import seaborn as sns
  4.  
  5. from weasyprint import CSS
  6. from weasyprint import HTML
  7.  
  8. import matplotlib.pyplot as plt
  9.  
  10. df = pd.read_csv('https://raw.githubusercontent.com/fati8999-tech/Data-visualization-with-Python-Using-Seaborn-and-Plotly_-GDP-per-Capita-Life-Expectency-Dataset/master/2019.csv')
  11.  
  12. #Change colors as appropriate: blue_light, blue_dark, grey_light, grey_dark, orange_light, orange_dark, yellow_light, yellow_dark, green_light, green_dark, red_light, red_dark
  13. output = build_table(df, 'green_light', font_size='medium', font_family='Open Sans, sans-serif', text_align='left', width='auto', index=False, even_color='black', even_bg_color='white')
  14.  
  15. #Let's create an image and attach it to HTML
  16. plt.style.use('ggplot')
  17. sns.pairplot(df)
  18. plt.savefig("email_plots.png")
  19.  
  20. with open("email_report.html","w+") as file:
  21.     file.write(output)
  22.     file.write("<img src='email_plots.png'/>")
  23.  
  24. #HTML(string=output).write_pdf("email_report.pdf")
  25. HTML(string=output).write_pdf("email_report.pdf", stylesheets=[CSS(string='@page { size: landscape }')])

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#2

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
Post Reply

Return to “Python Programming”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 14 guests