尝试在Django中将html转换为pdf时出现意外输出

时间:2018-12-12 12:35:17

标签: python django django-rest-framework pdf-generation

这是将html转换为django的视图

@api_view(['GET'])
@renderer_classes((JSONRenderer,TemplateHTMLRenderer))
def admin_order_pdf(request, order_id, *args, **kwargs):
# def admin_order_pdf(request, order_id):

    queryset=D.objects.all()
    # serializer=
    order = get_object_or_404(queryset, id=order_id)
    price=order.price
    discount=order.discount
    total=price-discount
    template=get_template('bill/bill.html')
    data={
    'order': order,'total':total
    }
    html = render_to_pdf('bill/bill.html',
    data)
    return HttpResponse(html, content_type='application/pdf')

这是render_to_pdf的代码

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

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)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

和我的urls.py

re_path(r'^bill/(?P<order_id>\d+)/pdf/$',
    admin_order_pdf,
 name='admin_order_pdf'),

和我的html模板

<html>
<body>
 <h1>My Shop</h1>
 <p>
   {% for ord in order %}
   <li>{{ ord.name }}</li>
   {% endfor %}

但是每当我尝试访问url时,我都可以加载pdf,但是该特定pdf文件中没有任何内容,只有一个单词“ profiles”我什至不知道该单词来自何处

0 个答案:

没有答案