使用PyPDF2批量为文件夹内PDF首页单独加盖印章的实现咨询
批量PDF首页盖章解决方案
实现功能
- 自动遍历指定文件夹内所有PDF文件,仅对每份PDF的首页加盖印章,不会合并多份PDF
- 支持直接覆盖原文件,也可选择生成新的盖章文件
- 可自定义印章放置的任意位置
- 支持在印章上方叠加自定义文字,可调整文字样式、位置
可调参数说明
你可以根据需求修改代码开头的配置项:
TARGET_FOLDER:存放待处理PDF的文件夹路径STAMP_PATH:你的stamp.pdf印章文件路径OVERWRITE_ORIGIN:设为True则直接覆盖原PDF,设为False则生成带_stamped后缀的新文件STAMP_POS:印章的左下角坐标,单位为点(1点=1/72英寸),第一个值为水平偏移(越大越靠右),第二个值为垂直偏移(越大越靠上)TEXT_CONFIG:叠加文字的配置,可修改文字内容、位置、字体大小、RGB颜色(取值0-1)
完整代码
import os import PyPDF2 import io from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from PyPDF2 import PdfFileReader, PdfFileWriter # -------------------------- 可修改配置项 -------------------------- TARGET_FOLDER = r'C:\User\Example_User\Desktop\待处理PDF文件夹' STAMP_PATH = r'C:\User\Example_User\Desktop\stamp.pdf' OVERWRITE_ORIGIN = True # 是否覆盖原文件 STAMP_POS = (50, 50) # 印章左下角坐标 (x, y),单位点 # 叠加文字配置 TEXT_CONFIG = { "content": "已审核", # 文字内容 "pos": (70, 120), # 文字左下角坐标 "font_size": 16, # 字体大小 "color": (1, 0, 0) # RGB颜色,红(1,0,0)、黑(0,0,0) } # ------------------------------------------------------------------- # 预加载印章PDF with open(STAMP_PATH, "rb") as f: stamp_reader = PdfFileReader(f) stamp_page = stamp_reader.getPage(0) stamp_width = float(stamp_page.mediaBox.getWidth()) stamp_height = float(stamp_page.mediaBox.getHeight()) # 遍历目标文件夹所有PDF for filename in os.listdir(TARGET_FOLDER): if not filename.lower().endswith(".pdf") or filename == os.path.basename(STAMP_PATH): continue file_path = os.path.join(TARGET_FOLDER, filename) temp_output = file_path + ".tmp" if OVERWRITE_ORIGIN else file_path.replace(".pdf", "_stamped.pdf") try: with open(file_path, "rb") as input_f: pdf_reader = PdfFileReader(input_f) pdf_writer = PdfFileWriter() # 处理首页 first_page = pdf_reader.getPage(0) page_width = float(first_page.mediaBox.getWidth()) page_height = float(first_page.mediaBox.getHeight()) # 生成临时画布,放置印章和文字 packet = io.BytesIO() can = canvas.Canvas(packet, pagesize=(page_width, page_height)) # 绘制印章到指定位置 can.drawPage(STAMP_PATH, 1, STAMP_POS[0], STAMP_POS[1], width=stamp_width, height=stamp_height) # 叠加文字 can.setFont("Helvetica", TEXT_CONFIG["font_size"]) can.setFillColorRGB(*TEXT_CONFIG["color"]) can.drawString(*TEXT_CONFIG["pos"], TEXT_CONFIG["content"]) can.save() packet.seek(0) overlay_reader = PdfFileReader(packet) overlay_page = overlay_reader.getPage(0) # 合并图层到首页 first_page.mergePage(overlay_page) pdf_writer.addPage(first_page) # 添加剩余页面 for page_num in range(1, pdf_reader.getNumPages()): pdf_writer.addPage(pdf_reader.getPage(page_num)) # 输出文件 with open(temp_output, "wb") as output_f: pdf_writer.write(output_f) # 覆盖原文件 if OVERWRITE_ORIGIN: os.replace(temp_output, file_path) print(f"处理完成:{filename}") except Exception as e: print(f"处理失败 {filename}:{str(e)}") if os.path.exists(temp_output): os.remove(temp_output)
注意事项
- 处理前建议先备份重要PDF文件,避免覆盖后无法找回
- 如果需要调整印章大小,可修改
drawPage方法里的width和height参数 - 如需使用中文字体,可将
can.setFont的第一个参数替换为你系统内的中文字体名称或路径
内容的提问来源于stack exchange,提问作者Colton Hunter
相关产品推荐
相关产品推荐

