当前位置:   article > 正文

NX二次开发 批量导出图纸 合并DWG_nx多个图纸页输出到一个dwg

nx多个图纸页输出到一个dwg

NXOpen入口

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. try
  6. {
  7. //Console.ReadKey(true);
  8. Console.BackgroundColor = ConsoleColor.DarkGray;
  9. Console.ForegroundColor = ConsoleColor.DarkMagenta;
  10. Console.Clear();
  11. Console.Title = "导出CAD图纸";
  12. string filePath = "";
  13. foreach (string arg in args)
  14. {
  15. filePath = filePath + arg + " ";
  16. }
  17. filePath = filePath.Trim();
  18. CombineSheetManager manager = string.IsNullOrWhiteSpace(filePath)
  19. ? new CombineSheetManager()
  20. : new CombineSheetManager(filePath);
  21. manager.Commit();
  22. }
  23. catch (System.Exception ex)
  24. {
  25. if (!string.IsNullOrWhiteSpace(ex.Source))
  26. {
  27. Console.WriteLine(ex.Source);
  28. }
  29. Console.WriteLine(ex);
  30. }
  31. Console.ReadKey();
  32. }
  33. }

主要类:导出 合并

  1. public class CombineSheetManager : BaseCombineManager, IEnumerable<CombineSheet>
  2. {
  3. private readonly List<CombineSheet> mList;
  4. public CombineSheetManager(string filePath)
  5. {
  6. var lines = ReadAllLines(filePath).ToList();
  7. if (lines.Count < 3)
  8. {
  9. throw new System.Exception($"工作包文件格式错误。\r\n{filePath}");
  10. }
  11. this.BaseDirectory = lines[0];
  12. this.InputPart = lines[1];
  13. this.OutputFile = lines[2];
  14. this.mList = lines.Skip(3).Select(p => new CombineSheet(this, p)).ToList();
  15. if (this.mList.Count == 0)
  16. {
  17. throw new System.Exception($"工作包文件没有指定导出图纸。\r\n{filePath}");
  18. }
  19. //赋序号
  20. int i = 0;
  21. foreach (var combineSheet in this.mList)
  22. {
  23. combineSheet.Id = ++i;
  24. }
  25. //查找Root目录
  26. var rootDir = this.BaseDirectory.GetSubFolder("NXBIN");
  27. if (rootDir == null || !rootDir.Exists)
  28. {
  29. rootDir = this.BaseDirectory.GetSubFolder("UGII");
  30. if (rootDir == null || !rootDir.Exists)
  31. {
  32. throw new System.Exception($"当前{this.BaseDirectory}程序安装不完整。");
  33. }
  34. }
  35. this.RootDirectory = rootDir;
  36. //配置表
  37. var ugTo2dDef = this.CurrentDirectory.GetFile("ugto2d.def");
  38. this.SettingTable = new SettingTable(ugTo2dDef);
  39. }
  40. public CombineSheetManager():this(OpenPackage())
  41. {
  42. }
  43. private static string OpenPackage()
  44. {
  45. Console.WriteLine("请输入工作包文件路径:");
  46. return Console.ReadLine();
  47. //var openFile = new System.Windows.Forms.OpenFileDialog();
  48. //openFile.Multiselect = false;
  49. //openFile.Filter = "Package Files(*.package)|*.package|All Files(*.*)|*.*";
  50. //openFile.CheckPathExists = true;
  51. //var result = openFile.ShowDialog();
  52. //string fileName = "";
  53. //if (result == System.Windows.Forms.DialogResult.OK)
  54. //{
  55. // fileName = openFile.FileName;
  56. //}
  57. //openFile.Dispose();
  58. //return fileName;
  59. }
  60. public FolderPathInfo BaseDirectory { get; }
  61. public FilePathInfo InputPart { get; set; }
  62. public FilePathInfo OutputFile { get; set; }
  63. public FolderPathInfo RootDirectory { get; }
  64. public SettingTable SettingTable { get; }
  65. private IEnumerable<string> ReadAllLines(string filePath)
  66. {
  67. bool isDeleteFile = true;
  68. if (string.IsNullOrWhiteSpace(filePath))
  69. {
  70. filePath = $"{base.Name}.package";
  71. isDeleteFile = false;
  72. }
  73. if (filePath.IndexOf('\\') < 0)
  74. {
  75. filePath = base.CurrentDirectory.GetFile(filePath);
  76. isDeleteFile = false;
  77. }
  78. if (!System.IO.File.Exists(filePath))
  79. {
  80. yield break;
  81. }
  82. var lines = System.IO.File.ReadAllLines(filePath);
  83. if (isDeleteFile)
  84. {
  85. System.IO.File.Delete(filePath);
  86. }
  87. foreach (var line in lines)
  88. {
  89. if (string.IsNullOrWhiteSpace(line)) continue;
  90. if (line.StartsWith("!")||
  91. line.StartsWith("#"))
  92. {
  93. continue;
  94. }
  95. yield return line;
  96. }
  97. }
  98. public FilePathInfo GetOutputTempFile(string fileName, bool deleteFile = true)
  99. {
  100. var filePathInfo = this.OutputFile.Directory.GetFile(fileName);
  101. if (filePathInfo?.Exists == true)
  102. {
  103. if (!deleteFile)
  104. {
  105. filePathInfo.CopyToBak();
  106. }
  107. filePathInfo.Delete();
  108. }
  109. return filePathInfo;
  110. }
  111. public FilePathInfo GetFrameFile(CombineSheet sheet)
  112. {
  113. if (sheet == null) return null;
  114. var folder = this.UserDirectory.GetSubFolder(@"Config\DrawingTemplate");
  115. if (!string.IsNullOrWhiteSpace(sheet.FrameCategory))
  116. {
  117. folder = folder.GetSubFolder(sheet.FrameCategory);
  118. }
  119. if (!string.IsNullOrWhiteSpace(sheet.FrameName))
  120. {
  121. return folder.GetFile(sheet.FrameName + ".dwg");
  122. }
  123. return null;
  124. }
  125. public void Commit()
  126. {
  127. try
  128. {
  129. this.PrintMessage("----------------------------------------------------");
  130. this.PrintMessage("图纸导出开始:");
  131. this.OnExport();
  132. this.PrintMessage("图纸导出完成。");
  133. this.PrintMessage("");
  134. this.PrintMessage("----------------------------------------------------");
  135. this.PrintMessage("图纸合并开始:");
  136. this.OnCombine();
  137. this.PrintMessage("图纸合并完成。");
  138. this.PrintMessage("");
  139. }
  140. finally
  141. {
  142. OnClearFile();
  143. }
  144. }
  145. private void OnExport()
  146. {
  147. var ugTo2dExe = this.BaseDirectory.GetFile(@"UGTO2D\ugto2d.exe");
  148. var dxfDwgExe = this.BaseDirectory.GetFile(@"DXFDWG\dxfdwg.exe");
  149. var dxfDwgDefine = this.CurrentDirectory.GetFile("dxfdwg.def");
  150. if (!dxfDwgDefine.Exists)
  151. {
  152. dxfDwgDefine = this.BaseDirectory.GetFile(@"DXFDWG\dxfdwg.def");
  153. }
  154. if (!ugTo2dExe.Exists ||
  155. !dxfDwgExe.Exists ||
  156. !dxfDwgDefine.Exists)
  157. {
  158. throw new System.Exception($"当前{this.BaseDirectory}程序安装不完整。");
  159. }
  160. if (this.OutputFile?.Directory?.Exists != true)
  161. {
  162. throw new System.Exception($"输出路径不正确。\r\n{this.OutputFile}");
  163. }
  164. var logFile = this.OutputFile.ChangeExtension(".log");
  165. this.SettingTable.InputPartsList = this.InputPart;
  166. this.SettingTable.LogFile = logFile;
  167. foreach (CombineSheet combineSheet in this)
  168. {
  169. this.PrintMessage($"{combineSheet.PartLayer}->{combineSheet.Name}");
  170. string name = $"{combineSheet.Id}_2d";
  171. var tempPart = this.GetOutputTempFile(name + ".prt");
  172. var defineFile = this.GetOutputTempFile(name + ".def");
  173. var dwgFile = this.GetOutputTempFile(name + ".dwg");
  174. combineSheet.DwgPath = dwgFile;
  175. this.SettingTable.OutputPartsList = tempPart;
  176. this.SettingTable.DrawingNames = combineSheet.Name;
  177. this.SettingTable.SaveAs(defineFile);
  178. var sb = new System.Text.StringBuilder();
  179. //初始化
  180. sb.AppendLine($"set UGII_BASE_DIR=\"{this.BaseDirectory}\"");
  181. sb.AppendLine($"set UGII_ROOT_DIR=\"{this.RootDirectory}\"");
  182. sb.AppendLine($"pushd \"{this.BaseDirectory}\"");
  183. sb.AppendLine($"cd \"{this.RootDirectory}\"");
  184. //转换成2D
  185. sb.AppendLine($"call \"{ugTo2dExe}\" d=\"{defineFile}\"");
  186. sb.AppendLine($"del \"{defineFile}\"");
  187. //转换成dwg
  188. sb.AppendLine($"call \"{dxfDwgExe}\" i=\"{tempPart}\" o=\"{dwgFile}\" d=\"{dxfDwgDefine}\" l=\"{logFile}\"");
  189. sb.AppendLine($"del \"{tempPart}\"");
  190. sb.AppendLine($"del \"{logFile}\"");
  191. //sb.AppendLine($"del %0");
  192. sb.AppendLine($"exit");
  193. //System.IO.File.WriteAllText(this.GetOutputTempFile($"{name}.bat"),sb.ToString());
  194. try
  195. {
  196. RunCommand(sb.ToString());
  197. }
  198. catch (System.Exception ex)
  199. {
  200. this.PrintMessage($"导出图纸遇到异常,----{ex.Message}");
  201. }
  202. }
  203. }
  204. private void OnCombine()
  205. {
  206. //Check AutoCAD
  207. Type cadType = Type.GetTypeFromProgID("AutoCAD.Application");
  208. if (cadType == null)
  209. {
  210. throw new System.Exception($"没有安装任何AutoCAD软件,图纸无法合并!");
  211. }
  212. //用COM创建
  213. object app = Activator.CreateInstance(cadType);
  214. //提供5秒的时间用于等待app
  215. for (int i = 0; i < 50; i++)
  216. {
  217. if (app == null)
  218. System.Threading.Thread.Sleep(100);
  219. }
  220. try
  221. {
  222. //new a document
  223. object document = app.GetProperty("Documents").InvokeMethod("Add");
  224. document.InvokeMethod("SaveAs", new object[] { this.OutputFile.FullPath });
  225. object modelSpace = document.GetProperty("ModelSpace");
  226. double x = 0;
  227. foreach (CombineSheet sheet in this)
  228. {
  229. double[] origin = new double[] { x, 0, 0 };
  230. x += (sheet.Length + 10);
  231. this.PrintMessage($"->{sheet.Name}");
  232. try
  233. {
  234. if (sheet.DwgPath?.Exists == true)
  235. {
  236. object blockReference = modelSpace.InvokeMethod("InsertBlock", new object[] { origin, sheet.DwgPath.FullPath, 1, 1, 1, 0 });
  237. object objects = blockReference.InvokeMethod("Explode");
  238. blockReference.InvokeMethod("Delete", new object[0]);
  239. sheet.DwgPath.Delete();
  240. }
  241. else
  242. {
  243. this.PrintMessage($"没有找到相应图纸,程序跳过。");
  244. }
  245. var framePath = this.GetFrameFile(sheet);
  246. if (framePath?.Exists == true)
  247. {
  248. object blockReference = modelSpace.InvokeMethod("InsertBlock", new object[] { origin, framePath.FullPath, sheet.FrameScale, sheet.FrameScale, 1, 0 });
  249. try
  250. {
  251. object objects = blockReference.InvokeMethod("Explode");
  252. blockReference.InvokeMethod("Delete", new object[0]);
  253. }
  254. catch (Exception ex)
  255. {
  256. //ex.ToString().WriteToLog();
  257. ex.Data.Clear();
  258. }
  259. }
  260. else
  261. {
  262. this.PrintMessage($"没有找到相应CAD图框 {sheet.FrameCategory}\\{sheet.FrameName}");
  263. }
  264. }
  265. catch (System.Exception ex)
  266. {
  267. this.PrintMessage(ex.ToString());
  268. }
  269. }
  270. document?.InvokeMethod("Save");
  271. document?.InvokeMethod("Close");
  272. }
  273. finally
  274. {
  275. app.InvokeMethod("Quit");
  276. }
  277. }
  278. private void OnClearFile()
  279. {
  280. foreach (CombineSheet sheet in this)
  281. {
  282. if (sheet?.DwgPath?.Exists == true)
  283. {
  284. sheet.DwgPath.Delete();
  285. }
  286. }
  287. }
  288. private void PrintMessage(string msg)
  289. {
  290. Console.WriteLine($"{msg}");
  291. }
  292. private void RunCommand(string args)
  293. {
  294. var process = new Process();
  295. try
  296. {
  297. process.StartInfo.FileName = "cmd.exe "; //打开DOS控制平台
  298. process.StartInfo.UseShellExecute = false;
  299. process.StartInfo.CreateNoWindow = true; //是否显示DOS窗口,true代表隐藏;
  300. process.StartInfo.RedirectStandardInput = true;
  301. process.StartInfo.RedirectStandardOutput = true;
  302. process.StartInfo.RedirectStandardError = true;
  303. process.Start();
  304. var input = process.StandardInput;//标准输入流
  305. var output = process.StandardOutput;//标准输入流
  306. var error = process.StandardError;//标准错误流
  307. input.AutoFlush = true;
  308. foreach (var s1 in args.Split(new string[] { System.Environment.NewLine },
  309. System.StringSplitOptions.RemoveEmptyEntries))
  310. {
  311. input.WriteLine(s1);
  312. }
  313. string s = output.ReadToEnd();//读取执行DOS命令后输出信息
  314. string er = error.ReadToEnd().Trim();//读取执行DOS命令后错误信息
  315. if (process.HasExited == false)
  316. {
  317. process.Kill();
  318. //MessageBox.Show(er);
  319. }
  320. else
  321. {
  322. //MessageBox.Show(s);
  323. }
  324. input.Close();
  325. output.Close();
  326. error.Close();
  327. if (!string.IsNullOrWhiteSpace(er))
  328. {
  329. throw new System.Exception(er);
  330. }
  331. }
  332. finally
  333. {
  334. process.Close();
  335. }
  336. }
  337. public IEnumerator<CombineSheet> GetEnumerator()
  338. {
  339. foreach (var combineSheet in this.mList)
  340. {
  341. yield return combineSheet;
  342. }
  343. }
  344. IEnumerator IEnumerable.GetEnumerator()
  345. {
  346. return GetEnumerator();
  347. }
  348. }

