Search code examples
pythonpymupdf

Python - Go through only 5 pages at one time in PyMuPdf Fitz


  • 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 of PyMuPdf, 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 process 15-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.

Solution

  • Look at the Document.pages() iterator. Simply iterate over Document.pages(-5) which will yield the last 5 pages.