D
D
Daniil Sergeev2016-04-22 14:54:25
Django
Daniil Sergeev, 2016-04-22 14:54:25

How can I generate pdf documents in Django?

Please tell me which library or other means can be used to implement the function of creating a document ready for printing. It is necessary that a document is formed that has a certain form, which is filled with data from the database. In PHP, I kind of heard that there is something like that. But for Django (namely, so that the document can be generated by pressing a button on a site that is written in Django), I don’t know anything like that. Is this really real? :) Thanks

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Gornostaev, 2016-04-22
@sd12

Reportlab
xhtml2pdf
PyPDF2

A
Alexander, 2016-04-22
@syschel

My example of a PDF generation function based on passing an html template and a context (data from a database).
xhtml2pdf

from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
import cStringIO as StringIO
import xhtml2pdf.pisa as pisa

def render_to_pdf(template_src, context_dict, filename='contract.pdf'):
    """ Отдаю PDF файл """
    template = get_template(template_src)
    context = Context(context_dict)
    html = template.render(context)
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(
        StringIO.StringIO(html.encode('utf-8')),
        result,
        encoding='UTF-8',
        show_error_as_pdf=True
    )
    if not pdf.err:
        response = HttpResponse(result.getvalue(), content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response
    return HttpResponse(u'We had some errors!')

def contract_text(request):
    text = ContractText.objects.filter(user=request.user)
    return render_to_pdf('pfd_template.html', {'text': text}, 'new_contract.pdf')

Z
zelsky, 2016-04-22
@zelsky

I wrote special styles. When you press ctrl + p, you get a document ready for printing.
https://www.smashingmagazine.com/2011/11/how-to-se...

F
Finger Gross, 2017-03-19
@GrossFinger

1. Generate or open ready and edit with any python-docx
2. Save to a temporary file
3. Call the console command https://wiki.ubuntuusers.de/unoconv/ for a temporary file
4. Stream the resulting pdf

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question