如何將繪圖圖形與其他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天全站免登陸
全免费A级毛片免费看无码播放