directory_to_pdf
Convert all images in a directory into a single PDF document. Specify the image directory, output path, optional title, and file pattern for streamlined PDF creation.
Instructions
Convert all images in a directory to a PDF document.
Args:
image_dir: Directory containing images
output_path: Path for the output PDF file
title: Optional title for the PDF document
pattern: File pattern to match (default: all files)
Returns:
JSON string with conversion results.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| image_dir | Yes | ||
| output_path | Yes | ||
| pattern | No | * | |
| title | No |
Implementation Reference
- server.py:365-365 (registration)MCP decorator registering the directory_to_pdf tool.@mcp.tool()
- server.py:366-413 (handler)Handler function for the MCP 'directory_to_pdf' tool, wrapping the core converter and providing JSON response.async def directory_to_pdf( image_dir: str, output_path: str, title: Optional[str] = None, pattern: str = "*" ) -> str: """ Convert all images in a directory to a PDF document. Args: image_dir: Directory containing images output_path: Path for the output PDF file title: Optional title for the PDF document pattern: File pattern to match (default: all files) Returns: JSON string with conversion results. """ try: pc = get_pdf_converter() pdf_path = pc.directory_to_pdf( image_dir=image_dir, output_path=output_path, pattern=pattern, title=title ) pdf_info = pc.get_pdf_info(pdf_path) result = { "status": "success", "input_directory": image_dir, "pattern": pattern, "output_pdf": pdf_path, "pdf_info": pdf_info } return json.dumps(result, indent=2) except Exception as e: logger.error(f"Failed to convert directory to PDF: {e}") return json.dumps({ "status": "error", "error": str(e), "input_directory": image_dir, "output_pdf": output_path })
- pdf_utils.py:106-157 (handler)Core implementation of directory_to_pdf in PDFConverter class: discovers images matching pattern and converts to PDF using images_to_pdf.def directory_to_pdf(self, image_dir: str, output_path: str, pattern: str = "*", title: Optional[str] = None) -> str: """ Convert all images in a directory to PDF. Args: image_dir: Directory containing images output_path: Output PDF file path pattern: File pattern to match (default: *) title: PDF document title (optional) Returns: Path to created PDF file """ try: image_paths = [] # Find all image files in directory logger.info(f"Searching for images in {image_dir} with pattern '{pattern}'") # Check if pattern already includes an extension if pattern.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.PNG', '.JPG', '.JPEG', '.BMP', '.TIFF')): # Pattern already has extension, use as-is image_paths.extend(Path(image_dir).glob(pattern)) logger.info(f"Using pattern with existing extension: {pattern}") else: # Pattern doesn't have extension, append supported formats for ext in self.supported_formats: glob_pattern = f"{pattern}{ext}" found_files = list(Path(image_dir).glob(glob_pattern)) image_paths.extend(found_files) logger.debug(f"Pattern '{glob_pattern}' found {len(found_files)} files") # Also check uppercase extensions glob_pattern_upper = f"{pattern}{ext.upper()}" found_files_upper = list(Path(image_dir).glob(glob_pattern_upper)) image_paths.extend(found_files_upper) logger.debug(f"Pattern '{glob_pattern_upper}' found {len(found_files_upper)} files") image_paths = [str(p) for p in sorted(image_paths)] logger.info(f"Total image files found: {len(image_paths)}") if not image_paths: raise ValueError(f"No image files found in {image_dir}") logger.info(f"Found {len(image_paths)} images in {image_dir}") return self.images_to_pdf(image_paths, output_path, sort_files=True, title=title) except Exception as e: logger.error(f"Failed to convert directory {image_dir} to PDF: {e}") raise
- pdf_utils.py:51-104 (helper)Helper method in PDFConverter that performs the actual image-to-PDF conversion using img2pdf.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
- server.py:372-383 (schema)Docstring defining the input parameters and output format for the directory_to_pdf tool.""" Convert all images in a directory to a PDF document. Args: image_dir: Directory containing images output_path: Path for the output PDF file title: Optional title for the PDF document pattern: File pattern to match (default: all files) Returns: JSON string with conversion results. """