html2pdf.py 1.9 KB

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