Is there a way to generate pdf containing non-ascii symbols with pisa from django template?

后端 未结 6 805
情歌与酒
情歌与酒 2021-02-05 08:11

I\'m trying to generate a pdf from template using this snippet:

def write_pdf(template_src, context_dict):
    template = get_template(template_src)
    context          


        
6条回答
  •  庸人自扰
    2021-02-05 08:32

    I am using xhtml2pdf version 0.2.4 I faced the same issue and I was able to resolve using this encoding:

    def render_to_pdf(template_src, context_dict={}):
        template = get_template(template_src)
        html = template.render(context_dict)
        result = BytesIO()
    
        # PDF
        pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
        if not pdf.err:
            return HttpResponse(result.getvalue(), content_type='application/pdf')
        return None
    

    Then in my views, I have defined like:

    def download_pdf(request, pk):
    item = get_object_or_404(object, id=pk)
    if item:
        context ={
            'item': item
        }
        template_name = 'template.html'
        pdf = render_to_pdf(template_name, context)
        return HttpResponse(pdf, content_type='application/pdf')
    
    else:
        messages.info(request, 'Item not found')
        return redirect('home')
    

    My HTML:

    {% load static %}
    {% load humanize %}
    
    
    
    
        
        
    
        
        {{ item.scientific_name}}
        
    
       
    

提交回复
热议问题