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

使用borb库生成PDF遇ImportError:无法导入Run类求解决方案

borb库Run类导入错误修复方案

Run类没被废弃,只是导入路径变了

你遇到的ImportError是因为Run类的正确导入路径不是borb.pdf,而是borb.pdf.text.run。你代码里注释的导入语句才是对的,官方只是调整了模块结构,并没有废弃这个类。

具体修复步骤

  1. 修正导入语句:将from borb.pdf import Run替换为from borb.pdf.text.run import Run
  2. 优化排版逻辑(可选):你原来的代码会给每个文本段新建一页,这通常不是预期效果,建议把所有段落放在同一页里,避免页面浪费。

修正后的完整代码

from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import Paragraph
from borb.pdf.text.run import Run  # 正确的导入路径

pdf_text = """
Long text here
divided in various sections
another sample section
final section content
"""

# 创建PDF文档
document = Document()
# 只创建一个页面,所有段落都添加到这个页面
page = Page()
document.add(page)

# 分割文本为多个段落
sections = pdf_text.split("\n\n")

# 遍历段落并添加到PDF
for section in sections:
    # 跳过空的段落(避免生成空白内容)
    if section.strip():
        paragraph = Paragraph()
        runs = [Run(text=section)]
        paragraph.add(*runs)
        page.add(paragraph)

# 保存PDF文件
document.save("updated.pdf")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:32:38