PyPdf2 无法添加多个裁剪页面

PyPdf2 cant add multiple cropped pages

我想在新的 pdf 文件中添加多个裁剪框作为新页面。作为以下代码的结果,我得到了正确数量的新页面,但这是问题所在。最后一页覆盖 PDF 文件中的每一页。

有什么建议吗?

from PyPDF2 import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input1 = PdfFileReader(open("1.pdf", "rb"))
outputStream = open("output.pdf", "wb")

page = input1.getPage(0)

page.mediaBox.lowerRight = (205+(0*185), 612)
page.mediaBox.upperLeft = (20+(0*185), 752)
output.addPage(page)
output.write(outputStream)

page.mediaBox.lowerRight = (205+(1*185), 612)
page.mediaBox.upperLeft = (20+(1*185), 752)
output.addPage(page)
output.write(outputStream)

page.mediaBox.lowerRight = (205+(2*185), 612)
page.mediaBox.upperLeft = (20+(2*185), 752)
output.addPage(page)
output.write(outputStream)


outputStream.close()

您需要 copy 模块才能复制页面对象。有一个解释 in the docs:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

所以你的代码应该是这样的:

from PyPDF2 import PdfFileWriter, PdfFileReader
from copy import copy

output = PdfFileWriter()
input1 = PdfFileReader(open("1.pdf", "rb"))
outputStream = open("output.pdf", "wb")

page = input1.getPage(0)

x = copy(page)
y = copy(page)
z = copy(page)

x.mediaBox.lowerRight = (205 + (0 * 185), 612)
x.mediaBox.upperLeft = (20 + (0 * 185), 752)
output.addPage(x)

y.mediaBox.lowerRight = (205 + (1 * 185), 612)
y.mediaBox.upperLeft = (20 + (1 * 185), 752)
output.addPage(y)

z.mediaBox.lowerRight = (205 + (2 * 185), 612)
z.mediaBox.upperLeft = (20 + (2 * 185), 752)
output.addPage(z)

output.write(outputStream)
outputStream.close()