cavemanweb
cavemanweb

Reputation: 21

Renaming last page using pyPDF2

I'm using the pyPDF2 library, with this script:

import os from PyPDF2 import PdfFileReader, PdfFileWriter

def pdf_splitter(path): fname = os.path.splitext(os.path.basename(path))[0]

pdf = PdfFileReader(path)
for page in range(pdf.getNumPages()):
    pdf_writer = PdfFileWriter()
    pdf_writer.addPage(pdf.getPage(page))

    output_filename = '{}_page_{}.pdf'.format(
        fname, page+1)

    with open(output_filename, 'wb') as out:
        pdf_writer.write(out)

    print('Created: {}'.format(output_filename))

if name == 'main': path = 'w9.pdf' pdf_splitter(path)

This is just an example, it reads the original PDF with multiple pages on it and split into separated files. It adds the page number on the splited files:

Ex. Original PDF name: w9.pdf Split into: w9_01_01.pdf,w9_01_02.pdf,w9_01_03.pdf

I need to rename the last splited pdf into w9_01_end.pdf instead of w9_01_03.pdf I know that with the getNumPages() you can get the total pages of the original pdf, but don't know how to detect the last one and name it different. Also with getPage you can get the current page too.

Any help will be appreciated.

Upvotes: 1

Views: 213

Answers (1)

zanga
zanga

Reputation: 719

If I understand right the problem you might just add an if statement to check if you are creating the last page or not:

if page != pdf.getNumPages()-1: #for loop works from [0;x[
      output_filename = '{}_page_{}.pdf'.format(
          fname, page+1)
    else:
      output_filename = '{}_page_end.pdf'.format(
          fname)

Upvotes: 2

Related Questions