WeasyPrint Not Inserting Images From Jinja2 For PDF Report

Viewed 2134

I am trying to create a report from a pandas dataframe using Jinja2 and Weasyprint. I am running into an issue where WeasyPrint is not properly displaying the images. The images are static and loaded in a folder.

I had this working with xhtml2pdf. This solution was working and producing the report that I wanted. But the styling was not as accurate as WeasyPrint is. So I would like to move forward with using WeasyPrint.

import pandas as pd
from datetime import date
import jinja2, os
#from xhtml2pdf import pisa
from weasyprint import HTML
import matplotlib.pyplot as plt
    t.plot.pie(figsize=(5, 5), label="", rot=90, legend=True)
    extensionPieChart = f"{imagesFolder}\\extensionPieChart.png"
    plt.savefig(extensionPieChart)
    t = t.reset_index()
    html = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath='')). \
            get_template(f'html_template.html'). \
            render(
                date=date.today().strftime('%d, %b %Y'),
                df=dfTemp.head(), 
                name = user,
                pie_chart = extensionPieChart,
                totals = t,
                companyImage = companyImage)
    print('Converting HTML to PDF')
    HTML(string=html).write_pdf(f'{reportsFolder}\\{user} Report.pdf')

Here is the HTML code from my HTML template

<td style="text-align:right"><img src="{{ pie_chart }}">

When I look at the code generated by Jinja2, the filepath is correct:

<td style="text-align:right"><img src="C:\Users\jg757fe\Desktop\Reports - Copy\Images\extensionPieChart.png">

I expect the image to show up but it isn't being inserted into the PDF. Any help would be appreciated

1 Answers

All I need to do was add file:\\ to my HTML Template:

Orignally ( not working )

<td style="text-align:right"><img src="{{ pie_chart }}">

Working

<td style="text-align:right"><img src="file:\\{{ pie_chart }}

Simple solution but not the most obvious

Related