需要帮助以使用xhtml2pdf从模板呈现pdf中的img

时间:2019-04-29 14:04:02

标签: django xhtml2pdf

我正在构建一个项目,我需要将我的数据从模板(html)转换为pdf,我的问题是该图像在pdf视图上不存在。 这是我的代码:

class GeneratePdf_month(TemplateView):

    template_name = "polls/info_month.html"

    def get(self, request, *args, **kwargs):
        ## do some....
        data = {
            'cliente': cliente,
        }
        pdf = render_to_pdf(self.template_name, data)
        return HttpResponse(pdf, content_type='application/pdf')


## and this is my html template
<head>
    {% load staticfiles %}
    <title>Detail</title>
    <style>
        table, th, td {
          border: 1px solid black;
          border-collapse: collapse;
          padding: 10px;
        }

    </style>
</head>
<body>
    <header>BlaBla<img src="{% static 'polls/images/image.png'%}"></header>
</body

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

如果您使用的是xhtmltopdf,则还需要提供一个link_callback以便于显示图像:

def link_callback(uri, rel):
    """
    Convert HTML URIs to absolute system paths so xhtml2pdf can access those
    resources
    """
    # use short variable names
    sUrl = settings.STATIC_URL     # Typically /static/
    #static Root
    sRoot = settings.STATIC_ROOT    # Typically /home/userX/project_static/
    mUrl = settings.MEDIA_URL       # Typically /static/media/
    mRoot = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/

    # convert URIs to absolute system paths
    if uri.startswith(mUrl):
        path = os.path.join(mRoot, uri.replace(mUrl, ""))
    elif uri.startswith(sUrl):
        path = os.path.join(sRoot, uri.replace(sUrl, ""))
    else:
        return uri  # handle absolute uri (ie: http://some.tld/foo.png)

    # make sure that file exists
    if not os.path.isfile(path):
            raise Exception(
                'media URI must start with %s or %s' % (sUrl, mUrl)
            )
    return path

不要忘了在您的render_to_pdf中添加链接回调:

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict) 
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=link_callback)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf') 
    return None

您还需要在img标签内指定高度和宽度,例如:

<img src="{% static 'polls/images/image.png'%}" alt="image" width="200" height="150" />

在settings.py中不要忘记定义您的STATIC_URL和STATIC_ROOT,MEDIA_URL和MEDIA_ROOT

例如,像这样:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'project_name/static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'project_name/media/')

然后别忘了在终端上运行 python manage.py collectstatic

此处有更多信息:https://xhtml2pdf.readthedocs.io/en/latest/usage.html#using-xhtml2pdf-in-django