- I want to iterate through the last 5 pages of a PDF in
PyMuPdf
, and ask the user if he wants to iterate through more 5 pages. - I came across
reversed
method ofPyMuPdf
, but that doesn't take the parameter of limiting it to only 5 pages. - Example, total 20 pages in a PDF. First process Page no. 16 to 20 in reverse order i.e.
20-19-18-17-16
and if the user enters Yes to process another 5 pages then process15-14-13-12-11
and so on. doc.pages(start, stop, step)
this method can be used for iterating through particular number of pages, but then I have to manually calculate the start and end, and do which is not a good practice.
Asked
Active
Viewed 385 times
0

donny
- 101
- 6
-
1Look at [this](https://stackoverflow.com/a/22919323/257027) answer that uses `itertools` with `islice` and `takewhile`. – Nick Sep 26 '22 at 09:46
2 Answers
2
Look at the Document.pages()
iterator.
Simply iterate over Document.pages(-5)
which will yield the last 5 pages.

Jorj McKie
- 2,062
- 1
- 13
- 17
1
Use doc.page_count
- Create a list of the page numbers, in your case it is the last 5 pages.
- Use the syntax
last_pages=list(range(doc.page_count-5,doc.page_count))
- Iterate through the list representing the page numbers.

Mohit Mehlawat
- 344
- 3
- 6