Search code examples
htmldjangopdfkit

I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf


views.py

def resume(request,id):
    user_profile=Profile.objects.get(pk=id) 
    template= loader.get_template("Resume/profile.html")
    html= template.render({'user_profile':user_profile})
    options={
        'page-size':'Letter',
        'encoding' : 'UTF-8',
        
    }

    pdf= pdfkit.from_string(html,False,options)
    response= HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition']= 'attachment' 
    return response




profile.html

{% extends "Resume/layout.html" %}

{% block body %}
  
  <h2>{{ user_profile.full_name }}</h2>
  <h2>{{ user_profile.job_title }}</h2>
  <hr>
  <h2>{{ user_profile.email }}</h2>
  <h2>{{ user_profile.phone }}</h2>
  <h2>{{ user_profile.home_adress }}</h2>
  
  <hr>

  <p>Summary</p>
  <p> {{ user_profile.work_experience }}</p>
  <p> {{ user_profile.skills }}</p>
  <hr>
  
  <p>Education</p>
  <ul>
      <li>
          {{user_profile.diplomes}}
      </li>
  </ul>
  <hr>

{% endblock %}  

![this is th pdf i get ][1]

[1]:( https://i.sstatic.net/PXlt3.png)

I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf can anyone help me with this, i don't know what the problem is


Solution

  • In your resume function: instead of:

    template= loader.get_template("Resume/profile.html")
    html= template.render({'user_profile':user_profile}
    

    use this:

    html = loader.render_to_string('Resume/profile.html', {'user_profile':user_profile})
    

    your code will look like this:

    from django.template import loader
    def resume(request,id):
        user_profile=Profile.objects.get(pk=id)
        html = loader.render_to_string('Resume/profile.html', {'user_profile':user_profile})
        options={
            'page-size':'Letter',
            'encoding' : 'UTF-8',
        }
        
        pdf= pdfkit.from_string(html, pdf_url)
        response= HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition']= 'attachment'
        return response