Skip to content

Instantly share code, notes, and snippets.

@Geekfish
Created January 31, 2017 16:07
Show Gist options
  • Save Geekfish/a4fe4efd59e158f55ca5c76479831c8d to your computer and use it in GitHub Desktop.
Save Geekfish/a4fe4efd59e158f55ca5c76479831c8d to your computer and use it in GitHub Desktop.
pyPDF2 merge 2 pdf pages into one
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.pdf import PageObject
reader = PdfFileReader(open("invoice.pdf",'rb'))
invoice_page = reader.getPage(0)
sup_reader = PdfFileReader(open("supplement.pdf",'rb'))
sup_page = sup_reader.getPage(1) # We pick the second page here
translated_page = PageObject.createBlankPage(None, sup_page.mediaBox.getWidth(), sup_page.mediaBox.getHeight())
translated_page.mergeScaledTranslatedPage(sup_page, 1, 0, -400) # -400 is approximate mid-page
translated_page.mergePage(invoice_page)
writer = PdfFileWriter()
writer.addPage(translated_page)
with open('out.pdf', 'wb') as f:
writer.write(f)
@winosli
Copy link

winosli commented Mar 25, 2020

An extra simple way to merge unlimited pdf's:

import PyPDF2
import sys

#inputs = sys.argv[1:] # From input (without spaces!)
inputs = ['test 1.pdf', 'test 2.pdf'] # Add those pdf's to your project

def pdf_combine(pdf_list):
    merger = PyPDF2.PdfFileMerger()
    for pdf in pdf_list:
        merger.append(pdf)
    merger.write('merge.pdf')

pdf_combine(inputs)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment