utils.py 908 B

123456789101112131415161718192021222324252627
  1. # textdocs/utils.py
  2. import re
  3. from django.conf import settings
  4. def convert_media_urls_to_file_paths(html_string):
  5. """
  6. Replaces relative media URLs in an HTML string with absolute
  7. file:// paths so that WeasyPrint can read images directly
  8. from the shared filesystem, bypassing HTTP entirely.
  9. Example:
  10. src="/media/tinymce_uploads/image.png"
  11. becomes
  12. src="file:///app/media/tinymce_uploads/image.png"
  13. """
  14. media_url = settings.MEDIA_URL # e.g., '/media/'
  15. media_root = str(settings.MEDIA_ROOT) # e.g., '/app/media'
  16. # This regex finds src attributes that start with MEDIA_URL
  17. # It handles both single and double quotes
  18. pattern = r'(src=["\'])' + re.escape(media_url) + r'(.*?["\'])'
  19. replacement = r'\1file://' + media_root + r'/\2'
  20. converted_html = re.sub(pattern, replacement, html_string)
  21. return converted_html