Created
April 28, 2016 12:06
-
-
Save kaajavi/372cf4360b03991d0121702c6b6944e3 to your computer and use it in GitHub Desktop.
Example: View Python for html2pdf library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Genera un listado de alumnos: | |
#imports necesarios: | |
from xhtml2pdf import pisa #INSTALAR ESTA LIBRERIA: xhtml2pdf | |
from django.template.loader import get_template | |
from django.http import HttpResponse | |
from django.template import Context | |
#En el ejemplo, hay una app llamada miappdecursos, importamos los modelos Curso y Alumno | |
from miappdecursos.models import Curso, Alumno | |
def generar_listado_alumnos_pdf(request, id_curso): | |
response = HttpResponse(content_type='application/pdf') | |
try: | |
curso = Curso.objects.get(pk=id_curso) | |
except Curso.DoesNotExist: | |
raise Http404("El curso no existe") | |
response['Content-Disposition'] = 'attachment; filename="listado_%s.pdf"' % (curso) #Nombre del archivo que se descarga | |
alumnos = Alumnos.objects.filter(curso=curso) | |
# Datos para enviar al render del template (via context) | |
data = {'curso':curso, | |
'alumnos':alumnos, | |
} | |
# Buscamos el template y lo procesamos | |
template = get_template('listados/example_html2pdf_4django.html') | |
html = template.render(Context(data)) | |
# Convertimos el html procesado a pdf (libreria pisa) | |
file = open(FILE_LIST, "w+b") | |
pisaStatus = pisa.CreatePDF(html, dest=file, | |
link_callback = link_callback) | |
# Return PDF document through a Django HTTP response | |
file.seek(0) | |
pdf = file.read() | |
file.close() | |
response.write(pdf) | |
#BORRAR EL ARCHIVO | |
if os.path.exists(FILE_LIST): | |
try: | |
os.remove(FILE_LIST) | |
except OSError, e: | |
pass | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment