使用netdxf(C#)框架实现dxf文件读取与导出坐标

使用netdxf(C#)框架实现dxf文件读取与导出坐标

一、新建窗体应用程序DxfToolDemo,将默认的Form1重命名为FormDxfTool

窗体FormDxfTool.Designer.cs设计器源程序如下:


namespace DxfToolDemo
{partial class FormDxfTool{/// <summary>/// 必需的设计器变量。/// </summary>private System.ComponentModel.IContainer components = null;/// <summary>/// 清理所有正在使用的资源。/// </summary>/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}#region Windows 窗体设计器生成的代码/// <summary>/// 设计器支持所需的方法 - 不要修改/// 使用代码编辑器修改此方法的内容。/// </summary>private void InitializeComponent(){this.rtxtMessage = new System.Windows.Forms.RichTextBox();this.btnOpenDxf = new System.Windows.Forms.Button();this.btnExportCsv = new System.Windows.Forms.Button();this.SuspendLayout();// // rtxtMessage// this.rtxtMessage.Location = new System.Drawing.Point(12, 70);this.rtxtMessage.Name = "rtxtMessage";this.rtxtMessage.Size = new System.Drawing.Size(1102, 529);this.rtxtMessage.TabIndex = 0;this.rtxtMessage.Text = "";// // btnOpenDxf// this.btnOpenDxf.Font = new System.Drawing.Font("宋体", 15F);this.btnOpenDxf.Location = new System.Drawing.Point(23, 12);this.btnOpenDxf.Name = "btnOpenDxf";this.btnOpenDxf.Size = new System.Drawing.Size(127, 43);this.btnOpenDxf.TabIndex = 1;this.btnOpenDxf.Text = "打开Dxf文件";this.btnOpenDxf.UseVisualStyleBackColor = true;this.btnOpenDxf.Click += new System.EventHandler(this.btnOpenDxf_Click);// // btnExportCsv// this.btnExportCsv.Font = new System.Drawing.Font("宋体", 15F);this.btnExportCsv.Location = new System.Drawing.Point(185, 12);this.btnExportCsv.Name = "btnExportCsv";this.btnExportCsv.Size = new System.Drawing.Size(182, 43);this.btnExportCsv.TabIndex = 2;this.btnExportCsv.Text = "导出坐标为.CSV";this.btnExportCsv.UseVisualStyleBackColor = true;this.btnExportCsv.Click += new System.EventHandler(this.btnExportCsv_Click);// // FormDxfTool// this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.ClientSize = new System.Drawing.Size(1126, 611);this.Controls.Add(this.btnExportCsv);this.Controls.Add(this.btnOpenDxf);this.Controls.Add(this.rtxtMessage);this.Name = "FormDxfTool";this.Text = "Dxf转化工具【CAD文件转坐标】";this.Load += new System.EventHandler(this.FormDxfTool_Load);this.ResumeLayout(false);}#endregionprivate System.Windows.Forms.RichTextBox rtxtMessage;private System.Windows.Forms.Button btnOpenDxf;private System.Windows.Forms.Button btnExportCsv;}
}

二、右键 项目DxfToolDemo, 管理NuGet程序包,输入关键字netDxf,下载该程序包

三、netDxf框架关键类型说明:

关键结构 netDxf.Vector3
            可以认为是立体三维坐标(x,y,z)
关键结构 netDxf.Vector2
            可以认为是平面二维坐标(x,y)

DxfDocument用于读写dxf文件

      关键函数Load()用于加载文件

      添加实体:dxfDocument.Entities.Add(EntityObject entity);

      关键函数Save()用于保存文件 

关键属性:
Entities:

对应类型 netDxf.Collections.DrawingEntities

密封类DrawingEntities由一系列【点、线、圆等】集合组成,允许直接访问与图形中实体相关的操作

对应的各种实体EntityObject说明:
netDxf.Entities.EntityObject:
        Gets the complete list entities contained in the active layout.
        抽象类,以下所有实体对象的父类

netDxf.Entities.PolyfaceMesh:
    Represents a polyface mesh entity.

netDxf.Entities.Text:
    Gets the list of texts in the active layout.
           
 netDxf.Entities.MText:       
     Gets the list of multiline texts in the active layout.

 netDxf.Entities.Hatch:       
     Gets the list of hatches in the active layout.

 netDxf.Entities.Image:     
     Gets the list of images in the active layout.
 
netDxf.Entities.Mesh:      
        Gets the list of mesh in the active layout.
 
netDxf.Entities.Leader:        
        Gets the list of leader in the active layout.
             
netDxf.Entities.Point:
        Gets the list of points in the active layout.
        
netDxf.Entities.Tolerance:
        Gets the list of tolerance in the active layout.
        
netDxf.Entities.MLine:
        Gets the list of multilines in the active layout.
        
netDxf.Entities.Dimension:
        Gets the list of dimensions in the active layout.
        
netDxf.Entities.Spline:
        Gets the list of splines in the active layout.
         
netDxf.Entities.Ray:
        Gets the list of rays in the active layout.

netDxf.Entities.Viewport:        
        Gets the list of viewports in the active layout.

netDxf.Entities.XLine:
        Gets the list of extension lines in the active layout.
        
netDxf.Entities.Underlay:
        Gets the list of underlay in the active layout.
       
netDxf.Entities.PolygonMesh:
        Gets the list of polygon meshes in the active layout.

netDxf.Entities.AttributeDefinition:
        Gets the list of attribute definitions in the active layout.

netDxf.Entities.Polyline3D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Arc:
        Gets the list of arcs contained in the active layout. 

netDxf.Entities.Ellipse:
        Gets the list of ellipses in the active layout.

netDxf.Entities.Wipeout:
        Gets the list of wipeouts in the active layout. 

netDxf.Entities.Face3D:
        Gets the list of 3d faces in the active layout.

netDxf.Entities.Circle:
        Gets the list of circles in the active layout.

netDxf.Entities.Trace:
        Gets the list of traces in the active layout.

netDxf.Entities.Insert:
        Gets the list of inserts in the active layout.

netDxf.Entities.Line:
        Gets the list of lines in the active layout.

netDxf.Entities.Shape:
        Gets the list of shapes in the active layout.

netDxf.Entities.Polyline2D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Solid:
        Gets the list of solids in the active layout.

四、新建csv导出类CsvUtil,

CsvUtil.cs源程序如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DxfToolDemo
{public class CsvUtil{/// <summary>/// 写CSV日志 按列显示/// </summary>/// <param name="fileName"></param>/// <param name="coordList">元组:圆心坐标,半径,模板名</param>/// <returns></returns>public static bool WriteCoordinateLogCsv(string fileName, List<Tuple<netDxf.Vector3, double, string>> coordList){if (coordList == null || coordList.Count == 0) {return false;}try{string directoryPath = Path.GetDirectoryName(fileName);if (!Directory.Exists(directoryPath)){Directory.CreateDirectory(directoryPath);}string columnContents = "模板名,极柱序号,圆心X坐标,圆心Y坐标,圆心Z坐标,圆心半径\r\n";if (!File.Exists(fileName)){File.AppendAllText(fileName, columnContents, Encoding.Default);}StringBuilder sb = new StringBuilder();using (StreamWriter write = new StreamWriter(fileName, true, Encoding.Default)){for (int i = 0; i < coordList.Count; i++){sb = new StringBuilder();sb.Append($"{ProcessPunctuationForCsv(coordList[i].Item3)},");sb.Append($"{i + 1},");sb.Append($"{coordList[i].Item1.X},");sb.Append($"{coordList[i].Item1.Y},");sb.Append($"{coordList[i].Item1.Z},");sb.Append($"{coordList[i].Item2}");write.WriteLine(sb.ToString());}                    }return true;}catch (Exception ex){System.Windows.Forms.MessageBox.Show("CSV文件写入失败:" + ex.Message);return false;}}/// <summary>/// 处理csv文件中的双引号和逗号,使其在Excel中完美显示为一个单元格/// 斯内科/// </summary>/// <param name="srcStr"></param>/// <returns></returns>private static string ProcessPunctuationForCsv(string srcStr){if (srcStr == null){return string.Empty;}bool quoteFlag = false;//是否添加过双引号//如果存在双引号,需要将字符串的一个双引号 替换为 两个双引号。并且需要在字符串的前后加上双引号if (srcStr.Contains("\"")){srcStr = srcStr.Replace("\"", "\"\"");srcStr = "\"" + srcStr + "\"";quoteFlag = true;}//如果只存在逗号(不存在引号),将前后加引号即可if (srcStr.Contains(",") && !quoteFlag){srcStr = "\"" + srcStr + "\"";}return srcStr;}}
}

五、窗体程序如下:

FormDxfTool.cs源程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using netDxf;
using netDxf.Collections;
using netDxf.Entities;namespace DxfToolDemo
{public partial class FormDxfTool : Form{public FormDxfTool(){InitializeComponent();rtxtMessage.ReadOnly = true;            }/// <summary>/// 显示推送消息/// </summary>/// <param name="msg"></param>private void DisplayMessage(string msg){this.BeginInvoke(new Action(() =>{if (rtxtMessage.TextLength > 20480){rtxtMessage.Clear(); }rtxtMessage.AppendText($"{DateTime.Now.ToString("HH:mm:ss.fff")}->{msg}\n");rtxtMessage.ScrollToCaret();}));}private void btnOpenDxf_Click(object sender, EventArgs e){rtxtMessage.Clear();OpenFileDialog openFileDialog = new OpenFileDialog();openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;openFileDialog.Filter = "dxf|*.dxf|All|*.*";DialogResult dialog = openFileDialog.ShowDialog();if (dialog != DialogResult.OK){return;}string fileName = openFileDialog.FileName;//AppDomain.CurrentDomain.BaseDirectory + "testFile\\蓝本-CAD.dxf"DisplayMessage($"CAD文件dxf路径为【{fileName}】");DxfDocument dxfDocument = DxfDocument.Load(fileName);DisplayMessage($"活动布局的名称为【{dxfDocument.Entities.ActiveLayout}】");rtxtMessage.Tag = dxfDocument.Entities;IEnumerable<Circle> circles = dxfDocument.Entities.Circles;int circleCount = circles.Count();DisplayMessage($"读取到圆Circle的个数为【{circleCount}】");for (int i = 0; i < circleCount; i++){Circle circle = circles.ElementAt(i);DisplayMessage($"\x20\x20圆【{(i + 1).ToString("D3")}】,圆心坐标【({circle.Center})】,半径【{circle.Radius}】");}            }private void btnExportCsv_Click(object sender, EventArgs e){DrawingEntities drawingEntities = rtxtMessage.Tag as DrawingEntities;if (drawingEntities == null) {return;}List<Tuple<Vector3, double, string>> coordList = new List<Tuple<Vector3, double, string>>();IEnumerable<Circle> circles = drawingEntities.Circles;int circleCount = circles.Count();//找出所有的圆for (int i = 0; i < circleCount; i++){Circle circle = circles.ElementAt(i);//元组:圆心坐标,半径,活动设计名coordList.Add(Tuple.Create(circle.Center, circle.Radius, drawingEntities.ActiveLayout));}string fileName = AppDomain.CurrentDomain.BaseDirectory + "testFile\\蓝本.csv";bool result = CsvUtil.WriteCoordinateLogCsv(fileName, coordList);MessageBox.Show($"导出csv文件结果【{result}】\n路径:{fileName}");}private void FormDxfTool_Load(object sender, EventArgs e){/** 1、读取dxf文件的思路
新建DxfDocument对象-调用Load方法读取对应地址的dxf文件并保存在新建的DxfDocument对象中-从新建的DxfDocument对象中读取对应的元素
读取dxf文件:
DxfDocument dxf = DxfDocument.Load("蓝本.dxf");关键结构 netDxf.Vector3可以认为是立体三维坐标(x,y,z)
关键结构 netDxf.Vector2可以认为是平面二维坐标(x,y)读取文件中的核心属性:
Entities:
对应类型 netDxf.Collections.DrawingEntities密封类DrawingEntities由一系列【点、线、圆等】集合组成,允许直接访问与图形中实体相关的操作
netDxf.Entities.EntityObject:Gets the complete list entities contained in the active layout.抽象类,以下所有实体对象的父类netDxf.Entities.PolyfaceMesh:Represents a polyface mesh entity.netDxf.Entities.Text:Gets the list of texts in the active layout.netDxf.Entities.MText:       Gets the list of multiline texts in the active layout.netDxf.Entities.Hatch:       Gets the list of hatches in the active layout.netDxf.Entities.Image:     Gets the list of images in the active layout.netDxf.Entities.Mesh:      Gets the list of mesh in the active layout.netDxf.Entities.Leader:        Gets the list of leader in the active layout.netDxf.Entities.Point:Gets the list of points in the active layout.netDxf.Entities.Tolerance:Gets the list of tolerance in the active layout.netDxf.Entities.MLine:Gets the list of multilines in the active layout.netDxf.Entities.Dimension:Gets the list of dimensions in the active layout.netDxf.Entities.Spline:Gets the list of splines in the active layout.netDxf.Entities.Ray:Gets the list of rays in the active layout.netDxf.Entities.Viewport:        Gets the list of viewports in the active layout.netDxf.Entities.XLine:Gets the list of extension lines in the active layout.netDxf.Entities.Underlay:Gets the list of underlay in the active layout.netDxf.Entities.PolygonMesh:Gets the list of polygon meshes in the active layout.netDxf.Entities.AttributeDefinition:Gets the list of attribute definitions in the active layout.netDxf.Entities.Polyline3D:Gets the list of polylines in the active layout.netDxf.Entities.Arc:Gets the list of arcs contained in the active layout. netDxf.Entities.Ellipse:Gets the list of ellipses in the active layout.netDxf.Entities.Wipeout:Gets the list of wipeouts in the active layout. netDxf.Entities.Face3D:Gets the list of 3d faces in the active layout.netDxf.Entities.Circle:Gets the list of circles in the active layout.netDxf.Entities.Trace:Gets the list of traces in the active layout.netDxf.Entities.Insert:Gets the list of inserts in the active layout.netDxf.Entities.Line:Gets the list of lines in the active layout.netDxf.Entities.Shape:Gets the list of shapes in the active layout.netDxf.Entities.Polyline2D:Gets the list of polylines in the active layout.netDxf.Entities.Solid:Gets the list of solids in the active layout.            */}}
}

六、运行效果如图:

【获取所有半径为3的圆极柱】

导出csv

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/627313.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

x-cmd pkg | magic-wormhole - (魔法虫洞)文件传输工具

目录 简介首次用户功能特点竞品和相关作品进一步探索 简介 magic-wormhole 是一个用于在两台计算机之间安全传输文件的工具。它通过创建一个临时的点对点连接&#xff0c;允许用户将文件或文本从一台计算机发送到另一台计算机。 它使用 PAKE 这一系列的加密算法&#xff0c;通…

扫地机行业研究:预计2028年将达到78.51亿美元

吸尘器、扫地机器人、洗地机为清洁电器中最亮眼的三大品类。吸尘器主要用来吸尘&#xff0c;扫地机的主要作用也是用于除尘&#xff0c;具备扫拖一体功能的扫地机&#xff0c;干湿混合垃圾暂时做不到干净清理。洗地机集齐了“吸、拖、洗”三种功能为一体&#xff0c;并且具备自…

消息队列-RockMQ-定时延时发送消息

定时延时发送消息 任务需要延迟一段时间再进行处理。 生产者 public class Producer {public static void main(String[] args) throws Exception {DefaultMQProducer producer new DefaultMQProducer("producer_group");producer.setNamesrvAddr("ip:9876&q…

【Python 数据分析】数据预处理:z-score 标准化、min-max 归一化、数据缺失值处理、数据重复处理

目录 简述 / 前言1. z-score 标准化2. min-max 归一化3. 数据缺失值处理4. 数据重复处理 简述 / 前言 本篇文章分享数据分析中最重要的一个步骤&#xff1a;数据预处理。我们在做数据分析之前&#xff0c;都需要采集很多数据&#xff0c;这些数据可能是从官网下载的&#xff0…

【docker-compose】【nginx】内网环境https配置

目录 1、openssl生成自签名证书和私钥2、nginx.conf配置ssl3、docker-compose挂载 1、openssl生成自签名证书和私钥 在部署服务器上&#xff0c;新建cert目录&#xff0c;执行以下指令&#xff0c;然后生成.crt和.key文件 openssl req -newkey rsa:2048 -nodes -keyout rsa_pri…

linux yum仓库

yum是基于rpm包构建的软件更新机制&#xff0c;能够自动解决软件包之间的依赖关系。 常用命令 查询 yum list [软件名] 显示可用的安装包&#xff0c;如果不加软件名则显示所有的可用包 yum info [软件名] 显示安装包的详细信息 如果不加软件名是显示所有包…

2024年【上海市安全员B证】考试试卷及上海市安全员B证复审模拟考试

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 上海市安全员B证考试试卷根据新上海市安全员B证考试大纲要求&#xff0c;安全生产模拟考试一点通将上海市安全员B证模拟考试试题进行汇编&#xff0c;组成一套上海市安全员B证全真模拟考试试题&#xff0c;学员可通过…

海外短剧APP小程序开发 随心随意畅享大片

随着智能手机的普及和网络的高速发展&#xff0c;短剧APP已经成为当今热门的观影方式。作为一种全新的观影体验&#xff0c;海外短剧APP以其丰富多样的内容吸引了大量用户。本文将为您介绍海外短剧APP开发的相关知识和其所带来的优势&#xff0c;以及市场前景和发展趋势。 海外…

jsonschema,一个超强的 Python 库!

更多资料获取 &#x1f4da; 个人网站&#xff1a;ipengtao.com 大家好&#xff0c;今天为大家分享一个超强的 Python 库 - jsonschema。 Github地址&#xff1a;https://github.com/python-jsonschema/jsonschema JSON&#xff08;JavaScript Object Notation&#xff09;是…

MySQL 多版本并发控制 MVCC

MVCC出现背景 事务的4个隔离级别以及对应的三种异常 读未提交&#xff08;Read uncommitted&#xff09; 读已提交&#xff08;Read committed&#xff09;&#xff1a;脏读 可重复读&#xff08;Repeatable read&#xff09;&#xff1a;不可重复读 串行化&#xff08;Se…

.NET领域最硬核的gRPC 核心能力一把梭

前言&#xff0c;本文定位为.NET方向 grpc核心能力一把梭&#xff0c;全篇是姿势性和结论性的展示&#xff0c; 方便中高级程序员快速上手.NET Grpc。 有关grpc更深层次的前世今生、底层原理、困惑点释疑请听下回分解&#xff0c; 欢迎菜鸟老鸟们提出宝贵意见。 grpc宏观目标&…

跨平台进程/任务管理服务——Meproc的配置

配置 Meproc的配置非常简单&#xff0c;只有以下几个配置选项。 Conf [ip: 0.0.0.0,port: 8606,log_level: debug,log_dir: /tmp,web: [ip: 127.0.0.1,port: 8606,],bootstrap_cmd: , ];ip 是 Meproc 服务监听 HTTP 请求的地址。port 是Meproc服务监听HTTP请求的端口。log_l…

「Vue3面试系列」Vue 3.0中如果想实现一个 Modal组件应该怎么设计?

文章目录 一、组件设计二、需求分析三、实现流程目录结构组件内容实现 API 形式事件处理其他完善 一、组件设计 组件就是把图形、非图形的各种逻辑均抽象为一个统一的概念&#xff08;组件&#xff09;来实现开发的模式 现在有一个场景&#xff0c;点击新增与编辑都弹框出来进…

51单片机学习总结(自学)

1、模块化编程 c语言模块化编程实现思路设计代码 具体的程序实现代码如下所示 1&#xff1a;程序的头文件 2&#xff1a;程序的函数文件 3&#xff1a;程序的主文件控制函数的实现 持续更新中......

用el-image-viewer实现全局预览图片

背景 在后台管理系统中&#xff0c;一些预览图片的场景&#xff0c;通常都是使用 el-image-viewer 去实现&#xff0c;但是如果多个地方都需要预览图片&#xff0c;又要重复的去写 el-image-viewer 以及一些重复的和预览相关的代码。 可以把预览图片的组件放在根文件&#x…

MyTinySTL 简单分析(一)--iterator.h

MyTinySTL 简单分析 目前在学习STL&#xff0c;看到一个开源的项目MyTinySTL&#xff0c;非常不错。想着照着这个代码自己敲一遍应该也能有些进步。然后就开始了学习过程。 首先分析的是vector 以下是由vector.h关联的所有头文件 其中有几个文件是重复的&#xff0c;例如type…

智能光栅光片显微成像技术的LabVIEW解决方案

智能光栅光片显微成像技术的LabVIEW解决方案 在生物医学研究中&#xff0c;高效的成像技术对于捕捉细胞内罕见和复杂事件至关重要。智能光栅光片显微技术&#xff08;smartLLSM&#xff09;的出现&#xff0c;代表了LabVIEW软件在高端成像领域的革命性应用&#xff0c;这项技术…

solr 远程命令执行漏洞复现 (CVE-2019-17558)

solr 远程命令执行漏洞复现 (CVE-2019-17558) ‍ 名称: solr 远程命令执行 (CVE-2019-17558) 描述: Apache Velocity是一个基于Java的模板引擎&#xff0c;它提供了一个模板语言去引用由Java代码定义的对象。Velocity是Apache基金会旗下的一个开源软件项目&#xff0c;旨在确…

Qt 快捷键设置

以 “在编辑时自动补齐”快捷键 为例&#xff1a; 位置&#xff1a;红色 搜索快捷键&#xff1a;蓝色 修改方式&#xff1a;绿色 快捷键&#xff1a;黄色

22k+star炒鸡好用的开源的网盘神器FileBrowser Docker自建个人网盘神器教程

目录 简介 1.拉取镜像 2.创建并启动容器 2.1创建目录 2.2启初始化一个容器用于导出配置文件和数据库&#xff0c;只挂载数据目录 2.3先将数据库文件和配置文件复制出来 2.4停止容器并删除容器 2.5创建完整的容器 3.愉快地使用 3.1示例&#xff1a; 3.2图片预览 3.3json…