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

如何在PyPDF2中将印章图片居中添加到PDF页面

在PDF每页中心添加印章(PyPDF2 + Flask)

原代码通过merge_page直接合并印章PDF页,导致印章默认锚定在内容页左下角。ChatGPT修改image_page.mediabox的方案无效,因为该操作仅改变印章页自身的边界范围,而非调整其在内容页上的绘制位置。以下是可行的实现方案:

核心实现思路

  1. 计算内容页与印章页的尺寸差值,得出中心偏移量
  2. 使用PyPDF2提供的平移合并方法,将印章页精准定位到内容页中心
  3. 修正响应返回逻辑,避免二进制文件编码损坏

修正后的完整路由代码

from flask import Flask, request, jsonify, make_response, after_this_request
from flask_cors import cross_origin
from PyPDF2 import PdfReader, PdfWriter
import io

@app.route('/stamp', methods=['POST'])
@cross_origin()
def add_stamp():
    try:
        content_file = request.files.get('contentFile')
        image_file = request.files.get('imageFile')

        if content_file and image_file:
            print('Content File:', content_file.filename)
            print('Image File:', image_file.filename)
        else:
            print('Files not received correctly')
            return jsonify({"error": "Files not received correctly"}), 400
        
        # 读取印章PDF(假设印章为单页PDF)
        stamp_reader = PdfReader(image_file.stream)
        stamp_page = stamp_reader.pages[0]
        stamp_width = stamp_page.mediabox.width
        stamp_height = stamp_page.mediabox.height

        writer = PdfWriter()
        content_reader = PdfReader(content_file.stream)

        for content_page in content_reader.pages:
            # 获取内容页尺寸
            content_mediabox = content_page.mediabox
            content_width = content_mediabox.width
            content_height = content_mediabox.height

            # 计算中心偏移量:内容页中心坐标 - 印章页中心坐标
            offset_x = (content_width - stamp_width) / 2
            offset_y = (content_height - stamp_height) / 2

            # 使用merge_translated_page平移并合并印章页(PyPDF2 2.0+ 支持)
            content_page.merge_translated_page(stamp_page, offset_x, offset_y)

            writer.add_page(content_page)
        
        stamp_output = io.BytesIO()
        writer.write(stamp_output)
        stamp_output.seek(0)

        @after_this_request
        def cleanup(response):
            stamp_output.close()
            return response

        # 直接返回二进制流,避免编码损坏
        response = make_response(stamp_output.getvalue())
        response.headers['Content-Type'] = 'application/octet-stream'
        response.headers['Content-Disposition'] = 'attachment; filename=stamped.pdf'
        return response

    except Exception as e:
        print(f"Error: {e}")
        return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500

关键修改说明

  • 替换合并方法:用merge_translated_page替代merge_page,该方法支持传入x、y偏移量,直接将印章页平移到目标位置,是PyPDF2官方推荐的位置调整方案。
  • 修正响应逻辑:原代码用jsonify将二进制数据转成latin1字符串返回,易导致文件损坏。改用make_response直接返回二进制流,并设置Content-Disposition头,方便前端识别下载。
  • 简化循环逻辑:直接遍历content_reader.pages,无需手动生成索引列表。

兼容旧版PyPDF2(<2.0)的方案

若使用不支持merge_translated_page的旧版本,可通过添加页面变换实现:

from PyPDF2.generic import Transformation

# 替换循环内的merge_translated_page代码块
transformation = Transformation().translate(tx=offset_x, ty=offset_y)
stamp_page.add_transformation(transformation)
content_page.merge_page(stamp_page)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 15:42:50