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

如何用Python检测PDF中的二维码?解决AttributeError报错问题

解决PyPDF2提取PDF图片时的AttributeError问题

你遇到的AttributeError: 'PageObject' object has no attribute 'Extract_Image'是因为PyPDF2的PageObject不存在名为Extract_Image()的方法,正确的方法是**extract_images()**(小写开头,复数形式)。

此外,extract_images()返回的是包含图片元数据和图像数据的字典列表,需要通过字典的键来获取实际图像内容,而非直接使用Image.fromarray()。以下是修正后的完整代码:

import PyPDF2
from pyzbar import pyzbar
from PIL import Image

def has_qr_code(pdf_path):
    # 使用with语句自动管理文件资源
    with open(pdf_path, 'rb') as pdf_file:
        pdf_reader = PyPDF2.PdfReader(pdf_file)

        for page in pdf_reader.pages:
            # 调用正确的extract_images()方法
            images = page.extract_images()
            for img_item in images:
                # 从字典中提取图像的模式、尺寸和数据
                img = Image.frombytes(
                    img_item['mode'],
                    img_item['size'],
                    img_item['image']
                )
                decoded = pyzbar.decode(img)
                if decoded:
                    # 打印识别出的二维码内容(可选)
                    print(f"二维码内容: {decoded[0].data.decode('utf-8')}")
                    return True
    
    return False

# 示例调用
pdf_path = r"C:\Users\TestData.PDF"
if has_qr_code(pdf_path):
    print("PDF中存在二维码。")
else:
    print("PDF中未找到二维码。")

额外说明

  • 确保安装的是最新版PyPDF2,旧版本可能存在方法差异,执行pip install --upgrade PyPDF2可更新至最新版。
  • extract_images()仅能提取PDF中的光栅图像(如JPG、PNG格式),若二维码是以矢量图形或文本路径形式绘制的,该方法无法提取,此时可考虑使用pdf2image库将PDF页面转换为图片后再进行二维码识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:32:50