Reputation: 23
I want to add multiple cropped boxes as new pages in a new pdf file. As result of the below code I get new the right amount of pages but here is the problem. The last page overwrite every single page in the PDF file.
Any suggestion?
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()
Upvotes: 2
Views: 1485
Reputation: 745
You need the copy
module in order to make copies of the page object. There's an explanation 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).
So your code should be like this:
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()
Upvotes: 5