Weasy-Prin的Unicode解码

2024-05-19 05:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

做了点小动作视图.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 for the line“响应.写入(输出.读取())" 这是我第一次遇到这样的问题,我该怎么解决呢? 谢谢!


Tags: djangoname应用程序outputstringpdfresponsehtml
3条回答

如果您只想将生成的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

不需要临时文件。希望这有帮助!在

编辑:如果需要文件字节,可以这样做:

^{pr2}$

你使用哪个版本的Python?2.x还是3.x?在

您是否尝试过encode()并导入以下模块:from __future__ import unicode_literals

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

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

相关问题 更多 >

    热门问题