读写配置表

  1. public class SettingTable:IEnumerable<SettingVariable>
  2. {
  3. private readonly List<SettingVariable> mList;
  4. public SettingTable(string filePath)
  5. {
  6. this.mList = GetSettingVariables(filePath).ToList();
  7. }
  8. public int Count => this.mList.Count;
  9. public string this[string name]
  10. {
  11. get
  12. {
  13. foreach (SettingVariable settingVariable in this)
  14. {
  15. if (string.Compare(settingVariable.Name, name,System.StringComparison.OrdinalIgnoreCase) == 0)
  16. {
  17. return settingVariable.Value;
  18. }
  19. }
  20. return null;
  21. }
  22. set
  23. {
  24. foreach (SettingVariable settingVariable in this)
  25. {
  26. if (string.Compare(settingVariable.Name, name, System.StringComparison.OrdinalIgnoreCase) == 0)
  27. {
  28. settingVariable.Value = value;
  29. return;
  30. }
  31. }
  32. this.mList.Add(new SettingVariable(name,value));
  33. }
  34. }
  35. /// <summary>
  36. /// 输入part文件路径
  37. /// </summary>
  38. public string InputPartsList
  39. {
  40. get => this["INPUT_PARTS_LIST"];
  41. set => this["INPUT_PARTS_LIST"] = value;
  42. }
  43. /// <summary>
  44. /// 输出Part文件路径
  45. /// </summary>
  46. public string OutputPartsList
  47. {
  48. get => this["OUTPUT_PARTS_LIST"];
  49. set => this["OUTPUT_PARTS_LIST"] = value;
  50. }
  51. /// <summary>
  52. /// 图纸名称
  53. /// </summary>
  54. public string DrawingNames
  55. {
  56. get => this["UGI_DRAWING_NAMES"];
  57. set => this["UGI_DRAWING_NAMES"] = value;
  58. }
  59. /// <summary>
  60. /// 日志文件路径
  61. /// </summary>
  62. public string LogFile
  63. {
  64. get => this["LOG_FILE"];
  65. set => this["LOG_FILE"] = value;
  66. }
  67. private IEnumerable<SettingVariable> GetSettingVariables(string filePath)
  68. {
  69. if (!System.IO.File.Exists(filePath))
  70. {
  71. yield break;
  72. }
  73. foreach (var line in System.IO.File.ReadAllLines(filePath))
  74. {
  75. if (string.IsNullOrWhiteSpace(line))
  76. {
  77. continue;
  78. }
  79. if (line.StartsWith("!") ||
  80. line.StartsWith("#"))
  81. {
  82. continue;
  83. }
  84. yield return new SettingVariable(line);
  85. }
  86. }
  87. public void SaveAs(string filePath)
  88. {
  89. System.IO.File.Exists(filePath);
  90. var lines = this.Select(p => $"{p}").ToArray();
  91. System.IO.File.WriteAllLines(filePath,lines);
  92. }
  93. public IEnumerator<SettingVariable> GetEnumerator()
  94. {
  95. foreach (var settingVariable in this.mList)
  96. {
  97. yield return settingVariable;
  98. }
  99. }
  100. IEnumerator IEnumerable.GetEnumerator()
  101. {
  102. return GetEnumerator();
  103. }
  104. }
  105. public class SettingVariable
  106. {
  107. public SettingVariable(string name, string value)
  108. {
  109. this.Name = name;
  110. this.Value = value;
  111. }
  112. public SettingVariable(string nameAndValue)
  113. {
  114. int index = nameAndValue.IndexOf('=');
  115. if (index < 0)
  116. {
  117. this.Name = nameAndValue.Trim();
  118. }
  119. else
  120. {
  121. this.Name = nameAndValue.Substring(0, index).Trim();
  122. this.Value = nameAndValue.Substring(index + 1).Trim();
  123. }
  124. }
  125. public string Name { get; }
  126. public string Value { get; set; }
  127. public override string ToString()
  128. {
  129. var value = $"{this.Value}".Trim();
  130. //if (value.IndexOf(' ') > 0)
  131. //{
  132. // if (value.StartsWith("\"") && value.EndsWith("\""))
  133. // {
  134. // }
  135. // else
  136. // {
  137. // value = $"\"{value}\"";
  138. // }
  139. //}
  140. return $"{this.Name}={value}";
  141. }
  142. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/646557
推荐阅读
相关标签
  

闽ICP备14008679号