I need to pass parameters by HttpResponse or in which case I look for an alternative from a pdf generator

0

Good afternoon dear stackoverflow friends.

I have a code that runs very well is a pdf generator from django. By means of which prints a html document as a common pdf and my current desire is to be able to pass parameters, that is, any dictionary to be able to print queries from an existing database to my pdf document here I leave all the code you need. Do the magic you want

views.py

from django.http import HttpResponse
from django.views.generic import View
from .pdf_generator import render_to_pdf

class GeneratePdf(View):
    def get(self, request, item_id,*args, **kwargs):
        data = {'item':item_id}
        pdf = render_to_pdf('cv/pdf-generator.html', data)
        print(pdf)
        return HttpResponse(pdf, content_type='application/pdf')

pdf_generator.py

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

cv / pdf-generator.html

{% extends "../base.html" %}

{% block content_style %}
body {
    font-family: "Helvetica", "sans-serif";
    color: #333333;
}
{% endblock content_style %}

{% block content %}
    <h1>Hello world!</h1>
    <h2>Welcome to the pdf!</h2>
{% endblock content %}

base.html

<!DOCTYPE html>
<html>
  {% include "meta.html" %}
  <body>
    <style>
      {% block content_style %}{% endblock content_style %}
    </style>
    {% block body %}
      {% include "navbar.html" %}
        {% if messages %}
        <div>
          <strong>Messages:</strong>
          <ul>
            {% for message in messages %}
            <li>{{message}}</li>
            {% endfor %}
          </ul>
        </div>
        {% endif %}
      <div class="main-content">
        <div class="container">
          <div class="row">
            <div class="col s12 m12 l12 xl12">
              {% block content %}{% endblock %}
            </div>
          </div>
        </div>
      </div>
    {% endblock %}
  </body>
</html>

urls.py

path('pdf/<int:item_id>', views.GeneratePdf.as_view(), name="pdfg"),
    
asked by Tysaic 13.06.2018 в 21:43
source

0 answers