5

I have tried 3 libraries for converting HTML to PDF ie xhtml2pdf, weasyprint & wkhtmltopdf.

My HTML has plotly graphs included in it, they are offline plots ie. graphs generated from plotly.offline.plots

When I load the same HTML in browser the graphs and other HTML content render well but when its converted to PDF using any one of the libraries mentioned above, the HTML content renders well but Graph becomes blank inside PDF.

from plotly.graph_objs import Scatter
from plotly.offline import plot

fig = plot([Scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])], output_type='div')

I pass this fig into Django template and render it as

{{ fig|safe }}

Used the xhtml2pdf, weasyprint & wkhtmltopdf to convert the HTML into PDF but none of them displayed the graphs.

What am I missing in my code ? Can any one tell me will any of the HTML to PDF conversion libraries render the Plotly graphs in the PDF ?

2
  • I am having the same problem using wkhtmltopdf, I wanted to add, I run the code on windows 10. Whereas other developers working on ubuntu seem to make it work.
    – Alex_H
    Aug 10, 2020 at 12:34
  • pdfkit worked for me, whereas wkhtmltopdfdid not.
    – micycle
    Jan 10 at 16:41

4 Answers 4

1

I searched high and low and could not find anything. Hacked together a solution that worked very well for me:

import plotly.graph_objs as go
import plotly.io as pio

labels = ['Alice','Bob','Carl']
vals = [2,5,4]

data = [go.Bar(x=vals, y=labels, orientation='h')]

layout = go.Layout(margin_pad=10)
fig = go.Figure(data=data,layout=layout)

svg = pio.to_image(fig, format="svg")
context["svg"] = svg.decode("utf-8")

and then in the template something like this

<div>
{{ svg|safe }}
</div>

The first solution I tried had me generate a png on plotly's website and then encode the image and then add it to an image tag and so on. The quality was very bad though. This solution is a lot more crisp.

I used it with weasyprint, but I'm sure it will work with other solutions as well.

0

I had the same issue, eventually just saved figure to image file then loaded image into template then rendered using weasyprint (Seems to mess the styling up less than the other solutions).

See below link on how to save figure to image.

https://plotly.com/python/static-image-export/

Other useful links:

https://weasyprint.readthedocs.io/en/latest/features.html#html

https://weasyprint.org/samples/

view.py's pdf rendering part:

    html_string = render_to_string('management/report_template.html', context)
    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    result = html.write_pdf(presentational_hints=True)

    # Creating http response
    response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'inline; filename=report.pdf'
    response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output = open(output.name, 'rb')
        response.write(output.read())

    return response

base_url=request.build_absolute_uri() will allow for relative URLs in the HTML file. presentational_hints=True For the HTML styles to show on the PDF.

0

According to Pyplot itself you cannot have interactive plots in data formats that are not HTML e.g. PNG, JPEG, SVG or PDF (Source)

If you want to include the image in a PDF file you must first convert the plot to an image and then add the image to the HTML file that you later convert using the standard tools s.a. weasyprint or pdfkit. How to get the image file is explained in the same source: Static Image Export in Python

0

I think the answers here are okay (plotly.io does not exist anymore) but the best way to do this is to use kaleido and then base64-encode the image to include it directly into the HTML. This way, you do not need to worry about the image path and making sure everything is relative to the same directory.

In your HTML template, simply do:

<img src="{fig1}">

Now you need to include fig1 as a variable in your template context and you can create the right value for fig1 using base64 encoding and kaleido:

import base64
import plotly.graph_objects as go
from kaleido.scopes.plotly import PlotlyScope

go = go.Figure()
# do something here with your figure...

img_bytes = PlotlyScope().transform(
    figure=self.figure,
    format="png",
    width=500,
    height=500,
    scale=2
)
fig1 = f"data:image/png;base64,{base64.b64encode(img_bytes).decode('utf8')}"

This should do the trick and works great. No files, no paths, and all the images of the graphs are directly put into your HTML.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.