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

使用pdfminer能否检测下划线?如何通过LTChar判断字符是否带下划线?

Checking Underline on LTChar (Single Characters or Words)

Great question! You absolutely can detect if a single character or word has an underline when working with LTChar objects—you just need to tap into the text decoration attributes stored in the character's text state.

How to Check for Underline on a Single LTChar

LTChar instances (from PyMuPDF/fitz) have a text_state property that holds text decoration flags. Underline is one of these flags, and you can check it using a bitwise operation against the TEXT_DECOR_UNDERLINE constant.

Here's a practical code example to demonstrate:

import fitz  # PyMuPDF

# Open your target PDF document
doc = fitz.open("your_document.pdf")
page = doc[0]

# Iterate through text elements to access LTChar objects
for text_block in page.get_text("raw"):
    if isinstance(text_block, fitz.LTText):
        for text_line in text_block:
            for text_span in text_line:
                for char_obj in text_span:
                    if isinstance(char_obj, fitz.LTChar):
                        # Check if the character has an underline applied
                        has_underline = char_obj.text_state.decorations & fitz.TEXT_DECOR_UNDERLINE
                        if has_underline:
                            print(f"Character '{char_obj.text}' is underlined!")

Checking for Underlined Words

To identify entire underlined words, you have two efficient approaches:

  • Track consecutive characters with the underline flag, grouping them into complete words manually.
  • First check the parent LTSpan object's decorations—underlines are often applied to an entire span (which typically maps to a word or phrase) rather than individual characters. This saves you from checking each character one by one:
for text_block in page.get_text("raw"):
    if isinstance(text_block, fitz.LTText):
        for text_line in text_block:
            for text_span in text_line:
                # Check if the entire span has underline enabled
                if text_span.text_state.decorations & fitz.TEXT_DECOR_UNDERLINE:
                    print(f"Underlined word/phrase: '{text_span.text}'")
                    # Optional: Verify individual characters in the span if needed
                    for char_obj in text_span:
                        if isinstance(char_obj, fitz.LTChar):
                            # Confirm underline status per character
                            pass

Key Notes

  • The decorations property uses bitmask values, so we use the & (bitwise AND) operator to check if the underline flag is active.
  • TEXT_DECOR_UNDERLINE is a built-in constant in PyMuPDF that represents the underline decoration flag.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:40:01