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

相关文章

基于C#实现PDF文件合并工具

《基于C#实现PDF文件合并工具》这篇文章主要为大家详细介绍了如何基于C#实现一个简单的PDF文件合并工具,文中的示例代码简洁易懂,有需要的小伙伴可以跟随小编一起学习一下... 界面主要用于发票PDF文件的合并。经常出差要报销的很有用。代码using System;using System.Col

Python实现将实体类列表数据导出到Excel文件

《Python实现将实体类列表数据导出到Excel文件》在数据处理和报告生成中,将实体类的列表数据导出到Excel文件是一项常见任务,Python提供了多种库来实现这一目标,下面就来跟随小编一起学习一... 目录一、环境准备二、定义实体类三、创建实体类列表四、将实体类列表转换为DataFrame五、导出Da

Python数据处理之导入导出Excel数据方式

《Python数据处理之导入导出Excel数据方式》Python是Excel数据处理的绝佳工具,通过Pandas和Openpyxl等库可以实现数据的导入、导出和自动化处理,从基础的数据读取和清洗到复杂... 目录python导入导出Excel数据开启数据之旅:为什么Python是Excel数据处理的最佳拍档

Python在固定文件夹批量创建固定后缀的文件(方法详解)

《Python在固定文件夹批量创建固定后缀的文件(方法详解)》文章讲述了如何使用Python批量创建后缀为.md的文件夹,生成100个,代码中需要修改的路径、前缀和后缀名,并提供了注意事项和代码示例,... 目录1. python需求的任务2. Python代码的实现3. 代码修改的位置4. 运行结果5.

Python视频剪辑合并操作的实现示例

《Python视频剪辑合并操作的实现示例》很多人在创作视频时都需要进行剪辑,本文主要介绍了Python视频剪辑合并操作的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习... 目录介绍安装FFmpegWindowsMACOS安装MoviePy剪切视频合并视频转换视频结论介绍

使用Python实现批量访问URL并解析XML响应功能

《使用Python实现批量访问URL并解析XML响应功能》在现代Web开发和数据抓取中,批量访问URL并解析响应内容是一个常见的需求,本文将详细介绍如何使用Python实现批量访问URL并解析XML响... 目录引言1. 背景与需求2. 工具方法实现2.1 单URL访问与解析代码实现代码说明2.2 示例调用

Oracle Expdp按条件导出指定表数据的方法实例

《OracleExpdp按条件导出指定表数据的方法实例》:本文主要介绍Oracle的expdp数据泵方式导出特定机构和时间范围的数据,并通过parfile文件进行条件限制和配置,文中通过代码介绍... 目录1.场景描述 2.方案分析3.实验验证 3.1 parfile文件3.2 expdp命令导出4.总结

不删数据还能合并磁盘? 让电脑C盘D盘合并并保留数据的技巧

《不删数据还能合并磁盘?让电脑C盘D盘合并并保留数据的技巧》在Windows操作系统中,合并C盘和D盘是一个相对复杂的任务,尤其是当你不希望删除其中的数据时,幸运的是,有几种方法可以实现这一目标且在... 在电脑生产时,制造商常为C盘分配较小的磁盘空间,以确保软件在运行过程中不会出现磁盘空间不足的问题。但在

在C#中合并和解析相对路径方式

《在C#中合并和解析相对路径方式》Path类提供了几个用于操作文件路径的静态方法,其中包括Combine方法和GetFullPath方法,Combine方法将两个路径合并在一起,但不会解析包含相对元素... 目录C#合并和解析相对路径System.IO.Path类幸运的是总结C#合并和解析相对路径对于 C

java poi实现Excel多级表头导出方式(多级表头,复杂表头)

《javapoi实现Excel多级表头导出方式(多级表头,复杂表头)》文章介绍了使用javapoi库实现Excel多级表头导出的方法,通过主代码、合并单元格、设置表头单元格宽度、填充数据、web下载... 目录Java poi实现Excel多级表头导出(多级表头,复杂表头)上代码1.主代码2.合并单元格3.