【问题标题】:I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf我正在尝试使用 pdfkit 将 HTML 模板转换为 PDF,但模板中的数据未加载到 pdf 中
【发布时间】:2021-04-02 12:05:59
【问题描述】:
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 %}  

![这是我得到的第一个 pdf ][1]

[1]:(https://i.stack.imgur.com/PXlt3.png)

我正在尝试使用 pdfkit 将 HTML 模板转换为 PDF,但模板中的数据未加载到 pdf 中 谁能帮帮我,我不知道是什么问题

【问题讨论】:

    标签: html django pdfkit


    【解决方案1】:

    在您的简历功能中: 而不是:

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

    使用这个:

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

    您的代码将如下所示:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2023-02-24
      • 2023-01-11
      • 2018-09-05
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多