Extract pages from PDF

import PyPDF2

def extract_pages(source_pdf_path, output_pdf_path, pages_to_extract):
    """
    Extracts specific pages from a PDF and saves them into a new PDF file.

    Parameters:
    - source_pdf_path: The path to the source PDF from which to extract pages.
    - output_pdf_path: The path to save the new PDF with the extracted pages.
    - pages_to_extract: A list of page numbers (0-indexed) to extract.
    """
    # Open the source PDF
    with open(source_pdf_path, 'rb') as file:
        reader = PyPDF2.PdfReader(file)
        writer = PyPDF2.PdfWriter()

        # Loop through the list of pages to extract and add them to the writer
        for page_num in pages_to_extract:
            try:
                writer.add_page(reader.pages[page_num])
            except IndexError:
                print(f"Page {page_num} is out of range.")
                continue

        # Save the pages to a new PDF
        with open(output_pdf_path, 'wb') as output_pdf:
            writer.write(output_pdf)

# Example usage
source_pdf = "input.pdf"  # Replace this with your source PDF file path
output_pdf = "output.pdf"  # The output file
pages = [19,20,21]  # Example page numbers to extract (0-indexed)

extract_pages(source_pdf, output_pdf, pages)