GroupDocs.Parser allows you to extract images from specific pages of a document, providing fine-grained control over image extraction.
Prerequisites
GroupDocs.Parser for Python via .NET installed
Sample documents with multiple pages
Basic understanding of page indexing (zero-based)
Extract images from a specific page
To extract images from a particular page:
fromgroupdocs.parserimportParser# Create an instance of Parser classwithParser("./sample.pdf")asparser:# Check if image extraction is supportedifnotparser.features.images:print("Document doesn't support image extraction")else:# Extract images from page 0 (first page)page_index=0images=parser.get_images(page_index)ifimages:print(f"Images on page {page_index+1}:")foridx,imageinenumerate(images):size=image.rectangle.sizeprint(f" Image {idx+1}: {image.file_type}, size: {size.width}x{size.height}")else:print(f"No images on page {page_index+1}")
The following sample file is used in this example: sample.pdf
Expected behavior: Returns only the images from the specified page, or an empty collection if the page has no images.
Extract images from all pages
To process images page by page:
fromgroupdocs.parserimportParser# Create an instance of Parser classwithParser("./sample.pptx")asparser:# Check if image extraction is supportedifnotparser.features.images:print("Document doesn't support image extraction")else:# Get document infoinfo=parser.get_document_info()# Check if document has pagesifinfo.page_count==0:print("Document has no pages")else:# Iterate over pagestotal_images=0forpage_indexinrange(info.page_count):print(f"\nPage {page_index+1}/{info.page_count}:")# Extract images from the current pageimages=parser.get_images(page_index)ifimages:page_image_count=0forimageinimages:print(f" Type: {image.file_type}, Position: ({image.rectangle.left}, {image.rectangle.top})")page_image_count+=1print(f" Total images on this page: {page_image_count}")total_images+=page_image_countelse:print(" No images on this page")print(f"\nTotal images in document: {total_images}")
The following sample file is used in this example: sample.pptx
Page 1/3:
Type: Portable Network Graphic(.png), Position: (30, 20)
Type: JPEG Image(.jpeg), Position: (140, 130)
Total images on this page: 2
Page 2/3:
Type: JPEG Image(.jpeg), Position: (40, 110)
Type: JPEG Image(.jpeg), Position: (380, 110)
Total images on this page: 2
[TRUNCATED]
Expected behavior: Iterates through all pages and extracts images from each page individually, showing page-specific image counts.
Save images by page
To save images organized by page number:
fromgroupdocs.parserimportParserimportos# Create output directoryoutput_dir="images_by_page"os.makedirs(output_dir,exist_ok=True)# Create an instance of Parser classwithParser("./sample.pdf")asparser:ifnotparser.features.images:print("Image extraction not supported")else:# Get document infoinfo=parser.get_document_info()# Process each pageforpage_indexinrange(info.page_count):# Create page-specific directorypage_dir=os.path.join(output_dir,f"page_{page_index+1}")os.makedirs(page_dir,exist_ok=True)# Extract images from pageimages=parser.get_images(page_index)ifimages:forimg_idx,imageinenumerate(images):# Generate filenamefilename=f"image_{img_idx+1}{image.file_type.extension}"filepath=os.path.join(page_dir,filename)# Save imageimage.save(filepath)print(f"Saved: {filepath}")else:print(f"No images on page {page_index+1}")
The following sample file is used in this example: sample.pdf
Expected behavior: Creates separate directories for each page and saves extracted images with organized naming.
Extract images from specific pages only
To extract images from selected pages:
fromgroupdocs.parserimportParserimportos# Create an instance of Parser classwithParser("./sample.docx")asparser:ifnotparser.features.images:print("Image extraction not supported")else:# Define pages to process (e.g., pages 1, 3, and 5)pages_to_process=[0,2,4]# Zero-based indicesoutput_dir="selected_page_images"os.makedirs(output_dir,exist_ok=True)# A page index past the last page raises an error, so check the page countpage_count=parser.get_document_info().page_countforpage_indexinpages_to_process:ifpage_index>=page_count:print(f"\nPage {page_index+1} skipped: the document has {page_count} pages")continueprint(f"\nProcessing page {page_index+1}...")# Extract images from this pageimages=parser.get_images(page_index)ifimages:forimg_idx,imageinenumerate(images):filename=f"page{page_index+1}_img{img_idx+1}{image.file_type.extension}"filepath=os.path.join(output_dir,filename)image.save(filepath)print(f" Saved: {filename}")else:print(f" No images found on page {page_index+1}")
The following sample file is used in this example: sample.docx
fromgroupdocs.parserimportParserimportos# Create output directoryoutput_dir="first_images"os.makedirs(output_dir,exist_ok=True)# Create an instance of Parser classwithParser("./sample.pdf")asparser:ifnotparser.features.images:print("Image extraction not supported")else:info=parser.get_document_info()forpage_indexinrange(info.page_count):# Extract images from pageimages=parser.get_images(page_index)ifimages:# Get first image onlyfirst_image=images[0]filename=f"page_{page_index+1}_first{first_image.file_type.extension}"filepath=os.path.join(output_dir,filename)first_image.save(filepath)print(f"Saved first image from page {page_index+1}: {filename}")else:print(f"No images on page {page_index+1}")
The following sample file is used in this example: sample.pdf