一、实现代码
import PyPDF2
from PyPDF2 import PdfWriter
from PyPDF2.generic import AnnotationBuilder
# 指定输入和输出pdf
pdf_path = r'C:\Users\ASUS\Desktop\temp\xxxx.pdf'
out_path = r'C:\Users\ASUS\Desktop\temp\xxxx2.pdf'
# 创建 PdfWriter 对象
writer = PdfWriter()
with open(pdf_path, 'rb') as pdf_file:
# 创建 PdfReader 对象
reader = PyPDF2.PdfReader(pdf_file)
# 获取 PDF 的总页数
num_pages = len(reader.pages)
# 指定页码左下角坐标(x,y)
x = 280
y = 30
# 指定方框的长和宽
a = 40
b = 20
# 逐页添加页码
for page_num in range(num_pages):
# 获取指定页的页面对象
page = reader.pages[page_num]
pagenum = page_num + 1
# 添加当前页到 PdfWriter 对象
writer.add_page(page)
# 添加页码注释
annotation = AnnotationBuilder.free_text(
f" {pagenum}/{num_pages} ",
rect=(x, y, x + a, y + b),
font="宋体",
font_size="10pt"
)
writer.add_annotation(page_number=page_num, annotation=annotation)
# 获取页面内容并打印
print(f"已经成功镶嵌页码:{page_num + 1}")
# 将最终的 PdfWriter 对象写入文件
with open(out_path, "wb") as fp:
writer.write(fp)
print("处理完毕")
二、坐标讲解
# 指定页码左下角坐标(x,y)
x = 280
y = 30
# 指定方框的长和宽
a = 40
b = 20
三、实现效果
处理后的PDF,每页都有页码显示