pdf_add_image
Add images to PDF documents by specifying exact position and dimensions on any page. Insert logos, signatures, or graphics into PDF files with precise placement control.
Instructions
Add an image to a PDF.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| pdf_path | Yes | ||
| page_number | Yes | ||
| image_path | Yes | ||
| x | Yes | ||
| y | Yes | ||
| width | Yes | ||
| height | Yes |
Implementation Reference
- The primary handler function for the 'pdf_add_image' tool. Decorated with @mcp.tool() for automatic registration in FastMCP. Validates PDF and image paths, page number, inserts image at specified position and size using PyMuPDF, generates timestamped output file, returns success path or error message.@mcp.tool() async def pdf_add_image( pdf_path: str, page_number: int, image_path: str, x: float, y: float, width: float, height: float ) -> str: """Add an image to a PDF.""" if not os.path.exists(pdf_path): return f"Error: PDF file not found: {pdf_path}" if not validate_pdf_file(pdf_path): return f"Error: Invalid PDF file: {pdf_path}" if not os.path.exists(image_path): return f"Error: Image file not found: {image_path}" try: # Open PDF document doc = fitz.open(pdf_path) # Validate page number if not validate_page_number(doc, page_number): doc.close() return f"Error: Invalid page number {page_number}. Document has {len(doc)} pages." # Get the page page = doc[page_number] # Create rectangle for image placement rect = fitz.Rect(x, y, x + width, y + height) # Add image to the page page.insert_image(rect, filename=image_path) # Generate output filename output_path = generate_output_filename(pdf_path) # Save the modified PDF doc.save(output_path) doc.close() return f"Successfully added image to PDF. Output saved to: {output_path}" except Exception as e:
- Helper function used by pdf_add_image to validate the input PDF file is valid by attempting to open it with PyMuPDF.def validate_pdf_file(pdf_path: str) -> bool: """Validate that the file is a valid PDF.""" try: doc = fitz.open(pdf_path) doc.close() return True except Exception: return False
- Helper function used by pdf_add_image to check if the specified page number is valid in the document.def validate_page_number(doc: fitz.Document, page_num: int) -> bool: """Validate that the page number exists in the document.""" return 0 <= page_num < len(doc)
- Helper function used by pdf_add_image to create a unique output filename with timestamp to prevent overwriting the original PDF.def generate_output_filename(input_path: str, suffix: str = "modified") -> str: """Generate a new filename with timestamp to avoid overwriting originals.""" path = Path(input_path) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") return str(path.parent / f"{path.stem}_{suffix}_{timestamp}{path.suffix}")