Skip to content

Instantly share code, notes, and snippets.

@saiankit
Created December 13, 2021 12:08
Show Gist options
  • Save saiankit/381a2a4a1e7f3f54a88014cdf68fb538 to your computer and use it in GitHub Desktop.
Save saiankit/381a2a4a1e7f3f54a88014cdf68fb538 to your computer and use it in GitHub Desktop.
Delete Select Pages from a given PDF
from PyPDF2 import PdfFileWriter, PdfFileReader
# Enter the pages to delete inside this array
# 1st page refers to 1
# If you want to delete the pages 2,18,222 enter 2,18,22 inside the array
pages_to_delete = []
#pdfName refers to the name of the PDF File, and also ensure that this code is inside the same directory where the PDF file is located
# or else move the PDF File to this directory and then run the code.
infile = PdfFileReader('pdfName.pdf', 'rb')
output = PdfFileWriter()
for i in range(infile.getNumPages()):
if (i+1) not in pages_to_delete:
p = infile.getPage(i)
output.addPage(p)
# newPdfName refers to the new PDF File name
with open('newPdfName.pdf', 'wb') as f:
output.write(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment