Django中CKEditor字段转HTML为PDF时图片无法渲染问题
解决Django中CKEditor图片在HTML转PDF时无法渲染的问题
问题核心
CKEditor的RichTextUploadingField存储的图片多为相对路径(如/media/uploads/xxx.jpg),而PDF生成工具(如wkhtmltopdf、WeasyPrint)无法直接解析相对路径,或是需要完整绝对URL才能加载图片;另外工具配置、媒体文件访问权限也可能导致图片无法渲染。
解决方案
1. 把图片相对路径转为绝对URL
通过自定义模板过滤器批量替换HTML内容里的图片路径:
- 在你的Django应用目录下创建
templatetags/custom_filters.py,写入以下代码:
from django import template from django.conf import settings register = template.Library() @register.filter(name='absolute_img_url') def absolute_img_url(html_content): if not html_content: return html_content # 先在settings.py中配置SITE_URL,比如 SITE_URL = "https://your-domain.com" base_url = settings.SITE_URL.rstrip('/') return html_content.replace('src="/media/', f'src="{base_url}/media/')
- 在模板中加载过滤器并使用:
{% load custom_filters %} {{ question.full_question | absolute_img_url | safe }}
2. 配置PDF生成工具的base_url
如果用WeasyPrint生成PDF,在视图里设置base_url参数,让工具正确解析相对路径:
from django.shortcuts import render_to_string from weasyprint import HTML from django.http import HttpResponse def generate_question_pdf(request): questions = # 你的查询集数据 html_content = render_to_string('your_template.html', {'questions': questions}) # 用request构建绝对路径作为base_url pdf = HTML(string=html_content, base_url=request.build_absolute_uri()).write_pdf() response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="questions.pdf"' return response
如果用wkhtmltopdf,本地开发时需添加允许加载本地文件的参数:
from wkhtmltopdf.views import PDFTemplateResponse def generate_question_pdf(request): questions = # 你的查询集数据 response = PDFTemplateResponse( request=request, template='your_template.html', context={'questions': questions}, filename='questions.pdf', cmd_options={'enable-local-file-access': True}, ) return response
3. 确保媒体文件可访问
- 本地开发:确认Django的
runserver在运行,且settings.py中MEDIA_URL、MEDIA_ROOT配置正确; - 生产环境:通过Nginx/Apache等服务器正确配置媒体文件的静态服务,保证PDF生成工具能通过网络访问到媒体文件的绝对URL。
4. 修复模板中的无效代码
你提供的模板里有一段残缺的图片标签:width="100px" height="80px" alt="">,这会破坏HTML结构,建议直接移除这段无效代码,确保CKEditor生成的<img>标签是完整的(包含src属性)。
内容的提问来源于stack exchange,提问作者mudassar kamal
相关产品推荐
相关产品推荐

