Skip to main content
Glama
andr3medeiros

PDF Manipulation MCP Server

pdf_add_image

Add images to PDF documents by specifying exact page positions and dimensions to enhance or annotate content.

Instructions

Add an image to a PDF.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pdf_pathYes
page_numberYes
image_pathYes
xYes
yYes
widthYes
heightYes

Implementation Reference

  • The handler function for the 'pdf_add_image' tool. It validates the input PDF and image paths, opens the PDF using PyMuPDF (fitz), adds the image to the specified page at given coordinates and size, generates a timestamped output filename, saves the modified PDF, and returns the output path.
    @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:
            return f"Error adding image to PDF: {str(e)}"
  • Helper utility used by pdf_add_image (and other tools) to generate a timestamped output filename 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}")
  • Helper function used by pdf_add_image to validate that the input file is a valid PDF.
    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.
    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)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/andr3medeiros/pdf-manipulation-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server