Extract specific pages of PDF and save it with Python

11,436

Solution 1

I have fixed the issue. it was the equal sign (start<=end).

for page in range(len(information)):
    pdf_writer = PyPDF2.PdfFileWriter()
    start = information[page][1]
    end = information[page][2]
    while start<=end:
        pdf_writer.addPage(pdfReader.getPage(start-1))
        start+=1
    if not os.path.exists(savepath):
        os.makedirs(savepath)
    output_filename = '{}_{}_page_{}.pdf'.format(information[page][0],information[page][1], information[page][2])
    with open(output_filename,'wb') as out:
        pdf_writer.write(out)

Solution 2

Full code + modified SSS' answer to be more portable. Now you can supply multiple PDF files with 1+ "segments" of pages you want to be extracted.

from PyPDF2 import PdfFileReader, PdfFileWriter

# Note: index starts at 1 and is inclusive of the end. 
# The following will extract page 3 of the pdf file.
pdfs = {'BMC PP template.pdf': ({'start': 3, 'end': 3},)}  

for pdf, segments in pdfs.items():
    pdf_reader = PdfFileReader(open(pdf, 'rb'))
    for segment in segments:
        pdf_writer = PdfFileWriter()
        start_page = segment['start']
        end_page = segment['end']
        for page_num in range(start_page - 1, end_page):
            pdf_writer.addPage(pdf_reader.getPage(page_num))
        output_filename = f'{pdf}_{start_page}_page_{end_page}.pdf'
        with open(output_filename,'wb') as out:
            pdf_writer.write(out)
Share:
11,436

Related videos on Youtube

SSS
Author by

SSS

Updated on June 19, 2022

Comments

  • SSS
    SSS almost 2 years

    I have some sources and tried to code which extract some pages and create pdf files. I have a list which looks like this

    information = [(filename1,startpage1,endpage1), (filename2, startpage2, endpage2), ...,(filename19,startpage19,endpage19)].
    

    This is my code.

    import PyPDF2    
    for page in range(pdfReader.getNumPages()-1):
        pdf_writer = PyPDF2.PdfFileWriter()
        start = information[page][1]
        end = information[page][2]
        while start<end:
            pdf_writer.addPage(pdfReader.getPage(start))
            start+=1
            output_filename = '{}_{}_page_{}.pdf'.format(information[page][0],information[page][1], information[page][2])
        with open(output_filename,'wb') as out:
            pdf_writer.write(out)
    

    But the output is weird.. some has nothing inside and some has just one page in it. How can I correct this?

  • Bjc51192
    Bjc51192 about 5 years
    I have been looking for something like this for hours. Thanks SSS.