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

如何使用pypdf围绕中心旋转PDF页面并可选缩放适配原页面?

用pypdf实现PDF页面绕中心任意旋转(支持缩放适配原尺寸)

要实现绕中心旋转任意角度并可选缩放适配原页面,核心是利用pypdf.Transformation构造平移-旋转-平移的组合变换矩阵,同时根据需求计算缩放因子。以下是完整实现方案:

依赖准备

确保安装最新版pypdf:

pip install --upgrade pypdf

完整代码示例

import math
from pypdf import PdfReader, PdfWriter, Transformation

def rotate_page_around_center(input_path, output_path, rotation_angle, fit_to_original=False):
    reader = PdfReader(input_path)
    writer = PdfWriter()
    
    for page in reader.pages:
        # 获取原页面尺寸与中心坐标
        page_width = float(page.mediabox.width)
        page_height = float(page.mediabox.height)
        cx, cy = page_width / 2, page_height / 2
        
        # 角度转弧度(用于计算缩放因子)
        theta = math.radians(rotation_angle)
        cos_theta = math.cos(theta)
        sin_theta = math.sin(theta)
        
        # 构造变换链:平移到原点 → 旋转 → (可选缩放)→ 平移回原中心
        transform = Transformation().translate(-cx, -cy)
        transform = transform.rotate(rotation_angle)
        
        if fit_to_original:
            # 计算旋转后外接矩形的尺寸
            rotated_width = page_width * abs(cos_theta) + page_height * abs(sin_theta)
            rotated_height = page_width * abs(sin_theta) + page_height * abs(cos_theta)
            # 取最小缩放因子,确保内容完全适配原页面
            scale_factor = min(page_width / rotated_width, page_height / rotated_height)
            transform = transform.scale(scale_factor)
        
        transform = transform.translate(cx, cy)
        
        # 应用变换并添加到输出文档
        page.add_transformation(transform)
        writer.add_page(page)
    
    with open(output_path, "wb") as out_file:
        writer.write(out_file)

# 使用示例
# 旋转15度,保留原内容尺寸(可能超出原页面边界)
rotate_page_around_center("input.pdf", "output_rotated.pdf", 15, fit_to_original=False)
# 旋转15度,缩放适配原页面边界
rotate_page_around_center("input.pdf", "output_rotated_fit.pdf", 15, fit_to_original=True)

关键逻辑说明

  • 绕中心旋转原理:pypdf默认旋转以页面左下角为原点,因此先通过平移将页面中心移到原点,旋转完成后再平移回原中心位置,实现绕中心旋转的效果。
  • 缩放适配逻辑:非90度倍数旋转后,内容的外接矩形会超出原页面尺寸,通过计算外接矩形与原页面的比例,取最小缩放因子,确保旋转后的内容完全被原页面边界容纳。
  • 变换顺序:Transformation的链式调用按从左到右顺序执行变换,必须严格遵循「平移→旋转→缩放→平移」的顺序才能得到正确效果。

注意事项

  • 旋转角度支持正负值:正值为顺时针旋转,负值为逆时针旋转。
  • 若输入PDF存在加密或损坏,需先解密或修复后再处理。
  • 代码支持批量处理多页PDF,所有页面会按统一参数旋转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 19:32:49