使用 PyPDF2 纠正方向信息错误的 PDF 页面

Gus*_*bra 5 python pypdf

我正在尝试将多个 PDF 文档合并为一个。然而,这些文档有不同的来源,其中一些是在计算机中创建的,其中一些是使用不同的扫描仪/软件扫描的。在加入之前,我将它们全部缩放到 A4 尺寸。

我的问题是某些文档显示正常,但当我检查方向时,文档看起来好像已旋转。

例如,对于此处的此文档,它在浏览器和 Acrobat Reader 中显示“正常”,但如果我使用 PyPDF2 获取信息:

from PyPDF2 import PdfReader

reader = PdfReader(path)
for page in reader.pages:
    orientation = page.get('/Rotate')
    print(f"Document: {path}")
    print(f"    Orientation: {orientation}")
    print(f"    mediabox:    {page.mediabox}")
    print(f"    artbox:      {page.artbox}")
    print(f"    bleedbox:    {page.bleedbox}")
    print(f"    cropbox:     {page.cropbox}")
    print(f"    trimbox:     {page.trimbox}")
Run Code Online (Sandbox Code Playgroud)

我得到:

        Orientation: 90
        mediaBox:    RectangleObject([0, 0, 792, 542])
        artBox:      RectangleObject([0, 0, 792, 542])
        bleedBox:    RectangleObject([0, 0, 792, 542])
        cropBox:     RectangleObject([0, 0, 792, 542])
        trimBox:     RectangleObject([0, 0, 792, 542])
Run Code Online (Sandbox Code Playgroud)

这很烦人,因为在后续步骤中,我向文档添加页码,但由于方向,它们都被放置错误。

请注意,页面显示正确,只是它们仅具有错误的方向数据。如果我尝试设置旋转页面的方向,例如

        Orientation: 90
        mediaBox:    RectangleObject([0, 0, 792, 542])
        artBox:      RectangleObject([0, 0, 792, 542])
        bleedBox:    RectangleObject([0, 0, 792, 542])
        cropBox:     RectangleObject([0, 0, 792, 542])
        trimBox:     RectangleObject([0, 0, 792, 542])
Run Code Online (Sandbox Code Playgroud)

然后它们会横向显示。

如何纠正方向?

Mar*_*oma 0

有两种方法可以更改页面的方向。我不太明白为什么你希望/Rotate该属性为零;它不会告诉您正确的方向是什么,而是在向用户显示内容之前对该页面的内容应用旋转。

属性/Rotate

from PyPDF2 import PdfReader, PdfWriter
from PyPDF2.generic import NameObject, NumberObject

# Add stuff to the PdfWriter
reader = PdfReader("example.pdf")
writer = PdfWriter()
writer.add_page(reader.pages[0])

# Change it in the writer
writer.pages[0][NameObject("/Rotate")] = NumberObject(90)
# Or simpler: writer.rotate(90)

# Write content back
with open("output.pdf", "wb") as fp:
    writer.write(fp)
Run Code Online (Sandbox Code Playgroud)

使用变换矩阵

使用PyPDF2 文档进行转换

from PyPDF2 import PdfReader, PdfWriter, Transformation
from PyPDF2.generic import NameObject, NumberObject

# Add stuff to the PdfWriter
reader = PdfReader("example.pdf")
writer = PdfWriter()
writer.add_page(reader.pages[0])

# Change it in the writer
transformation = Transformation().rotate(90) 
# you need to add .translate(tx=123, tx=456)
# as the coordinate system typically has it's origin in the bottom-left corner
writer.pages[0].add_transformation(transformation)


# Or simpler: writer.rotate(90)

# Write content back
with open("output.pdf", "wb") as fp:
    writer.write(fp)
Run Code Online (Sandbox Code Playgroud)