本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!