【发布时间】:2020-03-31 17:50:42
【问题描述】:
我正在尝试将 html 渲染为 pdf,它真的很棒!只有一个问题,那就是模板获取图像:
我正在使用 python xhtml2pdf 库进行 pdf 渲染
这是我渲染 pdf 的方法:
def render_pdf(template_src, context_dict):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('Unable to process the request, We had some errors<pre>%s</pre>' % escape(html))
这是我下面的views.py:
def test_view(request):
context = {
'test': 'a test string'
}
return render_pdf('test.html', context)
这是我的test.html
{% load static %}
<p>hello test </p>
<img src="{% static 'ok.jpg' %}">
如果我使用 django 默认的 render 方法渲染它会得到图像但是当我渲染 pdf 时图像没有得到。
我听说过这个解决方案使用 link_callback 方法和这个文档:https://xhtml2pdf.readthedocs.io/en/latest/usage.html
我不知道在哪里包含此内容或如何实现此内容。
在这种情况下谁能帮助我?
【问题讨论】:
-
您可以直接在视图中渲染图像。
img = settings.STATIC_URL + "/path/to/img"并在渲染您的 pdf 之前通过上下文发送。您需要使用template.render(Context(context))渲染pdf 并将其用作变量<img src="{{img}}" >