下面示例代码,是将横向纸张旋转为纵向(根据纸张大小判断纸张方向)
from PyPDF2 import PdfFileWriter, PdfFileReader
def page_rotation(old_file, new_file):
"""
PDF页面旋转
:param old_file: 需要旋转的PDF文件
:param new_file: 旋转后的PDF文件
:return:
"""
pdf = PdfFileReader(old_file)
page_num = pdf.getNumPages()
pdf_writer = PdfFileWriter()
for i in range(page_num):
# orientation = pdf.getPage(i).get(\'/Rotate\') # 获取页面的旋转角度
size = pdf.getPage(i).mediaBox # 获取页面大小值(长、宽)
x, y = size.getUpperRight_x(), size.getUpperRight_y()
if x > y:
# 顺时针旋转90度 90的倍数
page = pdf.getPage(i).rotateClockwise(90)
# 逆时针旋转90度 90的倍数
# page = pdf.getPage(i).rotateCounterClockwise(90)
pdf_writer.addPage(page)
else:
# 不旋转
page = pdf.getPage(i).rotateClockwise(0)
pdf_writer.addPage(page)
with open(new_file, \'wb\') as f:
pdf_writer.write(f)