Unicode Decode для Weasy Print - PullRequest
       6

Unicode Decode для Weasy Print

0 голосов
/ 21 сентября 2018

Попытка создать простое приложение Weasy Print с помощью Django

Сделал небольшую функцию в 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': 'customer@customer.at',
                '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

После его запуска я получаю UnicodeDecodeError для строки "response.write (output.read ())" Я впервые сталкиваюсь с такой проблемой, как я могуэто исправить?Спасибо!

Ответы [ 3 ]

0 голосов
/ 01 октября 2018

Если вы хотите вернуть сгенерированный PDF-файл как http-ответ, у меня работает следующее решение.Я не знаю ваш шаблон.Я использую {{ content.invoid_id }}, например, для доступа к значениям контекста в шаблоне.

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': 'customer@customer.at',
                'amount': 1339.99,
                'today': 'Today',
    }
    content = Context()
    content.update(context)
    template = loader.get_template('yourtemplate.html')

    # render and return
    html = template.render(context={'content':content}, request=request)
    response = HttpResponse(content_type='application/pdf')
    HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response)
    return response

Нет необходимости во временном файле.Надеюсь, это поможет!

Редактировать: если вам нужны байты файла, вы можете сделать это следующим образом:

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': 'customer@customer.at',
                'amount': 1339.99,
                'today': 'Today',
    }
    content = Context()
    content.update(context)
    template = loader.get_template('yourtemplate.html')
    html = template.render(context={'content':content})

    with TemporaryFile() as pdf:
        HTML(string=html, base_url=url).write_pdf(pdf)
        pdf.seek(0)
        # do what every you want with pdf.read())
0 голосов
/ 02 ноября 2018

Исправлено с простым изменением «r» на «rb»:

output = open(output.name, 'rb')
0 голосов
/ 21 сентября 2018

какую версию Python вы используете?2.x или 3.x?

Вы пытались кодировать () и импортировать следующий модуль: from __future__ import unicode_literals

...