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

如何用Python查找PDF中特定字体所在页码?PyPDF2实现遇问题

查找PDF中特定字体所在页码的修正方案

你的代码存在几个关键问题,导致无法正确识别字体所在页码:

  1. 未检查资源存在性:部分PDF页面可能没有/Resources或/Font节点,直接访问会抛出KeyError。
  2. 错误判断字体名称:fonts.keys()是字体的内部引用名(如/F1),并非实际字体名称,实际名称存储在字体对象的/BaseFont或/FontName字段中。
  3. 未处理嵌套资源:PDF中的XObject(如图片、表单)可能包含独立的字体资源,原代码会漏掉这部分内容。

以下是修正后的代码,解决了上述问题:

import PyPDF2

def check_page_for_font(page, target_font, checked_resources=None):
    if checked_resources is None:
        checked_resources = set()
    
    # 跳过已检查过的资源,避免重复处理
    resources = page.get('/Resources')
    if not resources or id(resources) in checked_resources:
        return False
    checked_resources.add(id(resources))
    
    target_font_lower = target_font.lower()
    has_target = False
    
    # 检查当前页面的字体
    fonts = resources.get('/Font')
    if fonts:
        for font_ref in fonts.values():
            # 解析字体对象,获取实际名称
            font_obj = font_ref.get_object()
            font_name = font_obj.get('/BaseFont') or font_obj.get('/FontName')
            if font_name and target_font_lower in font_name.lower():
                has_target = True
                break
    
    if has_target:
        return True
    
    # 检查XObject中的嵌套资源(如表单、嵌入内容)
    xobjects = resources.get('/XObject')
    if xobjects:
        for xobj_ref in xobjects.values():
            xobj = xobj_ref.get_object()
            if xobj.get('/Subtype') == '/Form':
                if check_page_for_font(xobj, target_font, checked_resources):
                    return True
    
    return has_target

pdf_file_path = "input.pdf"
target_font = "Arial"

pdf = PyPDF2.PdfReader(open(pdf_file_path, "rb"))

for page_idx in range(len(pdf.pages)):
    page = pdf.pages[page_idx]
    if check_page_for_font(page, target_font):
        print(f"字体 {target_font} 出现在第 {page_idx + 1} 页")

代码说明:

  • 资源存在性检查:使用get()方法安全访问资源节点,避免KeyError。
  • 正确提取字体名称:从字体对象的/BaseFont或/FontName字段获取实际名称,再进行匹配。
  • 递归处理嵌套资源:通过递归检查XObject中的Form类型资源,确保不会漏掉嵌入内容中的字体。
  • 避免重复检查:用checked_resources集合记录已处理的资源ID,防止循环引用导致的重复处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:53:21