Skip to main content
 首页 » 编程设计

python之Weasy Print 的 Unicode 解码

2024年12月31日9arxive

尝试使用 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': '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())” 这是我第一次遇到这样的问题,我该如何解决? 谢谢!

请您参考如下方法:

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

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