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

如何用PDFBOX提取Word打印转PDF中的高亮文本及颜色?

提取Word打印到PDF中的高亮文本(含颜色标记)

核心原因说明

Word通过「打印到PDF」生成的文件,其高亮是作为文本背景色嵌入内容流,而非PDF原生的高亮注释(后者是PDF编辑器添加的),所以常规的注释提取工具无法识别,需要读取文本的底层样式属性。

方法一:用PyMuPDF(fitz)直接提取(推荐)

这个Python库可以解析PDF中每个字符的背景色信息,直接输出带颜色标记的文本。

示例代码:

import fitz

def extract_highlighted_text(pdf_path):
    doc = fitz.open(pdf_path)
    output_content = []
    for page in doc:
        # 以字典格式获取页面文本,包含样式信息
        text_dict = page.get_text("dict")
        for block in text_dict["blocks"]:
            if "lines" not in block:
                continue
            for line in block["lines"]:
                for span in line["spans"]:
                    char_text = span["text"]
                    bg_rgb = span["bg"]
                    # 白色背景视为无高亮,跳过标记
                    if bg_rgb == (1.0, 1.0, 1.0):
                        output_content.append(char_text)
                        continue
                    # 将RGB值转换为十六进制颜色码
                    hex_color = "#{:02x}{:02x}{:02x}".format(
                        int(bg_rgb[0] * 255),
                        int(bg_rgb[1] * 255),
                        int(bg_rgb[2] * 255)
                    )
                    # 用颜色码标记高亮文本
                    output_content.append(f"[{hex_color}]{char_text}[/{hex_color}]")
    return "".join(output_content)

# 使用示例
result = extract_highlighted_text("your_target.pdf")
# 可将结果写入文件
with open("highlighted_output.txt", "w", encoding="utf-8") as f:
    f.write(result)

方法二:转回Word后提取(适合非编程用户)

  1. 用Adobe Acrobat Pro打开PDF,选择「导出PDF」→「Microsoft Word」,选择「保留排版」模式导出Word文档(该步骤会还原Word原有的高亮格式)
  2. 在Word中按Alt+F11打开VBA编辑器,插入模块并运行以下脚本:
Sub ExportHighlightedTextWithColor()
    Dim outputPath As String
    outputPath = ThisDocument.Path & "\highlighted_result.txt"
    Open outputPath For Output As #1
    
    Dim rng As Range
    For Each rng In ActiveDocument.StoryRanges
        Do
            With rng.Find
                .Highlight = True
                Do While .Execute
                    ' 转换Word颜色索引为RGB十六进制
                    Dim colorHex As String
                    colorHex = Right("000000" & Hex(rng.HighlightColorIndex), 6)
                    colorHex = "#" & Mid(colorHex, 5, 2) & Mid(colorHex, 3, 2) & Mid(colorHex, 1, 2)
                    Print #1, "[" & colorHex & "]" & rng.Text & "[/" & colorHex & "]"
                Loop
            End With
            Set rng = rng.NextStoryRange
        Loop Until rng Is Nothing
    Next rng
    
    Close #1
    MsgBox "导出完成,文件路径:" & outputPath
End Sub

注意事项

  • 生成PDF时避免选择「最小文件大小」模式,该模式会压缩样式信息,可能导致背景色丢失
  • 若遇到特殊字体或复杂排版的高亮,可调整代码中的颜色阈值(比如允许轻微的白色偏差)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:05:36