html2pdf.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import re
  4. from django.conf import settings
  5. from tempfile import NamedTemporaryFile
  6. from xhtml2pdf import pisa
  7. from django.template import loader, Context
  8. def link_callback(uri, rel):
  9. """
  10. # Convert HTML URIs to absolute system paths so xhtml2pdf can access
  11. # those resources
  12. """
  13. sUrl = settings.STATIC_URL # Typically /static/
  14. sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/
  15. mUrl = settings.MEDIA_URL # Typically /static/media/
  16. mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/
  17. projectDir = settings.PROJECT_PATH # Typically /home/userX/project/
  18. # convert URIs to absolute system paths
  19. if uri.startswith(mUrl):
  20. path = os.path.join(mRoot, uri.replace(mUrl, ""))
  21. elif uri.startswith(sUrl):
  22. path = os.path.join(sRoot, uri.replace(sUrl, ""))
  23. # If file doesn't exist try to find it in app static folder
  24. # This case occur in developpement env
  25. if not os.path.isfile(path):
  26. app_search = re.search(r'^(%s|%s)(.*)/.*' % (sUrl, mUrl), uri)
  27. app = app_search.group(2)
  28. path = os.path.join(projectDir, app, uri[1:])
  29. # make sure that file exists
  30. if not os.path.isfile(path):
  31. raise Exception(
  32. 'media URI must start with %s or %s' %
  33. (sUrl, mUrl))
  34. return path
  35. def render_as_pdf(template, context):
  36. """
  37. Génére le template indiqué avec les données du context en HTML et le
  38. converti en PDF via le module xhtml2pdf
  39. """
  40. template = loader.get_template(template)
  41. html = template.render(Context(context))
  42. file = NamedTemporaryFile()
  43. pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback)
  44. file.seek(0)
  45. pdf = file.read()
  46. file.close()
  47. return pdf