'Merge two pages into pdf into one page pdf
There's a pdf file of two pages that I need to merge these two pages to be just one page in a new pdf output. Simply the new output pdf should be of one page I have the following code that enables me to do that task but the problem is that the output is the two pages side by side. I need the page to be vertically one page after another inside the same page
from PyPDF2 import PdfFileWriter, PdfFileReader
from PyPDF2.pdf import PageObject
pdf_filenames = ['Sample.pdf']
inputpdf = PdfFileReader(open(pdf_filenames[0], 'rb'), strict=False)
page1 = inputpdf.getPage(0)
page2 = inputpdf.getPage(1)
total_width = page1.mediaBox.upperRight[0] + page2.mediaBox.upperRight[0]
total_height = max([page1.mediaBox.upperRight[1], page2.mediaBox.upperRight[1]])
new_page = PageObject.createBlankPage(None, total_width, total_height)
new_page.mergePage(page1)
new_page.mergeTranslatedPage(page2, page1.mediaBox.lowerRight[0], 0)
output = PdfFileWriter()
output.addPage(new_page)
output.write(open('MergedPDF.pdf', 'wb'))
Solution 1:[1]
I could solve it using the following code, but I welcome any ideas Another point I need, is it possible to control the size of the page before merging?
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.pdf import PageObject
reader = PdfFileReader(open('Sample.pdf','rb'))
page_1 = reader.getPage(0)
page_2 = reader.getPage(1)
translated_page = PageObject.createBlankPage(None, page_1.mediaBox.getWidth(), page_1.mediaBox.getHeight()*2)
translated_page.mergeScaledTranslatedPage(page_1, 1, 0, page_1.mediaBox.getHeight())
translated_page.mergePage(page_2)
writer = PdfFileWriter()
writer.addPage(translated_page)
with open('MergedPDF.pdf', 'wb') as f:
writer.write(f)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | YasserKhalil |
