diff --git a/python/kicad_interface.py b/python/kicad_interface.py index d892640..b019cd8 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -600,6 +600,7 @@ class KiCADInterface: "export_gerber_single": self._handle_export_gerber_single, "export_3d_cli": self._handle_export_3d_cli, "export_sch_bom": self._handle_export_sch_bom, + "export_sch_pdf": self._handle_export_sch_pdf, "generate_netlist": self._handle_generate_netlist, "sync_schematic_to_board": self._handle_sync_schematic_to_board, "list_schematic_libraries": self._handle_list_schematic_libraries, @@ -5667,6 +5668,87 @@ class KiCADInterface: logger.error(f"Error exporting schematic BOM: {e}") return {"success": False, "message": str(e)} + def _handle_export_sch_pdf(self, params: Dict[str, Any]) -> Dict[str, Any]: + """Export a schematic to PDF via kicad-cli (`sch export pdf`). + + Exposes the full option set: drawing-sheet override, theme, B&W, + exclude-drawing-sheet, default-font, the PDF popup/link/metadata + excludes, no-background-color, and page selection. schematicPath is + required. + """ + import subprocess + + logger.info("Exporting schematic PDF via kicad-cli") + try: + schematic_path = params.get("schematicPath") + output_path = params.get("outputPath") + + if not schematic_path: + return {"success": False, "message": "schematicPath is required"} + if not os.path.exists(schematic_path): + return {"success": False, "message": f"Schematic not found: {schematic_path}"} + if not output_path: + return {"success": False, "message": "outputPath is required"} + + kicad_cli = self._find_kicad_cli_static() + if not kicad_cli: + return {"success": False, "message": "kicad-cli not found in PATH"} + + output_path = os.path.abspath(os.path.expanduser(output_path)) + parent = os.path.dirname(output_path) + if parent: + os.makedirs(parent, exist_ok=True) + + cmd = [kicad_cli, "sch", "export", "pdf", "--output", output_path] + + if params.get("drawingSheet"): + cmd += ["--drawing-sheet", params["drawingSheet"]] + for kv in params.get("defineVar", []) or []: + cmd += ["--define-var", kv] + + value_map = { + "theme": "--theme", + "defaultFont": "--default-font", + "pages": "--pages", + } + for key, flag in value_map.items(): + val = params.get(key) + if val is not None and val != "": + cmd += [flag, str(val)] + + flag_map = { + "blackAndWhite": "--black-and-white", + "excludeDrawingSheet": "--exclude-drawing-sheet", + "excludePdfPropertyPopups": "--exclude-pdf-property-popups", + "excludePdfHierarchicalLinks": "--exclude-pdf-hierarchical-links", + "excludePdfMetadata": "--exclude-pdf-metadata", + "noBackgroundColor": "--no-background-color", + } + for key, flag in flag_map.items(): + if params.get(key): + cmd.append(flag) + + cmd.append(schematic_path) + + logger.info(f"Running: {' '.join(cmd)}") + result = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + + if result.returncode != 0: + return { + "success": False, + "message": f"kicad-cli failed (exit {result.returncode}): " + f"{result.stderr.strip()}", + } + return {"success": True, "outputPath": output_path} + + except FileNotFoundError: + return {"success": False, "message": "kicad-cli not found in PATH"} + except subprocess.TimeoutExpired: + return {"success": False, "message": "kicad-cli timed out after 180 seconds"} + except Exception as e: + logger.error(f"Error exporting schematic PDF: {e}") + return {"success": False, "message": str(e)} + def _handle_generate_netlist(self, params: Dict[str, Any]) -> Dict[str, Any]: """Generate netlist from schematic and return structured JSON. diff --git a/src/tools/export.ts b/src/tools/export.ts index d1364e9..9653081 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -1106,5 +1106,58 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF }, ); + // ------------------------------------------------------ + // Export Schematic PDF Tool (kicad-cli, full option set) + // ------------------------------------------------------ + server.tool( + "export_sch_pdf", + "Export a schematic to PDF via kicad-cli (`sch export pdf`), exposing the full option set (drawing-sheet override, theme, black-and-white, exclude-drawing-sheet, default-font, the PDF property-popup / hierarchical-link / metadata excludes, no-background-color, and page selection). schematicPath is REQUIRED.", + { + schematicPath: z.string().describe("Path to the .kicad_sch (required)"), + outputPath: z.string().describe("Output PDF file path"), + drawingSheet: z.string().optional().describe("Path to a drawing sheet override"), + defineVar: z + .array(z.string()) + .optional() + .describe("Project variable overrides as 'KEY=VALUE' strings"), + theme: z.string().optional().describe("Color theme to use (default: schematic settings)"), + blackAndWhite: z.boolean().optional().describe("Black and white only"), + excludeDrawingSheet: z.boolean().optional().describe("No drawing sheet"), + defaultFont: z.string().optional().describe("Default font name"), + excludePdfPropertyPopups: z + .boolean() + .optional() + .describe("Do not generate property popups in PDF"), + excludePdfHierarchicalLinks: z + .boolean() + .optional() + .describe("Do not generate clickable links for hierarchical elements in PDF"), + excludePdfMetadata: z + .boolean() + .optional() + .describe("Do not generate PDF metadata from AUTHOR and SUBJECT variables"), + noBackgroundColor: z + .boolean() + .optional() + .describe("Avoid setting a background color (regardless of theme)"), + pages: z + .string() + .optional() + .describe("Comma list of page numbers to print (blank = all pages)"), + }, + async (args) => { + logger.debug(`Exporting schematic PDF to: ${args.outputPath}`); + const result = await callKicadScript("export_sch_pdf", args); + return { + content: [ + { + type: "text", + text: JSON.stringify(result), + }, + ], + }; + }, + ); + logger.info("Export tools registered"); } diff --git a/src/tools/registry.ts b/src/tools/registry.ts index f04a979..0ff3617 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -71,6 +71,7 @@ export const toolCategories: ToolCategory[] = [ "export_gerber_single", "export_3d_cli", "export_sch_bom", + "export_sch_pdf", "export_pdf", "export_svg", "export_3d",