Skip to main content
Glama

convert_to_pdf

Convert multiple image files into a single PDF document with optional title and file sorting.

Instructions

Convert a list of images to a PDF document.

Args:
    image_paths: List of image file paths to convert
    output_path: Path for the output PDF file
    title: Optional title for the PDF document
    sort_files: Whether to sort files by name before conversion

Returns:
    JSON string with conversion results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_pathsYes
output_pathYes
titleNo
sort_filesNo

Implementation Reference

  • The primary handler for the 'convert_to_pdf' tool, registered via @mcp.tool(). Handles input validation, delegates to PDFConverter for conversion, and returns JSON results.
    @mcp.tool()
    async def convert_to_pdf(
        image_paths: List[str],
        output_path: str,
        title: Optional[str] = None,
        sort_files: bool = True
    ) -> str:
        """
        Convert a list of images to a PDF document.
        
        Args:
            image_paths: List of image file paths to convert
            output_path: Path for the output PDF file
            title: Optional title for the PDF document
            sort_files: Whether to sort files by name before conversion
        
        Returns:
            JSON string with conversion results.
        """
        try:
            # Validate images first
            pc = get_pdf_converter()
            validation = pc.validate_images_for_pdf(image_paths)
            
            if not validation["valid_images"]:
                return json.dumps({
                    "status": "error",
                    "error": "No valid images found for conversion",
                    "validation": validation
                })
            
            # Convert to PDF
            pdf_path = pc.images_to_pdf(
                validation["valid_images"],
                output_path,
                sort_files=sort_files,
                title=title
            )
            
            pdf_info = pc.get_pdf_info(pdf_path)
            
            result = {
                "status": "success",
                "input_images": len(image_paths),
                "valid_images": len(validation["valid_images"]),
                "output_pdf": pdf_path,
                "pdf_info": pdf_info,
                "validation": validation
            }
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            logger.error(f"Failed to convert to PDF: {e}")
            return json.dumps({
                "status": "error",
                "error": str(e),
                "input_images": len(image_paths) if image_paths else 0,
                "output_pdf": output_path
            })
  • Core helper method implementing the image-to-PDF conversion using img2pdf, filtering and sorting valid images before conversion.
    def images_to_pdf(self, image_paths: List[str], output_path: str, 
                     sort_files: bool = True, title: Optional[str] = None) -> str:
        """
        Convert a list of images to a single PDF document.
        
        Args:
            image_paths: List of image file paths
            output_path: Output PDF file path
            sort_files: Whether to sort files by name
            title: PDF document title (optional)
        
        Returns:
            Path to created PDF file
        """
        try:
            # Filter existing files with supported formats
            valid_images = []
            for path in image_paths:
                if os.path.exists(path):
                    ext = Path(path).suffix.lower()
                    if ext in self.supported_formats:
                        valid_images.append(path)
                    else:
                        logger.warning(f"Unsupported format: {path}")
                else:
                    logger.warning(f"File not found: {path}")
            
            if not valid_images:
                raise ValueError("No valid images found")
            
            # Sort files if requested
            if sort_files:
                valid_images.sort()
            
            logger.info(f"Converting {len(valid_images)} images to PDF")
            
            # Create output directory if needed
            output_dir = os.path.dirname(output_path)
            if output_dir:  # Only create directory if path has a directory component
                os.makedirs(output_dir, exist_ok=True)
            
            # Convert images to PDF
            with open(output_path, "wb") as f:
                f.write(img2pdf.convert(
                    valid_images,
                    title=title or "Auto-Snap Captured Document"
                ))
            
            logger.info(f"PDF created: {output_path}")
            return output_path
            
        except Exception as e:
            logger.error(f"Failed to convert images to PDF: {e}")
            raise
  • Helper method for validating input images before PDF conversion, checks existence, format, and image integrity using PIL.
    def validate_images_for_pdf(self, image_paths: List[str]) -> dict:
        """
        Validate images before PDF conversion.
        
        Args:
            image_paths: List of image file paths
        
        Returns:
            Dictionary with validation results
        """
        results = {
            'valid_images': [],
            'invalid_images': [],
            'missing_files': [],
            'unsupported_formats': [],
            'total_size_mb': 0
        }
        
        for path in image_paths:
            if not os.path.exists(path):
                results['missing_files'].append(path)
                continue
            
            ext = Path(path).suffix.lower()
            if ext not in self.supported_formats:
                results['unsupported_formats'].append(path)
                continue
            
            try:
                # Try to open image to validate
                with Image.open(path) as img:
                    img.verify()
                
                file_size = os.path.getsize(path)
                results['total_size_mb'] += file_size / (1024 * 1024)
                results['valid_images'].append(path)
                
            except Exception as e:
                logger.warning(f"Invalid image {path}: {e}")
                results['invalid_images'].append(path)
        
        results['total_size_mb'] = round(results['total_size_mb'], 2)
        
        logger.info(f"Validation: {len(results['valid_images'])} valid, "
                   f"{len(results['invalid_images'])} invalid, "
                   f"{len(results['missing_files'])} missing, "
                   f"{len(results['unsupported_formats'])} unsupported")
        
        return results
  • Helper method to retrieve metadata about the generated PDF file, such as size and existence.
    def get_pdf_info(self, pdf_path: str) -> dict:
        """
        Get basic information about a PDF file.
        
        Args:
            pdf_path: Path to PDF file
        
        Returns:
            Dictionary with PDF information
        """
        try:
            file_size = os.path.getsize(pdf_path)
            
            info = {
                'path': pdf_path,
                'size_bytes': file_size,
                'size_mb': round(file_size / (1024 * 1024), 2),
                'exists': os.path.exists(pdf_path)
            }
            
            return info
            
        except Exception as e:
            logger.error(f"Failed to get PDF info for {pdf_path}: {e}")
            return {'path': pdf_path, 'error': str(e)}
  • server.py:303-303 (registration)
    The @mcp.tool() decorator registers the convert_to_pdf function as an MCP tool.
    @mcp.tool()

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/PovedaAqui/auto-snap-mcp'

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