Forums

Flask WeasyPrint PDF does not render PNG

I have some HTML I am trying to turn into a PDF to make available for download on my Flask app. I am using WeasyPrint and I can get the HTML to render fine in the PDF but I am struggling to make the PNG appear.

Here is my code to create the PDF:

def make_pdf(self):

    results = self.compute()
    graph = "file:///home/Lynkon/mysite/app/static/fig1.png"
    html = render_template('result_pdf.html', form=self, results=results, graph=graph)
    pdf = HTML(string=html, base_url='file:///home/Lynkon/mysite/app/static/').write_pdf()

I'm taking some results from a form and displaying it on a HTML template. I would like to display the PDF at the bottom in an img tag like so:

<img src="{{ graph }}">

I've tried several variations of this with no luck. I do not see any error messages, so I must be doing something very stupid. Any suggestions would be greatly appreciated, thank you!

I wonder if it is because you have one too many '/'

I have tried to remove the extra '/' with no luck. I googled around for answers to this problem any many people seem to have the same issue with getting a png to render in their PDFs.

The comment section of this blog https://pbpython.com/pdf-reports.html offered solutions which I was trying to replicate with no luck unfortunately.

Are you sure that WeasyPrint supports file:// URLs? Perhaps there are WeasyPrint forums where people that understand the internals of WeasyPrint can tell you things like that.

I'm looking around for some WeasyPrint forms. I've made a post on stackoverflow about the issue as well.

But here is an excerpt from the WeasyPrint docs: https://weasyprint.readthedocs.io/en/stable/tutorial.html#access-to-local-files

Access to local files

As any web renderer, WeasyPrint can reach files on the local filesystem using file:// URIs. These files can be shown in img or embed tags for example.

When WeasyPrint used on a server with HTML or CSS files from untrusted sources, this feature may be used to know if files are present on the server filesystem, and to embed them in generated documents.

So I do believe it has the capability. It's just tricky to get it to work.

If WeasyPrint has some sort of argument where you can get it to log what it's doing, perhaps you can use that to get more information. You could also try that code in a Python console to perhaps see if there is any output that you can use to help you.

Solved the issue, thanks!

The problem was actually with my HTML/CSS that was wrapping around my img tag. After I removed everything but the img tag, I was able to display the png.

Glad to hear that you made it work!