尝试用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“响应.写入(输出.读取())" 这是我第一次遇到这样的问题,我该怎么解决呢? 谢谢!
如果您只想将生成的PDF作为http响应返回,那么下面的解决方案适用于我。我不知道你的模板。例如,我使用
{{ content.invoid_id }}
来访问模板中的上下文值。在不需要临时文件。希望这有帮助!在
编辑:如果需要文件字节,可以这样做:
^{pr2}$你使用哪个版本的Python?2.x还是3.x?在
您是否尝试过encode()并导入以下模块:
from __future__ import unicode_literals
通过简单地将'r'改为'rb'来修复它:
相关问题 更多 >
编程相关推荐