How to create a PDF file from an HTML / CSS source (including images) in Python?

Say I have an HTML / CSS page with some images in it, and I would like to generate a PDF from this source in Python - maybe?

+5
source share
3 answers

http://www.xhtml2pdf.com/

the setup was a little bizarre for me, but otherwise it worked fine.

+4
source

You can do something like this using Pisa:

def receipt(request, id):
    import ho.pisa as pisa
    from django.template.loader import render_to_string
    from datetime import datetime

    r = get_or_404(id, request.affiliate)    
    now = datetime.now()
    contents = render_to_string('home/reservations/receipt.html', {
        'reservation': r,
        'today': now
    })
    filename = now.strftime('%Y-%m-%d') + '.pdf'
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=' + filename
    pdf = pisa.CreatePDF(contents, response)
    if pdf.err:
        message(request, 'Unable to generate the receipt.')
        return HttpResponseRedirect(reverse('view_reservation', args=[r.id]))    
    else:
        return response

(This is a Django view that generates a receipt, but obviously you can use Pisa in any settings)

HTML, .

+4

All Articles