Search code examples
python-imaging-librarypypdf

How to render a PyPDF2.PageObject page to a PIL image in python?


Can you help me to render a PDF page opened using PyPDF2 into a PIL image in Python 3?


Solution

  • I don't think PyPDF2 can render a pdf page. However, you can use PyMuPDF to do this. Here is the tutorial of PyMuPDF.

    Here is an example of rendering with PyMuPDF:

    import fitz
    from PIL import Image
    
    filename = "test.pdf"  # name of pdf file you want to render
    n = 0  # n is the page number
    
    #render with PyMuPDF
    doc = fitz.open(filename)
    page = doc.loadPage(n)
    pix = page.getPixmap()
    
    #convert to a PIL image
    img = Image.frombytes("RGBA", [pix.width, pix.height], pix.samples)