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

使用FPDF生成PDF报错:Not enough horizontal space to render a single character

问题解决方案

1. 修复Not enough horizontal space to render a single character错误

这个报错的核心是multi_cell的宽度参数设置不合理,导致没有足够的水平空间渲染字符。你可以从这两点排查:

  • 检查FunctionDF1里的pdf.multi_cell调用,确保宽度参数是有效值:
    • 若要占满当前页面可用宽度,直接传0(FPDF默认行为,但要确认页面边距设置正常);
    • 或者明确计算可用宽度:pdf.w - pdf.l_margin - pdf.r_margin(页面总宽度减去左右边距)。
  • 调用FunctionDF1前,重置PDF的x坐标到左边缘,避免之前的内容把光标推到了页面外:
    pdf.set_x(pdf.l_margin)
    

示例修正后的FunctionDF1片段:

def FunctionDF1(self, pdf, patient_data):
    pdf.set_x(pdf.l_margin)
    # 使用页面可用宽度作为multi_cell宽度
    pdf.multi_cell(w=pdf.w - pdf.l_margin - pdf.r_margin, h=10, txt=patient_data, align='L')

2. 生成单个患者PDF的正确流程

不需要用while循环,直接用for循环遍历患者数据集,每个迭代创建独立的PDF实例,写入数据后单独保存:

# 假设patients是你的患者数据集(比如pandas DataFrame或列表)
for idx, patient in patients.iterrows():  # DataFrame用iterrows,列表用enumerate
    # 每个患者创建新的PDF实例
    pdf = FPDF()
    pdf.add_page()
    # 添加手动内容
    pdf.multi_cell(0, 10, "患者信息报告")
    # 调用方法写入当前患者数据
    df_instance = Dataframe1()
    df_instance.FunctionDF1(pdf, patient.to_string())  # 根据实际数据格式调整
    # 按患者标识命名保存
    pdf.output(f"患者_{patient['id']}_报告.pdf")

3. 替代while循环的更优工具

  • pandas.apply(适合DataFrame数据集):直接遍历每一行生成PDF,代码更简洁:
    def generate_pdf(row):
        pdf = FPDF()
        pdf.add_page()
        pdf.multi_cell(0, 10, f"患者姓名: {row['name']}")
        df_instance = Dataframe1()
        df_instance.FunctionDF1(pdf, row.to_string())
        pdf.output(f"患者_{row['id']}_报告.pdf")
    
    patients_df.apply(generate_pdf, axis=1)
    
  • 并行生成(患者数量多时用):用concurrent.futures提升生成速度:
    from concurrent.futures import ThreadPoolExecutor
    
    def generate_pdf(row):
        # 同上的PDF生成逻辑
        pass
    
    with ThreadPoolExecutor(max_workers=4) as executor:
        executor.map(generate_pdf, [row for _, row in patients_df.iterrows()])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:40:37