'How to stitch 2 PDF pages into one page and repeat for multiple page sets

I have written some code to stitch two PDF pages into one page (shown below), however the code relies on manually writing in the input files each time you want to merge two pages.

Ideally, I'd like the code to identify all PDFs in the working directory and then stitch together the PDFs in pairs. So '0_page_1.pdf' and '0_page_2.pdf' will be stitched together, then '0_page_3.pdf' and '0_page_4.pdf' will be stitched together, and so on until all PDFs have been stitched together.

from PyPDF3 import PdfFileWriter, PdfFileReader
from PyPDF3.pdf import PageObject

pdf_filenames = [r'C:\Users\AL15785\lpthw\0_page_1.pdf', r'C:\Users\AL15785\lpthw\0_page_2.pdf']

input1 = PdfFileReader(open(pdf_filenames[0], "rb"), strict=False)
input2 = PdfFileReader(open(pdf_filenames[1], "rb"), strict=False)

page1 = input1.getPage(0)
page2 = input2.getPage(0)

total_width = page1.mediaBox.upperRight[0]
total_height = page1.mediaBox.upperRight[1]

new_page = PageObject.createBlankPage(None, total_width, total_height)

# Add first page at the 0,0 position
new_page.mergePage(page1)
# Add second page with moving along the axis x
new_page.mergeTranslatedPage(page2, page1.mediaBox.upperLeft[0], 0)

output = PdfFileWriter()
output.addPage(new_page)
output.write(open("result.pdf", "wb"))


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source