为了从数据库打印字符串,我所知道的是生成一个pdf,然后在按钮点击时渲染它。 我想通过单击按钮来实现所有这些(生成pdf和渲染)。 是否有更快的&有效的方法来实现这一目标?
答案 0 :(得分:2)
我认为你必须在同一个视图中生成和渲染pdf。我有一个宠物项目,我生成pdf票http://ticket4event.herokuapp.com/en/
View,负责生成和返回pdf票证:
def ticket(request, pk):
"""
Show example of the ticket
:param request:
:return: response
"""
t = get_object_or_404(Ticket, pk=pk)
pdf_ticket = ticket_to_pdf(t.visitor, t.event)
response = HttpResponse(pdf_ticket['content'], content_type=pdf_ticket['mimetype'])
response['Content-Disposition'] = ('inline; filename=' + pdf_ticket['filename'])
return response
用于渲染pdf的辅助函数:
def ticket_to_pdf(visitor, event):
"""
Render ticket to pdf
:param visitor:
:param event:
:return: dict with pdf and meta info
"""
filename = 'ticket.pdf'
current_site = Site.objects.get_current().domain
site = '{scheme}://{host}'.format(scheme=config.SCHEME, host=current_site)
url = pyqrcode.create(current_site + visitor.get_absolute_url())
qr_code = url.png_as_base64_str(scale=5)
ticket = render_to_string('pdf/ticket.html', {'visitor': visitor,
'qr_code': qr_code,
'event': event,
'config': config})
html = HTML(string=ticket, base_url=site)
pdf = html.write_pdf()
return {
'filename': filename,
'content': pdf,
'mimetype': 'application/pdf',
}