# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import re from xhtml2pdf import pisa from tempfile import NamedTemporaryFile from django.conf import settings from django.template import loader, Context from django.core.files import File def link_callback(uri, rel): """ # Convert HTML URIs to absolute system paths so xhtml2pdf can access # those resources """ 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/ projectDir = settings.PROJECT_PATH # Typically /home/userX/project/ # 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, "")) else: return uri # handle the absolute URIs # If file doesn't exist try to find it in app static folder # This case occur in developpement env if not os.path.isfile(path): app_search = re.search(r'^(%s|%s)(.*)/.*' % (sUrl, mUrl), uri) app = app_search.group(2) path = os.path.join(projectDir, app, uri[1:]) # 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 def render_as_pdf(template, context): """ Génére le template indiqué avec les données du context en HTML et le converti en PDF via le module xhtml2pdf. Renvoi un objet de type File """ template = loader.get_template(template) html = template.render(Context(context)) file = NamedTemporaryFile() pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback) file.flush() return File(open(file.name))