[PYTHON] Merge two PDF files page by page with each other

Make one PDF by sandwiching two PDF files page by page

There was a request at work, so I made it.

** [Prepared file] ** ・ PdfA.pdf ・ PdfB.pdf ・pdf.py

【image】 pdfA.pdf --> pageA-1, pageA-2, pageA-3, ... pdfB.pdf --> pageB-1, PageB-2, pageB-3, ... pdfC.pdf --> pageA-1, pageB-1, pageA-2, pageB-2, pageA-3, pageB-3, ...

【procedure】

Install PyPDF2 library

conda install -c conda-forge pypdf2

Script creation

pdf.py


#! ~/usr/bin/python
# *-# -*- coding: utf-8

import PyPDF2

#File path
pdfA = "pdfA.pdf"
pdfB = "pdfB.pdf"

#Output pdf object
pdf_writer = PyPDF2.PdfFileWriter()

#pdfA open
f_A = open(pdfA, "rb")
pdfA_obj = PyPDF2.PdfFileReader(f_A)

#pdfB open
f_B = open(pdfB, "rb")
pdfB_obj = PyPDF2.PdfFileReader(f_B)

#Insert each PDF page by page. Edit the number of repetitions each time (for now)
for page_num in range(10):
	page_obj = pdfA_obj.getPage(page_num)
	pdf_writer.addPage(page_obj)
	page_obj = pdfB_obj.getPage(page_num)
	pdf_writer.addPage(page_obj)

#pdfC.Output as pdf
pdf_output = open('pdfC.pdf', 'wb')
pdf_writer.write(pdf_output)
pdf_output.close()

Run

% python pdf.py

from now on The number of pages is automatically acquired and the desired operation is performed without editing the script.

Recommended Posts

Merge two PDF files page by page with each other
Integrate PDF files with Python
Convert PDF files to PNG files with GIMP
Download PDF with selenium chromedriver (Chrome 57) + (Other notes)
Create a PDF file with a random page size
[Python] Continued-Convert PDF text to CSV page by page