尝试使用Django构建简单的Weasy打印应用程序

在views.py中做了一些功能:



def generate_pdf(request):
    # Model data
    students = Student.objects.all().order_by('last_name')
    context = {
                'invoice_id': 18001,
                'street_name': 'Rue 76',
                'postal_code': '3100',
                'city': 'Washington',
                'customer_name': 'John Cooper',
                'customer_mail': '[email protected]',
                'amount': 1339.99,
                'today': 'Today',
                }

    # Rendered
    html_string = render_to_string('pdf/invoice.html', context)
    html = HTML(string=html_string)
    result = html.write_pdf()

    # Creating http response
    response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'inline; filename=list_people.pdf'
    response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output = open(output.name, 'r')
        response.write(output.read())

    return response





运行它后,我在行“ response.write(output.read())”中得到一个UnicodeDecodeError。
这是我第一次遇到这样的问题,该如何解决?
谢谢!

最佳答案

通过简单地将'r'更改为'rb'来修复它:

output = open(output.name, 'rb')

08-25 06:11