html2pdf.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from django.conf import settings
  4. from tempfile import NamedTemporaryFile
  5. from xhtml2pdf import pisa
  6. from django.template import loader, Context
  7. # Convert HTML URIs to absolute system paths so xhtml2pdf can access
  8. # those resources
  9. def link_callback(uri, rel):
  10. sUrl = settings.STATIC_URL # Typically /static/
  11. sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/
  12. mUrl = settings.MEDIA_URL # Typically /static/media/
  13. mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/
  14. # convert URIs to absolute system paths
  15. if uri.startswith(mUrl):
  16. path = os.path.join(mRoot, uri.replace(mUrl, ""))
  17. elif uri.startswith(sUrl):
  18. path = os.path.join(sRoot, uri.replace(sUrl, ""))
  19. # make sure that file exists
  20. if not os.path.isfile(path):
  21. raise Exception(
  22. 'media URI must start with %s or %s' % \
  23. (sUrl, mUrl))
  24. return path
  25. def render_as_pdf(template, context):
  26. """
  27. Génére le template donné avec les données du context donné en HTML et le
  28. converti en PDF via le module xhtml2pdf
  29. """
  30. template = loader.get_template(template)
  31. html = template.render(Context(context))
  32. file = NamedTemporaryFile()
  33. pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback)
  34. # Return PDF document through a Django HTTP response
  35. file.seek(0)
  36. pdf = file.read()
  37. file.close()
  38. return pdf