问题描述
我已经尝试了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样式。
;