[Python] How do I split a PDF using Python, every page that contains a set of specific unique...

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a large PDF file, and need to split it every 'X' pages, but where 'X' could vary. I need it to split every page where a page contains the text 'Name:', but where the text after the 'Name: ' changes...

    So page 1 might have 'Name: Sachin', then page 2 might also have 'Name: Sachin', but page 3 has 'Name: Sarah', so it should split from Pages 1 to 2, and then Page 3.

    Here is a script I found, except it splits on every page, regardless.

    https://www.blog.pythonlibrary.org/2018/04/11/splitting-and-merging-pdfs-with-python/

    Thanks in advance,

    Sachin

    UPDATE:

    Here is some code that splits every page regardless, but which detects the name after the text 'Name:' is found and renames the split file accordingly, it has the name in the filename.

    How though do I update the code so that if there are two consecutive pages with the same name found (after the text field 'Name:') that it DOES NOT SPLIT on that page, but merges the two pages with the same name into one pdf file?

    Thanks again,

    Sachin

    import os
    import re
    from PyPDF2 import PdfFileReader, PdfFileWriter

    pdf_file_path = 'Payslips.pdf'
    file_base_name = pdf_file_path.replace('.pdf', '')
    output_folder_path = os.path.join(os.getcwd(), 'Output')

    pdf = PdfFileReader(pdf_file_path)

    for page_num in range(pdf.numPages):

    # Setup Objects & Classes
    pdfWriter = PdfFileWriter()
    pageObj = pdf.getPage(page_num)
    pdfWriter.addPage(pageObj)

    # Extract Text
    Text = pageObj.extractText()

    # print(Text)
    MatchedTextArray = re.findall("Name:[^0-9]+?\s", Text)
    MatchedText = (MatchedTextArray[0].replace('Name:', '')).replace('\n', '')

    # Splitting on UpperCase
    res_pos = [i for i, e in enumerate(MatchedText+'A') if e.isupper()]
    res_list = [MatchedText[res_pos[j]:res_pos[j + 1]]
    for j in range(len(res_pos)-1)]

    # Extracting Firstname
    firstname = res_list[1]

    # Extracting Surname
    del res_list[0:2]
    surname = ''.join(res_list)


    with open(os.path.join(output_folder_path,
    '{0}, {1} - {2}.pdf'.format(surname.upper(), firstname.upper(), file_base_name.upper())),
    'wb') as f:
    pdfWriter.write(f)
    f.close()

    print("Split Page " + str(page_num))

    Continue reading...

Compartilhe esta Página