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