Erwin
Erwin

Reputation: 19

Problems extracting files from a pdf with PyM

I want to extract and save images as .png, from a pdf file. I use the following Python code and PyMuPDF:

import fitz 
import io
from PIL import Image
file = "pdf1.pdf"
pdf_file = fitz.open(file)
for page_index in range(len(pdf_file)):
    page = pdf_file[page_index]
    image_list = page.getImageList()

    if image_list:
        print(f"[+] Found a total of {len(image_list)} images in page {page_index}")
    else:
        print("[!] No images found on page", page_index)
    for image_index, img in enumerate(page.getImageList(), start=1):
    
        xref = img[0]
        base_image = pdf_file.extractImage(xref)
        image_bytes = base_image["image"]
        image_ext = base_image["ext"]
        image = Image.open(io.BytesIO(image_bytes))
        image.save(open(f"image{page_index+1}_{image_index}.{image_ext}", "wb"))

But I get the following error message:

---------------------------------------------------------------------------
  AttributeError                            Traceback (most recent call last)
  <ipython-input-5-bb8715bc185b> in <module>()
  10     # get the page itself
  11     page = pdf_file[page_index]
  ---> 12     image_list = page.getImageList()
  13     # printing number of images found in this page
  14     if image_list:

  AttributeError: 'Page' object has no attribute 'getImageList'

​Is it related to the pdf file structure ( a non-dictionary type)? How could I solve it in that case?

Upvotes: 0

Views: 806

Answers (1)

Jorj McKie
Jorj McKie

Reputation: 3110

You forgot to mention the PyMuPDF version you used. Your method name getImageList had been deprecated for a long time - a new name page.get_images() should be have been used. In the most recent version 1.20.x the old name is finally removed. If you have a lot of old code using those old names you can either use a utility to make a global change, or execute fitz.restore_aliases() after import fitz.

Upvotes: 1

Related Questions