我已经尝试了3个库转换HTML到PDF,即xhtml2pdf,weasyprint和wkhtmltopdf。
我的HTML有绘图图形包含在其中,他们是离线绘图。从plotly.offline.plots生成的图形
当我在浏览器中加载相同的HTML时,图形和其他HTML内容呈现良好,但当使用上面提到的任何一个库将其转换为PDF时,HTML内容呈现良好,但图形在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中呈现Plotly图形吗?
发布于 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渲染部分:
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
上显示的超文本标记语言样式。
https://stackoverflow.com/questions/63087172
复制相似问题