一、实现代码
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 = 280y = 30# 指定方框的长和宽a = 40b = 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 = 280y = 30# 指定方框的长和宽a = 40b = 20
三、实现效果
处理后的PDF,每页都有页码显示