PyPdf2无法添加多个裁剪的页面

2024-06-28 11:00:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个新的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()

Tags: 文件outputpdfpageopenwrite新页面addpage
1条回答
网友
1楼 · 发布于 2024-06-28 11:00:41

您需要copy模块来复制page对象。有一个解释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()

相关问题 更多 >