You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用xhtml2pdf模板生成PDF时遇ValueError问题求助

解决xhtml2pdf生成PDF时的ValueError问题

问题详情

  • 触发场景:使用Django结合xhtml2pdf和模板生成PDF时,后台管理界面显示正常,但生成PDF时抛出ValueError
  • 错误信息:

ValueError at /multas/ <PmlTable@0x1F3B48B4320 2 rows x 1 cols> with cell(0,0) containing <PmlKeepInFrame at 0x1f3b48b4680> size=x data error - 2 rows in data but 1 row heights

  • 环境参数:
    • Django版本:3.2
    • Python版本:3.12.2
    • 异常位置:C:\Users\user\PycharmProjects\simertg\venv\Lib\site-packages\reportlab\platypus\tables.py第319行

解决方向

1. 修复模板表格结构

错误根源是ReportLab处理表格时行高数据与实际行数不匹配,xhtml2pdf将HTML表格转为PmlTable后,单元格内的图片被KeepInFrame包裹导致行高计算异常。

  • 检查模板中表格是否存在嵌套结构,或单元格内图片是否触发行拆分但行高数据未同步
  • 为表格行或图片添加明确高度样式,例如给<img>设置height属性,或给<tr>设置固定高度:
    <tr style="height: 150px;">
      <td><img src="{{ object.image.url }}" height="140" /></td>
    </tr>
    

2. 调整xhtml2pdf渲染配置

禁用自动KeepInFrame处理,避免内容包裹逻辑干扰表格行高计算:

from xhtml2pdf import pisa
from django.http import HttpResponse, BytesIO
from django.template.loader import get_template
from django.shortcuts import get_object_or_404
from .models import YourModel

def generate_pdf(request, id):
    template = get_template('pdf_template.html')
    context = {'object': get_object_or_404(YourModel, id=id)}
    html_content = template.render(context)
    
    result = BytesIO()
    # 生成PDF时关闭自动KeepInFrame逻辑
    pdf = pisa.pisaDocument(
        BytesIO(html_content.encode('UTF-8')),
        result,
        encoding='UTF-8',
        default_css=True
    )
    
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('PDF生成失败', status=500)

3. 降级ReportLab版本

Python 3.12.2较新,与Django 3.2、新版本ReportLab可能存在兼容性问题,降级到3.6.x版本可解决多数适配问题:

pip install reportlab==3.6.12

4. 修正图片嵌入方式

确保图片路径可被xhtml2pdf正确解析:

  • 使用绝对路径或Base64编码嵌入图片,避免相对路径导致的渲染异常
  • 模板中使用模型图片的完整URL:
    <img src="{{ object.image.url }}" alt="上传图片" />
    

内容的提问来源于stack exchange,提问作者Johnny Urdin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 03:15:14