1# pdf_merging.py
2
3from PyPDF2 import PdfFileReader, PdfFileWriter
4
5def merge_pdfs(paths, output):
6 pdf_writer = PdfFileWriter()
7
8 for path in paths:
9 pdf_reader = PdfFileReader(path)
10 for page in range(pdf_reader.getNumPages()):
11 # Add each page to the writer object
12 pdf_writer.addPage(pdf_reader.getPage(page))
13
14 # Write out the merged PDF
15 with open(output, 'wb') as out:
16 pdf_writer.write(out)
17
18if __name__ == '__main__':
19 paths = ['document1.pdf', 'document2.pdf']
20 merge_pdfs(paths, output='merged.pdf')
21
1from PyPDF2 import PdfFileMerger, PdfFileReader
2merger = PdfFileMerger()
3
4merger.append(PdfFileReader(open(filename1, 'rb')))
5merger.append(PdfFileReader(open(filename2, 'rb')))
6
7merger.write("merged.pdf")
1from PyPDF2 import PdfFileMerger, PdfFileReader
2
3# Call the PdfFileMerger
4mergedObject = PdfFileMerger()
5
6# I had 116 files in the folder that had to be merged into a single document
7# Loop through all of them and append their pages
8for fileNumber in range(1, 117):
9 mergedObject.append(PdfFileReader('6_yuddhakanda_' + str(fileNumber)+ '.pdf', 'rb'))
10
11# Write all the files into a file which is named as shown below
12mergedObject.write("mergedfilesoutput.pdf")
13