mxGraph XML 生成器 使用示例: generator = MxGraphXMLGenerator() cell = generator.create_text_cell("Hello", 100, 200, 80, 20, 12) generator.save_to_file([cell], "output.drawio")
| 65 | |
| 66 | |
| 67 | class MxGraphXMLGenerator: |
| 68 | """ |
| 69 | mxGraph XML 生成器 |
| 70 | |
| 71 | 使用示例: |
| 72 | generator = MxGraphXMLGenerator() |
| 73 | cell = generator.create_text_cell("Hello", 100, 200, 80, 20, 12) |
| 74 | generator.save_to_file([cell], "output.drawio") |
| 75 | """ |
| 76 | |
| 77 | def __init__(self, diagram_name: str = "Page-1", |
| 78 | page_width: int = 1169, page_height: int = 827): |
| 79 | """ |
| 80 | 初始化生成器 |
| 81 | |
| 82 | Args: |
| 83 | diagram_name: 图表名称 |
| 84 | page_width: 页面宽度 |
| 85 | page_height: 页面高度 |
| 86 | """ |
| 87 | self.diagram_name = diagram_name |
| 88 | self.page_width = page_width |
| 89 | self.page_height = page_height |
| 90 | self.next_id = 2 # ID 从 2 开始(0 和 1 被根节点和图层占用) |
| 91 | |
| 92 | def _get_next_id(self) -> int: |
| 93 | """获取下一个可用 ID""" |
| 94 | current_id = self.next_id |
| 95 | self.next_id += 1 |
| 96 | return current_id |
| 97 | |
| 98 | def _build_style_string(self, cell_data: TextCellData) -> str: |
| 99 | """ |
| 100 | 构建 mxCell 样式字符串 |
| 101 | |
| 102 | draw.io 使用分号分隔的键值对表示样式: |
| 103 | style="text;fontSize=12;fontStyle=1;fontColor=#000000;" |
| 104 | """ |
| 105 | styles = [ |
| 106 | "text", "html=1", "whiteSpace=nowrap", "autosize=1", "resizable=0", |
| 107 | f"fontSize={int(cell_data.font_size)}", "align=center", |
| 108 | "verticalAlign=middle", "overflow=visible", |
| 109 | ] |
| 110 | |
| 111 | # 字体样式:1=粗体, 2=斜体, 3=粗斜体 |
| 112 | font_style_value = 0 |
| 113 | if cell_data.font_weight == 'bold': |
| 114 | font_style_value += 1 |
| 115 | if cell_data.font_style == 'italic': |
| 116 | font_style_value += 2 |
| 117 | if font_style_value > 0: |
| 118 | styles.append(f"fontStyle={font_style_value}") |
| 119 | |
| 120 | # 字体颜色 |
| 121 | if cell_data.font_color: |
| 122 | styles.append(f"fontColor={cell_data.font_color}") |
| 123 | |
| 124 | # 字体名称 |