Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

merge pdf with python at same page

import os
from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger

def pdf_splitter(path): 

    fname = os.path.splitext(os.path.basename(path))[0]

    pdf = PdfFileReader(path)
    input_paths = []
    for page in range(pdf.getNumPages()):
        pdf_writer = PdfFileWriter()
        pdf_writer.addPage(pdf.getPage(page))
        output_filename = '{}_page_{}.pdf'.format(fname, page+1)
        input_paths.append(output_filename)
        with open(output_filename, 'wb') as out:
            pdf_writer.write(out)

        print('Created: {}'.format(output_filename))

        # every 2 pages! 
        # Change the two if you need every other number of pages!
        if page % 2 == 1:
            pdf_merger = PdfFileMerger() #create pdfilemerger
            for path in input_paths: 
                pdf_merger.append(path) #read the single pages

            # we call it pages_N-1_N, so first would be pages_0_1!
            output_path = '{}_pages_{}_{}.pdf'.format(fname, page-1, page)
            with open(output_path, 'wb') as fileobj:
                pdf_merger.write(fileobj) # write the two pages pdf!

            input_paths = []

if __name__ == '__main__': 

    path = 'D:TasksSamplesfw9.pdf' 
    pdf_splitter(path)
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #merge #pdf #python #page
ADD COMMENT
Topic
Name
5+1 =