Created
November 18, 2015 20:11
-
-
Save Irapoam/8490aee7518342e843d3 to your computer and use it in GitHub Desktop.
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
# coding: utf-8 | |
import os | |
import StringIO | |
from xhtml2pdf import pisa | |
from xhtml2pdf.pdf import pisaPDF | |
from django.template.loader import render_to_string | |
from django.conf import settings | |
def link_callback(uri, rel): | |
# use short variable names | |
sUrl = settings.STATIC_URL # Typically /static/ | |
sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ | |
mUrl = settings.MEDIA_URL # Typically /static/media/ | |
mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ | |
# convert URIs to absolute system paths | |
if uri.startswith(mUrl): | |
path = os.path.join(mRoot, uri.replace(mUrl, "")) | |
elif uri.startswith(sUrl): | |
path = os.path.join(sRoot, uri.replace(sUrl, "")) | |
# make sure that file exists | |
if not os.path.isfile(path): | |
raise Exception( | |
'media URI must start with %s or %s' % (sUrl, mUrl)) | |
return path | |
class PDF(object): | |
def __init__(self, template, dataset=[]): | |
self.template = template | |
self.dataset = dataset | |
self.pdf_base = pisaPDF() | |
def render(self): | |
for di in self.dataset: | |
page = render_to_string(self.template, di) | |
self.create_page(page) | |
return self.pdf_base | |
def create_page(self, page): | |
data = StringIO.StringIO(page.encode('utf-8')) | |
temp = StringIO.StringIO() | |
pdf = pisa.pisaDocument(data, temp) | |
self.pdf_base.addDocument(pdf) |
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>My Title - {{ pagesize }}</title> | |
</head> | |
<body> | |
Template pdf | |
</body> | |
</html> |
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
from .report import PDF | |
def gerar_pdf(request): | |
name = "nome teste" | |
pdf = PDF('technical_books/template_pdf.html',[{'name': name }]).render() | |
response = HttpResponse(content_type='application/pdf') | |
response['Content-Disposition'] = 'attachment; filename=' + ata.name + '.pdf' | |
response.write(pdf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment