Skip to main content

Working with Images

PDFDancer allows you to work with images in PDFs - add new images, select existing ones, move them, and delete them.


Selecting Images

All Images

from pdfdancer import PDFDancer

with PDFDancer.open("document.pdf") as pdf:
# Get all images across the document
all_images = pdf.select_images()

# Get all images on a specific page
page_images = pdf.page(1).select_images()

for img in page_images:
print(f"Image ID: {img.internal_id}")
print(f"Position: {img.position.bounding_rect}")

Images at Coordinates

with PDFDancer.open("document.pdf") as pdf:
# Find images at specific coordinates
images = pdf.page(2).select_images_at(x=120, y=300)

for img in images:
print(f"Found image at position: {img.position}")

Adding Images

From File Path

from pathlib import Path
from pdfdancer import PDFDancer

with PDFDancer.open("document.pdf") as pdf:
# Add image from file
pdf.new_image() \
.from_file(Path("logo.png")) \
.at(page=1, x=48, y=700) \
.add()

pdf.save("output.pdf")

From Bytes

info

The Python SDK does not have a from_bytes() method. If you have image bytes, write them to a temporary file first, then use from_file().

import tempfile
from pathlib import Path
from pdfdancer import PDFDancer

with PDFDancer.open("document.pdf") as pdf:
# Load image bytes
image_bytes = Path("logo.png").read_bytes()

# Write bytes to temporary file
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file:
temp_path = Path(temp_file.name)
temp_path.write_bytes(image_bytes)

try:
# Add image from temporary file
pdf.new_image() \
.from_file(temp_path) \
.at(page=1, x=100, y=600) \
.add()

pdf.save("output.pdf")
finally:
# Clean up temporary file
temp_path.unlink()

Moving Images

from pdfdancer import PDFDancer

with PDFDancer.open("document.pdf") as pdf:
images = pdf.page(1).select_images()

if images:
# Move image to new position
images[0].move_to(x=200, y=350)

pdf.save("output.pdf")

Deleting Images

from pdfdancer import PDFDancer

with PDFDancer.open("document.pdf") as pdf:
images = pdf.page(1).select_images()

# Delete all images on page 0
for image in images:
image.delete()

pdf.save("output.pdf")

Next Steps