NX二次开发 批量导出图纸 合并DWG

2023-10-19 00:50

本文主要是介绍NX二次开发 批量导出图纸 合并DWG,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

NXOpen入口

   class Program{static void Main(string[] args){try{//Console.ReadKey(true);Console.BackgroundColor = ConsoleColor.DarkGray;Console.ForegroundColor = ConsoleColor.DarkMagenta;Console.Clear();Console.Title = "导出CAD图纸";string filePath = "";foreach (string arg in args){filePath = filePath + arg + " ";}filePath = filePath.Trim();CombineSheetManager manager = string.IsNullOrWhiteSpace(filePath)? new CombineSheetManager(): new CombineSheetManager(filePath);manager.Commit();}catch (System.Exception ex){if (!string.IsNullOrWhiteSpace(ex.Source)){Console.WriteLine(ex.Source);}Console.WriteLine(ex);}Console.ReadKey();}}

主要类:导出 合并

    public class CombineSheetManager : BaseCombineManager, IEnumerable<CombineSheet>{private readonly List<CombineSheet> mList;public CombineSheetManager(string filePath){var lines = ReadAllLines(filePath).ToList();if (lines.Count < 3){throw new System.Exception($"工作包文件格式错误。\r\n{filePath}");}this.BaseDirectory = lines[0];this.InputPart = lines[1];this.OutputFile = lines[2];this.mList = lines.Skip(3).Select(p => new CombineSheet(this, p)).ToList();if (this.mList.Count == 0){throw new System.Exception($"工作包文件没有指定导出图纸。\r\n{filePath}");}//赋序号int i = 0;foreach (var combineSheet in this.mList){combineSheet.Id = ++i;}//查找Root目录var rootDir = this.BaseDirectory.GetSubFolder("NXBIN");if (rootDir == null || !rootDir.Exists){rootDir = this.BaseDirectory.GetSubFolder("UGII");if (rootDir == null || !rootDir.Exists){throw new System.Exception($"当前{this.BaseDirectory}程序安装不完整。");}}this.RootDirectory = rootDir;//配置表var ugTo2dDef = this.CurrentDirectory.GetFile("ugto2d.def");this.SettingTable = new SettingTable(ugTo2dDef);}public CombineSheetManager():this(OpenPackage()){}private static string OpenPackage(){Console.WriteLine("请输入工作包文件路径:");return Console.ReadLine();//var openFile = new System.Windows.Forms.OpenFileDialog();//openFile.Multiselect = false;//openFile.Filter = "Package Files(*.package)|*.package|All Files(*.*)|*.*";//openFile.CheckPathExists = true;//var result = openFile.ShowDialog();//string fileName = "";//if (result == System.Windows.Forms.DialogResult.OK)//{//    fileName = openFile.FileName;//}//openFile.Dispose();//return fileName;}public FolderPathInfo BaseDirectory { get; }public FilePathInfo InputPart { get; set; }public FilePathInfo OutputFile { get; set; }public FolderPathInfo RootDirectory { get; }public SettingTable SettingTable { get; }private IEnumerable<string> ReadAllLines(string filePath){bool isDeleteFile = true;if (string.IsNullOrWhiteSpace(filePath)){filePath = $"{base.Name}.package";isDeleteFile = false;}if (filePath.IndexOf('\\') < 0){filePath = base.CurrentDirectory.GetFile(filePath);isDeleteFile = false;}if (!System.IO.File.Exists(filePath)){yield break;}var lines = System.IO.File.ReadAllLines(filePath);if (isDeleteFile){System.IO.File.Delete(filePath);}foreach (var line in lines){if (string.IsNullOrWhiteSpace(line)) continue;if (line.StartsWith("!")||line.StartsWith("#")){continue;}yield return line;}}public FilePathInfo GetOutputTempFile(string fileName, bool deleteFile = true){var filePathInfo = this.OutputFile.Directory.GetFile(fileName);if (filePathInfo?.Exists == true){if (!deleteFile){filePathInfo.CopyToBak();}filePathInfo.Delete();}return filePathInfo;}public FilePathInfo GetFrameFile(CombineSheet sheet){if (sheet == null) return null;var folder = this.UserDirectory.GetSubFolder(@"Config\DrawingTemplate");if (!string.IsNullOrWhiteSpace(sheet.FrameCategory)){folder = folder.GetSubFolder(sheet.FrameCategory);}if (!string.IsNullOrWhiteSpace(sheet.FrameName)){return folder.GetFile(sheet.FrameName + ".dwg");}return null;}public void Commit(){try{this.PrintMessage("----------------------------------------------------");this.PrintMessage("图纸导出开始:");this.OnExport();this.PrintMessage("图纸导出完成。");this.PrintMessage("");this.PrintMessage("----------------------------------------------------");this.PrintMessage("图纸合并开始:");this.OnCombine();this.PrintMessage("图纸合并完成。");this.PrintMessage("");}finally{OnClearFile();}}private void OnExport(){var ugTo2dExe = this.BaseDirectory.GetFile(@"UGTO2D\ugto2d.exe");var dxfDwgExe = this.BaseDirectory.GetFile(@"DXFDWG\dxfdwg.exe");var dxfDwgDefine = this.CurrentDirectory.GetFile("dxfdwg.def");if (!dxfDwgDefine.Exists){dxfDwgDefine = this.BaseDirectory.GetFile(@"DXFDWG\dxfdwg.def");}if (!ugTo2dExe.Exists ||!dxfDwgExe.Exists ||!dxfDwgDefine.Exists){throw new System.Exception($"当前{this.BaseDirectory}程序安装不完整。");}if (this.OutputFile?.Directory?.Exists != true){throw new System.Exception($"输出路径不正确。\r\n{this.OutputFile}");}var logFile = this.OutputFile.ChangeExtension(".log");this.SettingTable.InputPartsList = this.InputPart;this.SettingTable.LogFile = logFile;foreach (CombineSheet combineSheet in this){this.PrintMessage($"{combineSheet.PartLayer}->{combineSheet.Name}");string name = $"{combineSheet.Id}_2d";var tempPart = this.GetOutputTempFile(name + ".prt");var defineFile = this.GetOutputTempFile(name + ".def");var dwgFile = this.GetOutputTempFile(name + ".dwg");combineSheet.DwgPath = dwgFile;this.SettingTable.OutputPartsList = tempPart;this.SettingTable.DrawingNames = combineSheet.Name;this.SettingTable.SaveAs(defineFile);var sb = new System.Text.StringBuilder();//初始化sb.AppendLine($"set UGII_BASE_DIR=\"{this.BaseDirectory}\"");sb.AppendLine($"set UGII_ROOT_DIR=\"{this.RootDirectory}\"");sb.AppendLine($"pushd \"{this.BaseDirectory}\"");sb.AppendLine($"cd \"{this.RootDirectory}\"");//转换成2Dsb.AppendLine($"call \"{ugTo2dExe}\" d=\"{defineFile}\"");sb.AppendLine($"del \"{defineFile}\"");//转换成dwgsb.AppendLine($"call \"{dxfDwgExe}\" i=\"{tempPart}\" o=\"{dwgFile}\" d=\"{dxfDwgDefine}\" l=\"{logFile}\"");sb.AppendLine($"del \"{tempPart}\"");sb.AppendLine($"del \"{logFile}\"");//sb.AppendLine($"del %0");sb.AppendLine($"exit");//System.IO.File.WriteAllText(this.GetOutputTempFile($"{name}.bat"),sb.ToString());try{RunCommand(sb.ToString());}catch (System.Exception ex){this.PrintMessage($"导出图纸遇到异常,----{ex.Message}");}}}private void OnCombine(){//Check AutoCADType cadType = Type.GetTypeFromProgID("AutoCAD.Application");if (cadType == null){throw new System.Exception($"没有安装任何AutoCAD软件,图纸无法合并!");}//用COM创建object app = Activator.CreateInstance(cadType);//提供5秒的时间用于等待appfor (int i = 0; i < 50; i++){if (app == null)System.Threading.Thread.Sleep(100);}try{//new a documentobject document = app.GetProperty("Documents").InvokeMethod("Add");document.InvokeMethod("SaveAs", new object[] { this.OutputFile.FullPath });object modelSpace = document.GetProperty("ModelSpace");double x = 0;foreach (CombineSheet sheet in this){double[] origin = new double[] { x, 0, 0 };x += (sheet.Length + 10);this.PrintMessage($"->{sheet.Name}");try{if (sheet.DwgPath?.Exists == true){object blockReference = modelSpace.InvokeMethod("InsertBlock", new object[] { origin, sheet.DwgPath.FullPath, 1, 1, 1, 0 });object objects = blockReference.InvokeMethod("Explode");blockReference.InvokeMethod("Delete", new object[0]);sheet.DwgPath.Delete();}else{this.PrintMessage($"没有找到相应图纸,程序跳过。");}var framePath = this.GetFrameFile(sheet);if (framePath?.Exists == true){object blockReference = modelSpace.InvokeMethod("InsertBlock", new object[] { origin, framePath.FullPath, sheet.FrameScale, sheet.FrameScale, 1, 0 });try{object objects = blockReference.InvokeMethod("Explode");blockReference.InvokeMethod("Delete", new object[0]);}catch (Exception ex){//ex.ToString().WriteToLog();ex.Data.Clear();}}else{this.PrintMessage($"没有找到相应CAD图框 {sheet.FrameCategory}\\{sheet.FrameName}");}}catch (System.Exception ex){this.PrintMessage(ex.ToString());}}document?.InvokeMethod("Save");document?.InvokeMethod("Close");}finally{app.InvokeMethod("Quit");}}private void OnClearFile(){foreach (CombineSheet sheet in this){if (sheet?.DwgPath?.Exists == true){sheet.DwgPath.Delete();}}}private void PrintMessage(string msg){Console.WriteLine($"{msg}");}private void RunCommand(string args){var process = new Process();try{process.StartInfo.FileName = "cmd.exe "; //打开DOS控制平台 process.StartInfo.UseShellExecute = false;process.StartInfo.CreateNoWindow = true; //是否显示DOS窗口,true代表隐藏;process.StartInfo.RedirectStandardInput = true;process.StartInfo.RedirectStandardOutput = true;process.StartInfo.RedirectStandardError = true;process.Start();var input = process.StandardInput;//标准输入流 var output = process.StandardOutput;//标准输入流 var error = process.StandardError;//标准错误流 input.AutoFlush = true;foreach (var s1 in args.Split(new string[] { System.Environment.NewLine },System.StringSplitOptions.RemoveEmptyEntries)){input.WriteLine(s1);}string s = output.ReadToEnd();//读取执行DOS命令后输出信息 string er = error.ReadToEnd().Trim();//读取执行DOS命令后错误信息 if (process.HasExited == false){process.Kill();//MessageBox.Show(er);}else{//MessageBox.Show(s);}input.Close();output.Close();error.Close();if (!string.IsNullOrWhiteSpace(er)){throw new System.Exception(er);}}finally{process.Close();}}public IEnumerator<CombineSheet> GetEnumerator(){foreach (var combineSheet in this.mList){yield return combineSheet;}}IEnumerator IEnumerable.GetEnumerator(){return GetEnumerator();}}

读写配置表

    public class SettingTable:IEnumerable<SettingVariable>{private readonly List<SettingVariable> mList;public SettingTable(string filePath){this.mList = GetSettingVariables(filePath).ToList();}public int Count => this.mList.Count;public string this[string name]{get{foreach (SettingVariable settingVariable in this){if (string.Compare(settingVariable.Name, name,System.StringComparison.OrdinalIgnoreCase) == 0){return settingVariable.Value;}}return null;}set{foreach (SettingVariable settingVariable in this){if (string.Compare(settingVariable.Name, name, System.StringComparison.OrdinalIgnoreCase) == 0){settingVariable.Value = value;return;}}this.mList.Add(new SettingVariable(name,value));}}/// <summary>/// 输入part文件路径/// </summary>public string InputPartsList{get => this["INPUT_PARTS_LIST"];set => this["INPUT_PARTS_LIST"] = value;}/// <summary>/// 输出Part文件路径/// </summary>public string OutputPartsList{get => this["OUTPUT_PARTS_LIST"];set => this["OUTPUT_PARTS_LIST"] = value;}/// <summary>/// 图纸名称/// </summary>public string DrawingNames{get => this["UGI_DRAWING_NAMES"];set => this["UGI_DRAWING_NAMES"] = value;}/// <summary>/// 日志文件路径/// </summary>public string LogFile{get => this["LOG_FILE"];set => this["LOG_FILE"] = value;}private IEnumerable<SettingVariable> GetSettingVariables(string filePath){if (!System.IO.File.Exists(filePath)){yield break;}foreach (var line in System.IO.File.ReadAllLines(filePath)){if (string.IsNullOrWhiteSpace(line)){continue;}if (line.StartsWith("!") ||line.StartsWith("#")){continue;}yield return new SettingVariable(line);}}public void SaveAs(string filePath){System.IO.File.Exists(filePath);var lines = this.Select(p => $"{p}").ToArray();System.IO.File.WriteAllLines(filePath,lines);}public IEnumerator<SettingVariable> GetEnumerator(){foreach (var settingVariable in this.mList){yield return settingVariable;}}IEnumerator IEnumerable.GetEnumerator(){return GetEnumerator();}}public class SettingVariable{public SettingVariable(string name, string value){this.Name = name;this.Value = value;}public SettingVariable(string nameAndValue){int index = nameAndValue.IndexOf('=');if (index < 0){this.Name = nameAndValue.Trim();}else{this.Name = nameAndValue.Substring(0, index).Trim();this.Value = nameAndValue.Substring(index + 1).Trim();}}public string Name { get; }public string Value { get; set; }public override string ToString(){var value = $"{this.Value}".Trim();//if (value.IndexOf(' ') > 0)//{//    if (value.StartsWith("\"") && value.EndsWith("\""))//    {//    }//    else//    {//        value = $"\"{value}\"";//    }//}return $"{this.Name}={value}";}}

这篇关于NX二次开发 批量导出图纸 合并DWG的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/236212

相关文章

pandas批量拆分与合并Excel文件的实现示例

《pandas批量拆分与合并Excel文件的实现示例》本文介绍了Pandas中基于整数位置的iloc和基于标签的loc方法进行数据索引和切片的操作,并将大Excel文件拆分合并,具有一定的参考价值,感... 目录一、Pandas 进行索引和切编程片的iloc、loc方法二、Pandas批量拆分与合并Exce

使用C#导出Excel数据并保存多种格式的完整示例

《使用C#导出Excel数据并保存多种格式的完整示例》在现代企业信息化管理中,Excel已经成为最常用的数据存储和分析工具,从员工信息表、销售数据报表到财务分析表,几乎所有部门都离不开Excel,本文... 目录引言1. 安装 Spire.XLS2. 创建工作簿和填充数据3. 保存为不同格式4. 效果展示5

MySQL 批量插入的原理和实战方法(快速提升大数据导入效率)

《MySQL批量插入的原理和实战方法(快速提升大数据导入效率)》在日常开发中,我们经常需要将大量数据批量插入到MySQL数据库中,本文将介绍批量插入的原理、实现方法,并结合Python和PyMySQ... 目录一、批量插入的优势二、mysql 表的创建示例三、python 实现批量插入1. 安装 PyMyS

Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)

《Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)》在职场中,Word文档是公认的好伙伴,但你有没有被它折磨过?批量生成合同、制作报告以及发放证书/通知等等,这些重复、低效... 目录重复性文档制作,手动填充模板,效率低下还易错1.python-docx入门:Word文档的“瑞士

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造

Ubuntu向多台主机批量传输文件的流程步骤

《Ubuntu向多台主机批量传输文件的流程步骤》:本文主要介绍在Ubuntu中批量传输文件到多台主机的方法,需确保主机互通、用户名密码统一及端口开放,通过安装sshpass工具,准备包含目标主机信... 目录Ubuntu 向多台主机批量传输文件1.安装 sshpass2.准备主机列表文件3.创建一个批处理脚

MySQL批量替换数据库字符集的实用方法(附详细代码)

《MySQL批量替换数据库字符集的实用方法(附详细代码)》当需要修改数据库编码和字符集时,通常需要对其下属的所有表及表中所有字段进行修改,下面:本文主要介绍MySQL批量替换数据库字符集的实用方法... 目录前言为什么要批量修改字符集?整体脚本脚本逻辑解析1. 设置目标参数2. 生成修改表默认字符集的语句3

JAVA实现亿级千万级数据顺序导出的示例代码

《JAVA实现亿级千万级数据顺序导出的示例代码》本文主要介绍了JAVA实现亿级千万级数据顺序导出的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 前提:主要考虑控制内存占用空间,避免出现同时导出,导致主程序OOM问题。实现思路:A.启用线程池

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s