如何将绘图图形与其他HTML内容一起导出为pdf? [英] How to export plotly graphs along with other HTML content into pdf?

查看:0
本文介绍了如何将绘图图形与其他HTML内容一起导出为pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了3个库来将HTML转换为PDF,即xhtml2pdf、weasyprint&;wkhtmltopdf。

我的超文本标记语言中包含了图形,它们是离线图形。从plotly.offline.plots生成的图表

当我在浏览器中加载相同的HTML时,图形和其他HTML内容呈现得很好,但当它使用上面提到的任何一个库转换为PDF时,HTML内容呈现良好,但Graph在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')

我将此图传递到Django模板并将其呈现为

{{ fig|safe }}

使用xhtml2pdf、weasyprint&;wkhtmltopdf将HTML转换为PDF,但它们都没有显示图形。

我的代码中遗漏了什么?谁能告诉我,是否会有任何从HTML到PDF的转换库在PDF中呈现Ploly图形?

推荐答案

我遇到了同样的问题,最终只是将图形保存到图像文件,然后将图像加载到模板中,然后使用weasyprint渲染(似乎比其他解决方案更少搞砸样式)。

有关如何将图形保存到图像的信息,请参阅下面的链接。

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

其他有用链接:

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

https://weasyprint.org/samples/

view.py的pdf呈现部分:

    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()将允许在HTML文件中使用相对URL。 presentational_hints=True要在PDF上显示的HTML样式。

这篇关于如何将绘图图形与其他HTML内容一起导出为pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