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

问题描述 投票:1回答:1

我正在构建一个项目,我需要从模板(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

有人能帮我吗?

django xhtml2pdf
1个回答
1
投票

如果你正在使用html到pdf,你还需要提供链接回调以便能够显示图像:

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

© www.soinside.com 2019 - 2024. All rights reserved.