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

相关文章

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

Python中合并列表(list)的六种方法小结

《Python中合并列表(list)的六种方法小结》本文主要介绍了Python中合并列表(list)的六种方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋... 目录一、直接用 + 合并列表二、用 extend() js方法三、用 zip() 函数交叉合并四、用

Mac备忘录怎么导出/备份和云同步? Mac备忘录使用技巧

《Mac备忘录怎么导出/备份和云同步?Mac备忘录使用技巧》备忘录作为iOS里简单而又不可或缺的一个系统应用,上手容易,可以满足我们日常生活中各种记录的需求,今天我们就来看看Mac备忘录的导出、... 「备忘录」是 MAC 上的一款常用应用,它可以帮助我们捕捉灵感、记录待办事项或保存重要信息。为了便于在不同

MySQL数据库实现批量表分区完整示例

《MySQL数据库实现批量表分区完整示例》通俗地讲表分区是将一大表,根据条件分割成若干个小表,:本文主要介绍MySQL数据库实现批量表分区的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录一、表分区条件二、常规表和分区表的区别三、表分区的创建四、将既有表转换分区表脚本五、批量转换表为分区

利用Python实现Excel文件智能合并工具

《利用Python实现Excel文件智能合并工具》有时候,我们需要将多个Excel文件按照特定顺序合并成一个文件,这样可以更方便地进行后续的数据处理和分析,下面我们看看如何使用Python实现Exce... 目录运行结果为什么需要这个工具技术实现工具的核心功能代码解析使用示例工具优化与扩展有时候,我们需要将

MySQL Workbench工具导出导入数据库方式

《MySQLWorkbench工具导出导入数据库方式》:本文主要介绍MySQLWorkbench工具导出导入数据库方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录mysql Workbench工具导出导入数据库第一步 www.chinasem.cn数据库导出第二步

Java如何根据word模板导出数据

《Java如何根据word模板导出数据》这篇文章主要为大家详细介绍了Java如何实现根据word模板导出数据,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... pom.XML文件导入依赖 <dependency> <groupId>cn.afterturn</groupId>

Python实现获取带合并单元格的表格数据

《Python实现获取带合并单元格的表格数据》由于在日常运维中经常出现一些合并单元格的表格,如果要获取数据比较麻烦,所以本文我们就来聊聊如何使用Python实现获取带合并单元格的表格数据吧... 由于在日常运维中经常出现一些合并单元格的表格,如果要获取数据比较麻烦,现将将封装成类,并通过调用list_exc

Oracle 通过 ROWID 批量更新表的方法

《Oracle通过ROWID批量更新表的方法》在Oracle数据库中,使用ROWID进行批量更新是一种高效的更新方法,因为它直接定位到物理行位置,避免了通过索引查找的开销,下面给大家介绍Orac... 目录oracle 通过 ROWID 批量更新表ROWID 基本概念性能优化建议性能UoTrFPH优化建议注

C#实现高性能Excel百万数据导出优化实战指南

《C#实现高性能Excel百万数据导出优化实战指南》在日常工作中,Excel数据导出是一个常见的需求,然而,当数据量较大时,性能和内存问题往往会成为限制导出效率的瓶颈,下面我们看看C#如何结合EPPl... 目录一、技术方案核心对比二、各方案选型建议三、性能对比数据四、核心代码实现1. MiniExcel