-3

I've uploaded a PDF using PyPDF2. Here's my code:

PageNo=list(range(0,pfr.numPages))

for i in PageNo:
    pg = writer.addPage(i)

PageNo creates a list of all the page numbers and I'm trying to add each page from the list into a new PDF, but when I run this script, I'm getting 'int' object is not subscriptable. I know it's an error in my for loop, and I'm sure it's obvious, but any insight on my mistake above would be appreciated.

Thanks!

Edit - here's the solution:

for i in list(range(0,pfr.numPages))
     pg = pfr.getPage(i)
     writer.addPage(pg)
user2744315
  • 77
  • 1
  • 1
  • 7

2 Answers2

1

Without seeing more code, like what exactly is pfr.numPages? Where is it created? How is it used? the error is happening because PageNo is being evaluated as an int, so its less likely its an error in your for loop and more likely an error in your list. Assuming pfr.numPages is an array of some type, try this:

for i in range(0, len(pfr.numPages)):
    pg = writer.addPage(prf.numPages[i])

However as mentioned before, if PageNo is being evaluated as an int, then pfr.numPages isn't an array or its an array with one element. Pay close attention to the trace if this errors, it will tell you which line, and if it says int is not subscriptable on the line with prf.numPages, then you know that your problem is deeper than this for loop.

darrahts
  • 365
  • 1
  • 10
  • 1
    You are using `prf.numPages[i]` in your loop, it means that `prf.numPages` is a list. So how can use use `pfr.numPages` as integer in `for i in range(0, pfr.numPages):`? – Nouman Aug 18 '18 at 12:36
  • Good catch! Thank you I forgot to add `len` . – darrahts Aug 19 '18 at 13:46
  • Thanks for your comment! Turns out the issue was that I needed to define the variable before it was passed through writer.addPage. for i in list(range(0,pfr.numPages)): pg = pfr.getPage(i) writer.addPage(pg) – user2744315 Aug 19 '18 at 14:06
0

I am assuming that writer is a PdfFileWriter object. In that case, you will have to pass a page retrieved from pfr to the writer.addPage method, instead of passing an integer.

for i in pfr.pages:
    writer.addPage(i)
sourya
  • 165
  • 1
  • 1
  • 9