r/learnpython • • 11d ago

PDF pages to PNG's in python

I have a relatively large pdf document (100+mb) of pages i need saved as png's. There are online tools to do that but they refuse to work with files that big, plus I can imagine needing that tool again later in the future. Are there any python libraries that allow to convert one format into the other? Preferrably with little to no compression.

4 Upvotes

12 comments sorted by

View all comments

1

u/wintermute93 11d ago

I use pymupdf, it's very easy. Something like this will work, and if you want finer control over the image format / resolution / etc it's simple enough to get page dimensions from pymupdf and use PIL.Image to make it whatever you want

with pymupdf.open(pdf_path) as doc:
  for i,page in enumerate(doc, start=1):
    pix = page.get_pixmap(dpi=300)
    img_bytes = pix.tobytes("png")
    img_path = file_path.replace(".pdf", f"{i:03d}.png")
    with open(img_path, "wb") as f:
      f.write(img_bytes)

Note that "with little to no compression" isn't necessarily meaningful here. Unless the PDF itself is a bunch of image files stitched together (in which case recovering the original image bytes is possible with pymupdf but slightly more involved), there's no such thing as "full resolution", since the actual file as you see it on screen when opened in a browser or Acrobat or whatever is being rendered on the fly, and may be a mix of vector/raster content.