
本文介绍如何利用 pymupdf(fitz)精准定位 pdf 中的图像,将其移除后按指定位置与尺寸重新插入,实现 logo 批量替换与自由缩放,避免 pikepdf 原图尺寸硬绑定的限制。
本文介绍如何利用 pymupdf(fitz)精准定位 pdf 中的图像,将其移除后按指定位置与尺寸重新插入,实现 logo 批量替换与自由缩放,避免 pikepdf 原图尺寸硬绑定的限制。
在自动化处理多份 PDF 文档(如合同、报告、宣传册)时,常需批量替换页眉或封面中的 Logo 图像,并确保新 Logo 按统一尺寸、居中/对齐方式呈现。原始 pikepdf 方案虽能定位并替换图像数据,但受限于直接修改原始图像流对象(raw_image),无法独立控制显示区域(display rectangle)——即图像在页面上的渲染尺寸与位置由其底层 /Width /Height 和所在内容流中的 Do 操作符共同决定,强行修改元数据易导致渲染异常或 PDF 结构损坏。
更可靠、符合 PDF 渲染逻辑的方案是:先提取图像原始字节流,再以“新图像对象 + 自定义矩形框”的方式重新注入页面。PyMuPDF(fitz)原生支持该流程,且提供简洁的红注(redaction)与重绘接口,无需解析底层 COS 对象,安全高效。
以下为完整可运行的批量替换教程:
✅ 核心步骤说明
- 定位目标图像:通过 page.get_images() 获取所有图像的 xref(交叉引用 ID);
- 提取图像数据:用 doc.extract_image(xref) 获得含 image 字节流和元信息的字典;
- 清除旧图像显示区域:用 add_redact_annot() 标记原图像显示范围,再调用 apply_redactions(images=PDF_REDACT_IMAGE_REMOVE) 彻底移除;
- 按需插入新图像:调用 page.insert_image(rect, stream=..., rotate=...),其中 rect = (x0, y0, x1, y1) 精确控制宽高与位置(单位:PDF 用户坐标,1/72 英寸)。
? 完整代码示例(支持批量处理 + 尺寸自定义)
import fitz # pip install PyMuPDF
import os
def replace_logo_in_pdfs(
input_folder: str,
output_folder: str,
replacement_image_path: str,
target_width: float = 200.0, # 新图像宽度(PDF 单位)
target_height: float = 80.0, # 新图像高度(PDF 单位)
align: str = "top-left", # 支持 "top-left", "center", "top-right"
page_index: int = 0 # 默认处理第一页(索引从 0 开始)
):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if not filename.lower().endswith(".pdf"):
continue
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
try:
doc = fitz.open(input_path)
if page_index >= len(doc):
print(f"⚠️ 页面索引 {page_index} 超出 {filename} 总页数,跳过。")
continue
page = doc[page_index]
images = page.get_images()
if not images:
print(f"ℹ️ {filename} 第 {page_index+1} 页无图像,跳过。")
doc.close()
continue
# 取第一个图像(通常为 Logo);如需匹配特定名称/尺寸,可扩展筛选逻辑
xref = images[0][0] # xref 是图像在文档中的唯一标识
img_info = doc.extract_image(xref)
img_bytes = img_info["image"]
# 获取原图像显示区域(用于对齐参考)
old_rects = page.get_image_rects(xref)
if not old_rects:
print(f"⚠️ 无法获取 {filename} 中图像 {xref} 的显示区域,跳过。")
doc.close()
continue
old_rect = old_rects[0]
# 计算新矩形(支持三种对齐方式)
x0, y0, x1, y1 = old_rect # 原始左下角(x0,y0) → 右上角(x1,y1)
new_width, new_height = target_width, target_height
if align == "center":
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
new_rect = fitz.Rect(
cx - new_width / 2,
cy - new_height / 2,
cx + new_width / 2,
cy + new_height / 2
)
elif align == "top-right":
new_rect = fitz.Rect(x1 - new_width, y1 - new_height, x1, y1)
else: # top-left (default)
new_rect = fitz.Rect(x0, y1 - new_height, x0 + new_width, y1)
# 执行移除 → 插入
page.add_redact_annot(old_rect)
page.apply_redactions(images=fitz.PDF_REDACT_IMAGE_REMOVE)
page.insert_image(new_rect, stream=img_bytes)
doc.ez_save(output_path) # ez_save 启用高压缩,减小体积
print(f"✅ 已处理:{filename} → {os.path.basename(output_path)}")
except Exception as e:
print(f"❌ 处理 {filename} 时出错:{e}")
finally:
if 'doc' in locals():
doc.close()
# 使用示例
replace_logo_in_pdfs(
input_folder=r"C:\input_folder",
output_folder=r"C:\output_folder",
replacement_image_path=r"C:\new_logo.png",
target_width=220.0,
target_height=65.0,
align="center"
)
⚠️ 注意事项与最佳实践
- 图像来源一致性:replacement_image_path 应为高分辨率 PNG 或 JPEG;PyMuPDF 会自动适配色彩空间与压缩格式,无需预处理。
- 坐标系理解:PDF 用户坐标系原点在左下角,y1 > y0;insert_image 的 rect 参数必须为 fitz.Rect 对象(非元组)。
- 多图像处理:当前示例仅替换每页首个图像。若需按尺寸、位置或文件名匹配特定图像,可在 images 列表中增加条件过滤(如 if img[2] > 1000 and img[3] > 500:)。
- 性能优化:处理大量文件时,建议添加 fitz.TOOLS.set_small_glyph_heights(True) 并关闭日志输出。
- 兼容性:PyMuPDF 支持 Python 3.8+,Windows/macOS/Linux 全平台;安装命令:pip install --upgrade PyMuPDF。
通过该方法,你不仅能自由设定 Logo 的像素级尺寸与位置,还可轻松集成旋转、透明度(通过 opacity= 参数)等高级效果,真正实现专业级 PDF 图像自动化管理。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











