如何使用 Python 旋转 PDF 页面
在实际的文档处理场景中,PDF 页面方向不正确是一个非常常见的问题,例如扫描文件方向颠倒、合并文档后页面方向混乱等。借助 Python,我们可以通过代码实现对 PDF 页面旋转角度的精确控制,并支持读取当前旋转状态和批量操作。 本文使用的方法需要用到 Free Spire.PDF for Python,可通过 pip 安装: 本文将介绍: 在 Spire.PDF 中,每个页面都对应一个 需要注意的是: 下面的示例演示了如何旋转 PDF 中的某一页,并对参数进行合理校验: 该方法适用于明确知道目标角度的场景,例如“统一将第 1 页旋转为 90°”。 以下是旋转效果预览: 在实际应用中,我们往往需要先判断页面当前方向,再决定是否旋转或如何旋转。 这种方式非常适合用于: 如果直接设置 这种写法的优势在于: 当需要对整份文档进行统一处理时,可以直接遍历 如果需要只旋转方向不正确的页面,可以结合 通过 Spire.PDF for Python,PDF 页面旋转已经不再是复杂操作。 在自动化文档处理、扫描文件修正、企业级 PDF 流程中,这类能力往往是不可或缺的基础组件。pip install spire.pdf。一、PDF 页面旋转的基本原理
PdfPageBase 对象,其 Rotation 属性用于描述页面的旋转状态。
该属性的类型为 PdfPageRotateAngle 枚举,内部以整数值表示当前旋转方向:Rotation.value 实际角度 0 0°(无旋转) 1 90° 2 180° 3 270° Rotation.value 可安全转换为 int 用于逻辑判断二、旋转指定页面(基础示例)
from spire.pdf.common import *
from spire.pdf import *
def rotate_pdf_page(input_pdf_path, output_pdf_path, page_index, rotation_angle):
"""
旋转PDF文档中指定页面。
Args:
input_pdf_path (str): 输入PDF路径
output_pdf_path (str): 输出PDF路径
page_index (int): 页面索引(从0开始)
rotation_angle (int): 旋转角度(90 / 180 / 270)
"""
document = PdfDocument()
try:
document.LoadFromFile(input_pdf_path)
if page_index < 0 or page_index >= document.Pages.Count:
raise IndexError("页面索引超出范围")
page = document.Pages[page_index]
if rotation_angle == 90:
page.Rotation = PdfPageRotateAngle.RotateAngle90
elif rotation_angle == 180:
page.Rotation = PdfPageRotateAngle.RotateAngle180
elif rotation_angle == 270:
page.Rotation = PdfPageRotateAngle.RotateAngle270
else:
raise ValueError("仅支持 90、180、270 度旋转")
document.SaveToFile(output_pdf_path)
finally:
document.Close()
三、获取 PDF 页面当前的旋转角度
page = document.Pages[0]
current_rotation = page.Rotation.value
print(f"当前页面旋转状态:{current_rotation}")current_rotation 的返回值为 0~3 的整数,对应关系如下:rotation_map = {
0: 0,
1: 90,
2: 180,
3: 270
}
print(f"当前角度为 {rotation_map[current_rotation]}°")四、在原有角度基础上进行增量旋转
page.Rotation,原有旋转状态会被覆盖。
若希望在当前角度基础上再旋转 90°,可以采用如下方式:current_value = page.Rotation.Value
new_value = (current_value + 1) % 4
rotation_enum_map = {
0: PdfPageRotateAngle.RotateAngle0,
1: PdfPageRotateAngle.RotateAngle90,
2: PdfPageRotateAngle.RotateAngle180,
3: PdfPageRotateAngle.RotateAngle270,
}
page.Rotation = rotation_enum_map[new_value]五、批量旋转 PDF 中的所有页面
Pages 集合:def rotate_all_pages(input_pdf_path, output_pdf_path, rotation_angle):
document = PdfDocument()
try:
document.LoadFromFile(input_pdf_path)
for i in range(document.Pages.Count):
page = document.Pages[i]
if rotation_angle == 90:
page.Rotation = PdfPageRotateAngle.RotateAngle90
elif rotation_angle == 180:
page.Rotation = PdfPageRotateAngle.RotateAngle180
elif rotation_angle == 270:
page.Rotation = PdfPageRotateAngle.RotateAngle270
document.SaveToFile(output_pdf_path)
finally:
document.Close()Rotation.Value 进行条件判断,从而避免不必要的修改。六、常见注意事项与实践建议
第 1 页的索引为 0,这一点在批量处理时尤其容易忽略。
旋转的是页面显示方向,而非重新排版内容。
很多扫描 PDF 天生就带有旋转信息。
避免在循环中频繁调用 SaveToFile,提升性能。结语
无论是简单的单页方向修正,还是基于当前角度的智能批量处理,都可以通过 page.Rotation 与 Rotation.Value 实现精细控制。