Search code examples
pythonpymupdf

Python PyMuPDF looping next pages


I'm using below code to open a PDF file and convert into an image file as output. Now, i'm trying to figure it out how can I loop the next page and convert it as same output file. Any help is much appreciated!

# display image on the canvas
def openFile(self, _value=False):
    global fileImg, output


    path = os.path.dirname(ustr(self.filePath)) if self.filePath else '.'
    fileImg = QFileDialog.getOpenFileName(self, '%s - Choose file' % __appname__, path)

    # convert PDF to image file
    pdffile = fileImg
    doc = fitz.open(pdffile)
    page = doc.loadPage(0)
    pix = page.getPixmap(matrix=fitz.Matrix(100 / 72, 100 / 72))
    output = "output.png"
    pix.writePNG(output)

Solution

  • You can simply loop over the doc object to get the next pages.

    doc = fitz.open(file_name)  # open document
    for page in doc:  # iterate through the pages
        pix = page.getPixmap(...)  # render page to an image
        pix.writePNG("page-%i.png" % page.number)  # store image as a PNG
    

    check the PyMuPDF documentation for more information.