convert_to_pdf
Combine multiple image files into a single PDF document. Specify image paths, output location, optional title, and choose to sort files by name for organized results.
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
| Name | Required | Description | Default |
|---|---|---|---|
| image_paths | Yes | ||
| output_path | Yes | ||
| sort_files | No | ||
| title | No |
Implementation Reference
- server.py:303-363 (handler)MCP tool handler for convert_to_pdf. Registers the tool with @mcp.tool(), defines input schema via type hints, handles validation, conversion via PDFConverter, 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 })
- pdf_utils.py:51-104 (helper)Core helper method in PDFConverter class that performs the actual image-to-PDF conversion using img2pdf library.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
- pdf_utils.py:206-254 (helper)Helper method for input validation, checks file existence, supported formats, 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
- pdf_utils.py:180-205 (helper)Helper method to retrieve PDF file metadata like size and existence, used in tool response.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)}