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

如何用Python测量PDF文本行左边距并判断对齐方式?

用Python获取PDF文本行左边距并判断对齐方式

可以用**PyMuPDF(fitz)**实现需求,它能精准获取PDF中每个文本元素的位置坐标,完全满足你对左边距提取和对齐判断的要求。以下是具体实现思路和代码:

核心原理

PDF里的每一行文本都有对应的边界框(bounding box),其中x0属性就是文本行左边缘到页面左边界的距离(单位为点pt,可转换为CSS像素:1pt ≈ 1.333px)。你提到的三种固定左边距,对应三个不同的x0值,直接依据这个值就能判断对齐方式。

实现步骤

  1. 安装依赖
pip install pymupdf
  1. 编写解析代码
import fitz

def analyze_pdf_alignment(pdf_path):
    doc = fitz.open(pdf_path)
    margin_left_values = []
    line_results = []

    for page in doc:
        # 提取每个单词的位置信息
        text_blocks = page.get_text("words")
        # 按y坐标分组,拼接成完整行
        lines = {}
        for word in text_blocks:
            x0, y0, x1, y1, text, _, _, _ = word
            # 用y0的整数作为行标识,规避微小坐标误差
            line_key = int(y0 // 1)
            if line_key not in lines:
                lines[line_key] = {"x0": x0, "text": text}
            else:
                lines[line_key]["text"] += " " + text
                # 取整行最左侧的x0作为左边距
                if x0 < lines[line_key]["x0"]:
                    lines[line_key]["x0"] = x0

        # 收集当前页所有行的信息
        for line in lines.values():
            margin_left = line["x0"]
            margin_left_values.append(margin_left)
            line_results.append({
                "text": line["text"],
                "margin_left_pt": margin_left,
                "margin_left_px": round(margin_left * 1.333, 2)
            })

    doc.close()

    # 提取去重后的固定边距值,按从小到大排序
    unique_margins = sorted(list(set([round(m, 1) for m in margin_left_values])))
    # 映射对齐规则:最小对应左对齐,中间对应居中,最大对应右对齐
    alignment_map = {
        unique_margins[0]: "left-aligned",
        unique_margins[1]: "center-aligned",
        unique_margins[2]: "right-aligned"
    }

    # 给每行添加对齐结果
    for res in line_results:
        rounded_margin = round(res["margin_left_pt"], 1)
        res["alignment"] = alignment_map.get(rounded_margin, "unknown")

    return line_results

# 调用示例
results = analyze_pdf_alignment("your_document.pdf")
for res in results:
    print(f"文本: {res['text']} | 左边距(px): {res['margin_left_px']} | 对齐方式: {res['alignment']}")

关键说明

  • 代码通过提取单词位置再按行拼接,确保拿到整行的真实左边距(取行内最左侧单词的x0),避免单行文本被拆分导致的位置偏差。
  • 对x0做四舍五入处理,规避PDF渲染时的微小坐标误差,保证相同边距的行被归为同一组。
  • 单位转换遵循CSS标准:1pt = 96/72 ≈ 1.333px,直接输出你需要的像素单位。
  • 自动统计所有行的边距值并映射对齐方式,无需提前知晓x和y的具体数值,适配你提到的固定边距场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:05:22