【问题标题】:django xhtml2pdf not getting imagedjango xhtml2pdf没有得到图像
【发布时间】: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 并将其用作变量&lt;img src="{{img}}" &gt;

标签: python django xhtml2pdf


【解决方案1】:

我建议修改你的html模板,并使用图像文件的绝对/相对路径(硬盘中的目录路径)而不是使用{% static %}标签。静态标签仅适用于渲染 HTMl,但 pisa 无法从中读取图像。

我从一个从 html 生成 PDF 的项目中获得了这段代码,我的图像是这样完成的:

<img src="{{ STATIC_ROOT }}/report/logo.png" >

其中 STATIC_ROOT 是从渲染上下文传递的变量。

【讨论】:

  • 我通过了,它不起作用,我想,我需要在设置文件上更改一些内容>
  • 尝试硬编码驱动器中实际文件的路径
  • 是的,我试过硬编码:STATIC_ROOT = '/home/py/Desktop/weasprint/staticfiles'
  • staticfiles下ok.jpg吗?或者可能是静态文件/img
  • 不,它在静态文件中,不在任何子文件夹中
【解决方案2】:

如果它仍然相关,这对我有用。

我的静态文件夹在我的根目录中。

{% 加载静态 %}

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 2018-05-20
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多