Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a HTML Page to PDF using Django

Tags:

python

pdf

django

I have a web app in Django. It's a plataform to store bills and invoices. Now i'm trying to export those bills un PDF.

I'm using xhtml2pdf but it's not working.

I'm using this code for testing: http://obroll.com/generate-pdf-with-xhtml2pdf-pisa-in-django-examples/

It doesnt give any errors but doesnt generate the PDF documentos.

like image 521
user3657840 Avatar asked May 20 '14 18:05

user3657840


People also ask

How do I automatically convert HTML to PDF?

On a Windows computer, open an HTML web page in Internet Explorer, Google Chrome, or Firefox. On a Mac, open an HTML web page in Firefox. Click the “Convert to PDF” button in the Adobe PDF toolbar to start the PDF conversion. Enter a file name and save your new PDF file in a desired location.

How do I print an HTML page as a PDF?

Press the shortcut key Ctrl + P to print the page, and then in the print window that appears, change the Destination to Save as PDF or choose Adobe PDF as the printer.


1 Answers

Try using this code. It works for me. Change "template_testing.html" for your template and add your data to render on "data = {}"

views.py:

import os
from django.conf import settings
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
import datetime
from xhtml2pdf import pisa 


def generate_PDF(request):
    data = {}

    template = get_template('template_testing.html')
    html  = template.render(Context(data))

    file = open('test.pdf', "w+b")
    pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file,
            encoding='utf-8')

    file.seek(0)
    pdf = file.read()
    file.close()            
    return HttpResponse(pdf, 'application/pdf')
like image 64
Marcos Aguayo Avatar answered Sep 20 '22 14:09

Marcos Aguayo