Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ProximaB/c82ca664b7d89d4bf10003b8dce03e4b to your computer and use it in GitHub Desktop.
Save ProximaB/c82ca664b7d89d4bf10003b8dce03e4b to your computer and use it in GitHub Desktop.
import os
from PyPDF2 import PdfReader, PdfWriter
def replace_third_page_with_first(dir_path, replacement_file, output_dir):
with open(replacement_file, 'rb') as replacement_pdf_file:
replacement_pdf = PdfReader(replacement_pdf_file)
first_page = replacement_pdf.pages[0]
for filename in os.listdir(dir_path):
if filename.endswith('.pdf'):
pdf_path = os.path.join(dir_path, filename)
output_pdf_path = os.path.join(output_dir, 'modified_' + filename)
with open(pdf_path, 'rb') as pdf_file:
pdf = PdfReader(pdf_file)
writer = PdfWriter()
for page_num, page in enumerate(pdf.pages):
if page_num == 2:
writer.add_page(first_page)
else:
writer.add_page(page)
with open(output_pdf_path, 'wb') as output_pdf_file:
writer.write(output_pdf_file)
directory_path = './Zaproszenia'
replacement_pdf_file = './trzeciaStrona.pdf'
output_directory_path = './Poprawione'
if not os.path.exists(output_directory_path):
os.makedirs(output_directory_path)
replace_third_page_with_first(directory_path, replacement_pdf_file, output_directory_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment