dxfedit/03_Python_OpenSource_DXF/test_dxf_rw.py
2025-09-09 18:42:30 +08:00

122 lines
3.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import ezdxf
from ezdxf.enums import TextEntityAlignment
import os
# --- 配置 ---
# 输入文件路径使用之前Java代码生成的DXF文件
INPUT_DXF_PATH = os.path.join('..', '05_Reports', '图签测试.dxf')
# 输出文件路径
OUTPUT_DIR = '.'
OUTPUT_DXF_PATH = os.path.join(OUTPUT_DIR, '图签测试_modified.dxf')
# 确保输出目录存在
os.makedirs(OUTPUT_DIR, exist_ok=True)
def read_dxf_content(doc):
"""
读取并分析 DXF 文件内容
"""
print("\n--- 正在读取 DXF 文件内容 ---\n")
msp = doc.modelspace()
# 1. 查询所有的 LINE 实体
lines = msp.query('LINE')
print(f"文件中找到 {len(lines)} 条 LINE 实体。")
# 打印前5条线的坐标作为示例
for i, line in enumerate(lines[:5]):
start = line.dxf.start
end = line.dxf.end
print(f" - Line {i+1}: Start=({start.x:.2f}, {start.y:.2f}), End=({end.x:.2f}, {end.y:.2f})")
if len(lines) > 5:
print(" ...")
# 2. 查询所有的 TEXT 实体
texts = msp.query('TEXT')
print(f"\n文件中找到 {len(texts)} 条 TEXT 实体。")
# 打印前5个文本内容作为示例
for i, text in enumerate(texts[:5]):
content = text.dxf.text
pos = text.dxf.insert
print(f" - Text {i+1}: Position=({pos.x:.2f}, {pos.y:.2f}), Content='{content}'")
if len(texts) > 5:
print(" ...")
print("\n-------------------------------\n")
def write_new_entities_to_dxf(doc):
"""
向 DXF 文件中写入新的实体
"""
print("--- 正在向 DXF 文件写入新内容 ---\n")
msp = doc.modelspace()
# 1. 添加一条新的线
# 这条线将从 (0, 0) 连接到 (100, 100)
# 使用红色 (color=1) 和虚线 (linetype='DASHED') 以便区分
line_attributes = {
'start': (0, 0),
'end': (100, 100),
'color': 1, # 1 = Red
'linetype': 'DASHED',
}
msp.add_line(**line_attributes)
print("成功添加一条新的红色虚线: 从 (0, 0) 到 (100, 100)。")
# 2. 添加一个新的文本标签
# 放置在 (100, 105) 位置
text_attributes = {
'text': '你好, ezdxf!',
'height': 5, # 字体高度
'insert': (100, 105),
'dxf': {
'color': 3, # 3 = Green
}
}
# 设置对齐方式
text = msp.add_text(text_attributes['text'], dxfattribs=text_attributes['dxf'])
text.set_placement(text_attributes['insert'], align=TextEntityAlignment.BOTTOM_LEFT)
text.dxf.height = text_attributes['height']
print("成功添加一个新的绿色文本: '你好, ezdxf!' at (100, 105)。")
print("\n---------------------------------\n")
def main():
"""
主函数:加载、读取、写入并保存 DXF 文件
"""
# 检查输入文件是否存在
if not os.path.exists(INPUT_DXF_PATH):
print(f"错误: 输入的 DXF 文件未找到: '{INPUT_DXF_PATH}'")
print("请确保 '05_Reports' 文件夹中存在由 Java 代码生成的 '图签测试.dxf' 文件。")
return
try:
# 1. 加载 DXF 文件
print(f"正在加载 DXF 文件: '{INPUT_DXF_PATH}'...")
doc = ezdxf.readfile(INPUT_DXF_PATH)
print("文件加载成功!")
# 2. 读取和分析文件内容
read_dxf_content(doc)
# 3. 写入新的实体
write_new_entities_to_dxf(doc)
# 4. 保存为新文件
print(f"正在保存修改后的 DXF 文件到: '{OUTPUT_DXF_PATH}'...")
doc.saveas(OUTPUT_DXF_PATH)
print("文件保存成功!")
print(f"\n测试完成。请在 AutoCAD 或兼容的查看器中打开 '{OUTPUT_DXF_PATH}' 来验证修改。")
except IOError:
print(f"错误: 无法读取或写入文件。请检查文件权限和路径。")
except ezdxf.DXFStructureError as e:
print(f"错误: DXF 文件结构损坏或格式不支持: {e}")
if __name__ == '__main__':
main()