首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将绘图图形与其他HTML内容一起导出到pdf?

如何将绘图图形与其他HTML内容一起导出到pdf?
EN

Stack Overflow用户
提问于 2020-07-25 18:21:39
回答 1查看 1.2K关注 0票数 4

我已经尝试了3个库转换HTML到PDF,即xhtml2pdf,weasyprint和wkhtmltopdf。

我的HTML有绘图图形包含在其中,他们是离线绘图。从plotly.offline.plots生成的图形

当我在浏览器中加载相同的HTML时,图形和其他HTML内容呈现良好,但当使用上面提到的任何一个库将其转换为PDF时,HTML内容呈现良好,但图形在PDF中变为空白。

代码语言:javascript
运行
复制
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模板中,并将其呈现为

代码语言:javascript
运行
复制
{{ fig|safe }}

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

我的代码中遗漏了什么?谁能告诉我HTML到PDF的转换库会在PDF中呈现Plotly图形吗?

EN

回答 1

Stack Overflow用户

发布于 2020-10-10 22:44:39

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

请参阅下面的链接,了解如何将图形保存到图像。

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

其他有用的链接:

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

https://weasyprint.org/samples/

view.py的pdf渲染部分:

代码语言:javascript
运行
复制
    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上显示的超文本标记语言样式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63087172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档