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

使用Python为已有PDF添加页眉时遇报错问题求助

解决PyPDF2添加页眉时的两类错误

错误1:AttributeError: module 'PyPDF2' has no attribute 'pdf'

这个错误是因为错误引用了不存在的PyPDF2.pdf子模块。PyPDF2的核心类(如PdfReader、PdfWriter)直接在顶层模块下,不需要额外的pdf子模块。

错误示例(导致该报错)

from PyPDF2 import pdf  # 错误:PyPDF2没有pdf子模块

正确导入方式

from PyPDF2 import PdfReader, PdfWriter
from PyPDF2.generic import AnnotationBuilder

错误2:TypeError: 'decimal.Decimal' object is not callable

这个错误通常是因为把某个返回Decimal类型的属性当成方法调用了(多加了括号())。比如在设置页眉位置、获取页面尺寸时,错误使用了类似page.mediabox.width()的写法,而mediabox.width本身就是一个Decimal值,无需调用。

错误示例(导致该报错)

# 错误:把属性当成方法调用
page_width = page.mediabox.width()

正确写法

# 直接获取属性值,无需调用
page_width = page.mediabox.width

完整可运行的添加页眉代码

下面是给Sample.pdf添加页眉"YasserKhalil"的正确代码:

from PyPDF2 import PdfReader, PdfWriter
from PyPDF2.generic import AnnotationBuilder

def add_header(input_pdf, output_pdf, header_text):
    reader = PdfReader(input_pdf)
    writer = PdfWriter()

    for page in reader.pages:
        # 获取页面宽度,用于计算页眉居中位置
        page_width = page.mediabox.width
        # 页眉位置:距离顶部20单位,水平居中(字号12时,每个字符约占6单位宽度,可按需调整)
        header_x = (page_width - len(header_text) * 6) / 2
        header_y = page.mediabox.top - 20

        # 创建文本注释作为页眉(PyPDF2通过添加注释实现文本添加)
        header_annotation = AnnotationBuilder.free_text(
            (header_x, header_y, header_x + len(header_text)*6, header_y + 12),
            header_text,
            font_size=12,
            font="Helvetica",
            text_color=(0, 0, 0)  # 黑色文本
        )
        page.add_annotation(header_annotation)
        writer.add_page(page)

    # 写入带页眉的新PDF
    with open(output_pdf, "wb") as out_file:
        writer.write(out_file)

# 执行添加页眉操作
add_header("Sample.pdf", "Sample_with_header.pdf", "YasserKhalil")

代码说明

  1. 用PdfReader读取原PDF,PdfWriter生成新PDF文件
  2. 通过AnnotationBuilder.free_text创建文本注释作为页眉,这是PyPDF2添加文本的标准方式
  3. 基于页面宽度计算页眉的水平居中位置,可根据字体大小调整字符宽度系数
  4. 避免了属性调用错误,直接使用mediabox.width和mediabox.top获取页面尺寸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:32:09