getFilesWithEditor(string caption, string name, string filter, string directory, string message) { Editor ed = BaseObjs._editor; PromptOpenFileOptions pofo = null; try { pofo = new PromptOpenFileOptions("Select a file using Editor. GetFileNameForOpen()"); pofo.DialogCaption = caption; } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " FileManager.cs: line: 183"); } pofo.DialogName = name; pofo.Filter = filter; pofo.InitialDirectory = directory; pofo.Message = message; PromptFileNameResult pfnr = ed.GetFileNameForOpen(pofo); if (pfnr.Status == PromptStatus.OK) { return(pfnr.StringResult); } return(null); }
private static bool OpenNewDocument(string Name) { try { //Application.DocumentManager.Open(Name); new UtilityClass().ReadDocument(Name); return(true); } catch { try { PromptOpenFileOptions opts = new PromptOpenFileOptions("Select a drawing file (for a custom command)"); opts.Filter = "Drawing (*.dwg)"; PromptFileNameResult pr = Application.DocumentManager.MdiActiveDocument.Editor.GetFileNameForOpen(opts); if (pr.Status == PromptStatus.OK) { //Application.DocumentManager.Open(pr.StringResult); new UtilityClass().ReadDocument(pr.StringResult); return(true); } else { return(false); } } catch { return(false); } } }
internal static string SelectFolder(string promptText) { //ask for a file using the open file dialog Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptSaveFileOptions op = new PromptSaveFileOptions(promptText); op.InitialDirectory = "C:\\"; op.Filter = "CSV Files (*.csv)|*.csv"; op.FilterIndex = 2; PromptFileNameResult fn = ed.GetFileNameForSave(op); return(fn.StringResult); }
/// <summary> /// 提示框提示用户输入文件名作为文件保存 /// </summary> /// <param name="message">提示</param> /// <returns></returns> public static string FileNameForSave(string message) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptFileNameResult i = ed.GetFileNameForSave(message); if (i.Status == PromptStatus.OK) { return(i.StringResult); } else { return(""); } }
[CommandMethod("gsi")] //Comanda revizuita care importa puncte din fisiere gsi public void ImportGSI() { //Selectia fisierelor gsi Document acadDoc = Application.DocumentManager.MdiActiveDocument; CivilDocument civilDoc = CivilApplication.ActiveDocument; Editor ed = acadDoc.Editor; Database db = HostApplicationServices.WorkingDatabase; PromptOpenFileOptions POFO = new PromptOpenFileOptions("Select gsi file: "); POFO.Filter = ".gsi"; PromptFileNameResult FileRes = ed.GetFileNameForOpen(POFO); if (FileRes.Status != PromptStatus.OK) { ed.WriteMessage("\nFile selection failed! Aborting."); return; } string cale = FileRes.StringResult; PromptResult PSR = ed.GetString("\nSpecify points description"); if (PSR.Status != PromptStatus.OK) { ed.WriteMessage("\nInvalid description! Aborting."); return; } string descriere = PSR.StringResult; String3D listaPuncte = new String3D(); listaPuncte.ImportGSI(cale); using (Transaction trans = db.TransactionManager.StartTransaction()) { CogoPointCollection cogoPoints = civilDoc.CogoPoints; foreach (Punct3D punct in listaPuncte) { ObjectId pointId = cogoPoints.Add(new Point3d(punct.X, punct.Y, punct.Z)); CogoPoint cogo = pointId.GetObject(OpenMode.ForWrite) as CogoPoint; cogo.RawDescription = descriere; } trans.Commit(); } }
public void ReadConfigCommand() { PromptOpenFileOptions file_opt = new PromptOpenFileOptions("Укажите путь к файлу настроек ссылок"); file_opt.Filter = "Файлы настроек ссылок (*.xml)|*.xml|Все файлы (*.*)|*.*"; //file_opt.FilterIndex = 1; PromptFileNameResult file_res = Core.current_editor.GetFileNameForOpen(file_opt); if (file_res.Status == PromptStatus.OK) { Core.config = new Configuration(file_res.StringResult); } else { Core.WriteMessage("Пользователь отказался\n"); return; } Core.WriteMessage("\n"); }
public void load_preview() { if (myPal == null) { this.preview(); } //ask for a file using the open file dialog Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptOpenFileOptions op = new PromptOpenFileOptions("Select a File to Preview."); PromptFileNameResult fn = ed.GetFileNameForOpen(op); //did we get a file okay? if (fn.Status == PromptStatus.OK) { //use the loaded dwg file to update the preview box myPreviewBox.load_file_preview(fn.StringResult); } //show the palette just in case it's been closed myPal.Visible = true; }
public static void PythonLoad(bool useCmdLine) { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; short fd = (short)Application.GetSystemVariable("FILEDIA"); // As the user to select a .py file PromptOpenFileOptions pfo = new PromptOpenFileOptions("Select Python Script to load"); pfo.Filter = "Python Script (*.py)|*.py"; pfo.PreferCommandLine = (useCmdLine || fd == 0); PromptFileNameResult pr = ed.GetFileNameForOpen(pfo); // And then try to load and execute it if (pr.Status == PromptStatus.OK) { ExecutePythonScript(pr.StringResult); } }
/// <summary> /// Запрос пользователя для выбора файла шаблона /// </summary> /// <returns>True, если был выбран корректный файл шаблона, иначе false</returns> private bool SelectTemplate() { Configuration.AppConfig cfg = Configuration.AppConfig.Instance; PromptOpenFileOptions pofo = new PromptOpenFileOptions(CP.TemplateFileQuery); pofo.Filter = CP.TemplateFileQueryFilter; pofo.InitialFileName = cfg.TemplatePath; PromptFileNameResult templateName = ed.GetFileNameForOpen(pofo); if (templateName.Status == PromptStatus.OK) { if (!System.IO.File.Exists(templateName.StringResult)) { throw new System.IO.FileNotFoundException(templateName.StringResult); } cfg.TemplatePath = templateName.StringResult; cfg.Save(); return(true); } return(false); }
public static void ReadICD() { // CAD指针 CivilDocument civildoc = CivilApplication.ActiveDocument; Document doc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = doc.Database; Editor ed = doc.Editor; PromptOpenFileOptions opt = new PromptOpenFileOptions("\n请选择线型文件."); opt.Filter = "ICD File (*.icd)|*.icd|All files (*.*)|*.*"; PromptFileNameResult res = ed.GetFileNameForOpen(opt); if (res.Status != PromptStatus.OK) { return; } SRBA.PM bill = new SRBA.PM(res.StringResult); // 转化平曲线 ObjectId AlgID = Alignment.Create(civildoc, Path.GetFileNameWithoutExtension(res.StringResult), null, "0", "Basic", "All Labels"); using (Transaction ts = acCurDb.TransactionManager.StartTransaction()) { Alignment myAg = ts.GetObject(AlgID, OpenMode.ForWrite) as Alignment; AddICD(ref myAg, ref bill, ref ed); myAg.ReferencePointStation = bill.StartPK; //ed.WriteMessage("\n{0}读取成功.", res.StringResult); // 竖曲线 PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("\n是否加载竖曲线?"); pKeyOpts.Keywords.Add("Y"); pKeyOpts.Keywords.Add("N"); pKeyOpts.Keywords.Default = "Y"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = doc.Editor.GetKeywords(pKeyOpts); switch (pKeyRes.Status) { case PromptStatus.OK: if (pKeyRes.StringResult == "Y") { SRBA.SQX kitty = new SRBA.SQX(Path.ChangeExtension(res.StringResult, "SQX")); ObjectId layerId = myAg.LayerId; ObjectId styleId = civildoc.Styles.ProfileStyles["Basic"]; ObjectId labelSetId = civildoc.Styles.LabelSetStyles.ProfileLabelSetStyles["Complete Label Set"]; ObjectId oProfileId = Profile.CreateByLayout(myAg.Name + "-Profile", myAg.ObjectId, layerId, styleId, labelSetId); Profile oProfile = ts.GetObject(oProfileId, OpenMode.ForWrite) as Profile; AddSQX(ref oProfile, ref kitty, ref ed); } break; default: break; } // 转化对比JD法 //pKeyOpts = new PromptKeywordOptions("\n是否加载交点法平曲线?"); //pKeyOpts.Keywords.Add("Y"); //pKeyOpts.Keywords.Add("N"); //pKeyOpts.Keywords.Default = "Y"; //pKeyOpts.AllowNone = true; //pKeyRes = doc.Editor.GetKeywords(pKeyOpts); //switch (pKeyRes.Status) //{ // case PromptStatus.OK: // if (pKeyRes.StringResult == "Y") // { // PQXnew kitty = new PQXnew("Test"); // kitty.ReadICDFile(res.StringResult); // ObjectId layerId = myAg.LayerId; // ObjectId styleId = civildoc.Styles.ProfileStyles["Basic"]; // ObjectId labelSetId = civildoc.Styles.LabelSetStyles.ProfileLabelSetStyles["Complete Label Set"]; // ObjectId oProfileId = Profile.CreateByLayout(myAg.Name + "-Profile", myAg.ObjectId, layerId, styleId, labelSetId); // Profile oProfile = ts.GetObject(oProfileId, OpenMode.ForWrite) as Profile; // AddPQX( 0,24000,500, ref acCurDb, ref kitty, ref ed); // } // break; // default: // break; //} ts.Commit(); } }
private void PythonConsole(bool cmdLine) { Dictionary <string, object> options = new Dictionary <string, object>(); options["Debug"] = true; var ipy = Python.CreateRuntime(options); var engine = Python.GetEngine(ipy); try { string path = ""; System.Version version = Application.Version; string ver = version.ToString().Split(new char[] { '.' })[0]; string release = "2020"; switch (ver) { case "20": release = "2016"; break; case "21": release = "2017"; break; case "22": release = "2018"; break; case "23": release = "2019"; break; case "24": release = "2020"; break; } if (!cmdLine) { WF.OpenFileDialog ofd = new WF.OpenFileDialog(); ofd.Filter = "Python Script (*.py) | *.py"; if (ofd.ShowDialog() == WF.DialogResult.OK) { path = ofd.FileName; } } else { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; short fd = (short)Application.GetSystemVariable("FILEDIA"); // Ask the user to select a .py file PromptOpenFileOptions pfo = new PromptOpenFileOptions("Select Python script to load"); pfo.Filter = "Python script (*.py)|*.py"; pfo.PreferCommandLine = (cmdLine || fd == 0); PromptFileNameResult pr = ed.GetFileNameForOpen(pfo); path = pr.StringResult; } if (path != "") { ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\acmgd.dll", release))); ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\acdbmgd.dll", release))); ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\accoremgd.dll", release))); ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\ACA\AecBaseMgd.dll", release))); ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\ACA\AecPropDataMgd.dll", release))); ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\C3D\AeccDbMgd.dll", release))); ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\C3D\AeccPressurePipesMgd.dll", release))); ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\acdbmgdbrep.dll", release))); ScriptSource source = engine.CreateScriptSourceFromFile(path); CompiledCode compiledCode = source.Compile(); ScriptScope scope = engine.CreateScope(); compiledCode.Execute(scope); } } catch (System.Exception ex) { string message = engine.GetService <ExceptionOperations>().FormatException(ex); WF.MessageBox.Show(message); } return; }
public void updateTBFromFile() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor; //read external json PromptFileNameResult pfnr = ed.GetFileNameForOpen("\nSpecify json file"); if (pfnr.Status != PromptStatus.OK) { ed.WriteMessage("\nerror to read external json file " + pfnr.Status.ToString()); return; } string paramFile = pfnr.StringResult; string rawJsonContent = File.ReadAllText(paramFile); Transaction tr = db.TransactionManager.StartTransaction(); // Start the transaction try { //convert json to json class jsonDrawing jsonDrawingInstance = JsonConvert.DeserializeObject <jsonDrawing>(rawJsonContent); if (jsonDrawingInstance == null) { ed.WriteMessage("\nraw json file is bad!\n"); return; } //string tblayer = jsonDrawingInstance.tblayer; //create the layer for signature ObjectId lyId = createLayer("signature_layer"); if (lyId.IsNull) { ed.WriteMessage("\nlayer cannot be created"); return; } // Build a filter list so that only block references are selected TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") }; SelectionFilter filter = new SelectionFilter(filList); PromptSelectionResult res = ed.SelectAll(filter); // Do nothing if selection is unsuccessful if (res.Status != PromptStatus.OK) { ed.WriteMessage("\nno any Insert in this drawing!"); return; } SelectionSet selSet = res.Value; ObjectId[] idArray = selSet.GetObjectIds(); foreach (ObjectId blkId in idArray) { BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead); ed.WriteMessage("\nBlock: " + btr.Name); btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForWrite); //check the block ref of title block on the specific layer if (attRef.Layer == Helper.tblayer) { foreach (var eachAtt in jsonDrawingInstance.tbjson) { if (eachAtt.tag == attRef.Tag) { ed.WriteMessage("\nbegin: " + eachAtt.tag + " \n"); ed.WriteMessage("\nis image: " + eachAtt.isImage + " \n"); if (eachAtt.isImage) { attRef.TextString = ""; //create image for signature createImages(eachAtt, tr, lyId); } else { attRef.TextString = eachAtt.content; } break; ed.WriteMessage("\nend: " + eachAtt.tag + " \n"); } } } } } tr.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(("\nException: " + ex.Message)); } finally { tr.Dispose(); } db.SaveAs("newTB.dwg", DwgVersion.Newest); }
public void MyCommand() // This method can have any name { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; using (Transaction Trans = db.TransactionManager.StartTransaction()) { try { PromptOpenFileOptions fileoptions = new PromptOpenFileOptions("\n输入要插入的图形文件"); fileoptions.Filter = "dwg图形文件(*.dwg)|*.dwg"; string filename = ""; PromptFileNameResult fileresult = ed.GetFileNameForOpen(fileoptions); if (fileresult.Status == PromptStatus.OK) { filename = fileresult.StringResult; if (!File.Exists(filename)) { ed.WriteMessage("\n文件路径无效!"); return; } } else { return; } //自动脚本,去掉插入点输入 //PromptPointResult pointResult = ed.GetPoint("\n输入插入点"); Point3d insertpoint = new Point3d(0, 0, 0); /* * if (pointResult.Status == PromptStatus.OK) * { * insertpoint = pointResult.Value; * } * else * { * return; * } */ //获取布局列表(剔除模型空间) DBDictionary Layouts = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; ArrayList Layoutlist = new ArrayList(); foreach (DBDictionaryEntry item in Layouts) { if (item.Key != "Model") { Layout layoutobject = Trans.GetObject(item.Value, OpenMode.ForRead) as Layout; Layoutlist.Add(layoutobject); } } foreach (Layout LT in Layoutlist) { ObjectId xrefID = db.AttachXref(filename, Path.GetFileNameWithoutExtension(filename)); if (!xrefID.IsNull) { BlockReference xref = new BlockReference(insertpoint, xrefID); BlockTableRecord BTR = Trans.GetObject(LT.BlockTableRecordId, OpenMode.ForWrite) as BlockTableRecord; BTR.AppendEntity(xref); Trans.AddNewlyCreatedDBObject(xref, true); } //Layout LT = Layoutlist[0] as Layout; //BlockTableRecord BTR = Trans.GetObject(LT.BlockTableRecordId, OpenMode.ForWrite) as BlockTableRecord; //BTR.AppendEntity(xref); // Trans.AddNewlyCreatedDBObject(xref,true); } Trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception Ex) { ed.WriteMessage("出错啦!{0}", Ex.ToString()); } finally { Trans.Dispose(); } } }
public void SetDataLink() // This method can have any name { // Put your command code here Database db = Application.DocumentManager.MdiActiveDocument.Database; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; //获取目录表格的容量 int NumberPerPage = 1; PromptIntegerOptions GetNumberOption = new PromptIntegerOptions("\n输入每张表格的最大容量"); GetNumberOption.AllowNegative = false; GetNumberOption.AllowZero = false; PromptIntegerResult GetNumberResult = ed.GetInteger(GetNumberOption); if (GetNumberResult.Status == PromptStatus.OK) { NumberPerPage = GetNumberResult.Value; } else { return; } //获取图纸目录数据文件 string DataFile = ""; PromptOpenFileOptions fileoption = new PromptOpenFileOptions("\n输入链接数据文件路径"); fileoption.InitialDirectory = System.IO.Path.GetDirectoryName(db.Filename); fileoption.Filter = "Excel Documents (*.xlsx) |*.xlsx"; PromptFileNameResult DataFileResult = ed.GetFileNameForOpen(fileoption); if (DataFileResult.Status == PromptStatus.OK) { DataFile = DataFileResult.StringResult; } else { return; } //获取数据表范围信息 string SheetName = "图纸目录"; string StartCol = "A"; string EndCol = "E"; int StartRow = 2; PromptResult GetSheetName = ed.GetString("\n输入链接数据表名称"); if (GetSheetName.Status == PromptStatus.OK) { SheetName = GetSheetName.StringResult; } else { return; } PromptResult GetStartCol = ed.GetString("\n输入数据起始列"); if (GetStartCol.Status == PromptStatus.OK) { StartCol = GetStartCol.StringResult; } else { return; } PromptResult GetEndCol = ed.GetString("\n输入数据结束列"); if (GetEndCol.Status == PromptStatus.OK) { EndCol = GetEndCol.StringResult; } else { return; } PromptIntegerResult GetStartRow = ed.GetInteger("\n输入数据起始行"); if (GetStartRow.Status == PromptStatus.OK) { StartRow = GetStartRow.Value; } else { return; } using (Transaction Trans = db.TransactionManager.StartTransaction()) { DBDictionary Layouts = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; ArrayList Layoutlist = new ArrayList(); foreach (DBDictionaryEntry item in Layouts) { if (item.Key != "Model") { Layoutlist.Add(item.Key); } } //int NumberOfList = Layoutlist.Count; ArrayList TableIDs = new ArrayList(); foreach (string name in Layoutlist) { TypedValue[] Filter = new TypedValue[] { new TypedValue((int)DxfCode.Operator, "<and"), new TypedValue((int)DxfCode.LayoutName, name), new TypedValue((int)DxfCode.Start, "ACAD_TABLE"), new TypedValue((int)DxfCode.Operator, "and>"), }; PromptSelectionResult selresult = ed.SelectAll(new SelectionFilter(Filter)); if (selresult.Status == PromptStatus.OK) { ObjectId[] ids = selresult.Value.GetObjectIds(); TableIDs.Add(ids[0]); } } int NumberOfTables = TableIDs.Count; /* * ed.WriteMessage("\nLayout:{0}", Layoutlist.Count); * foreach(string name in Layoutlist) * { * ed.WriteMessage("\nLayoutname:{0}", name); * } * ed.WriteMessage("\nTables:{0}", TableIDs.Count); */ DataLinkManager dlm = db.DataLinkManager; try { for (int i = 0; i < NumberOfTables; i++) { Autodesk.AutoCAD.DatabaseServices.DataLink dl = new Autodesk.AutoCAD.DatabaseServices.DataLink(); dl.DataAdapterId = "AcExcel"; dl.Name = SheetName + (i + 1).ToString(); dl.Description = SheetName + "数据链接" + (i + 1).ToString(); string location = string.Format("!{0}!{1}{2}:{3}{4}", SheetName, StartCol, (StartRow + i * NumberPerPage), EndCol, ((1 + i) * NumberPerPage) + StartRow - 1); dl.ConnectionString = DataFile + location; dl.DataLinkOption = DataLinkOption.PersistCache; dl.UpdateOption |= (int)UpdateOption.AllowSourceUpdate | (int)UpdateOption.SkipFormat; ObjectId dlId = dlm.AddDataLink(dl); ed.WriteMessage("\n链接字符串:{0}", dl.ConnectionString); Trans.AddNewlyCreatedDBObject(dl, true); Table tb = (Table)Trans.GetObject((ObjectId)TableIDs[i], OpenMode.ForWrite); tb.Cells[1, 0].DataLink = dlId; tb.GenerateLayout(); } Trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception Ex) { ed.WriteMessage("\n出错啦!" + Ex.ToString()); } finally { Trans.Dispose(); } } }
public void PrintTT() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; List <String> imagelist = new List <String>(); string directory = @"D:\";//磁盘路径 string MediaName = comboBoxMedia.SelectedItem.ToString().Replace(" ", "_").Replace("毫米", "MM").Replace("英寸", "Inches").Replace("像素", "Pixels"); try { if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { int flag = 0; //获取当前布局管理器变量 LayoutManager acLayoutMgr = LayoutManager.Current; //获取当前布局变量 Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead); //Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForWrite); //获取当前布局的打印信息 PlotInfo acPlInfo = new PlotInfo() { Layout = acLayout.ObjectId }; //提示用户输入打印窗口的两个角点 PromptPointResult resultp = ed.GetPoint("\n指定第一个角点"); if (resultp.Status != PromptStatus.OK) { return; } Point3d basePt = resultp.Value; resultp = ed.GetCorner("指定对角点", basePt); if (resultp.Status != PromptStatus.OK) { return; } Point3d cornerPt = resultp.Value; //选择实体对象 // PromptSelectionOptions result1 = new PromptSelectionOptions(); SelectionFilter frameFilter = new SelectionFilter( new TypedValue[] { new TypedValue(0, "LWPOLYLINE"), new TypedValue(90, 4), new TypedValue(70, 1) }); PromptSelectionResult selectedFrameResult = ed.SelectWindow(basePt, cornerPt, frameFilter); // PromptSelectionResult selectedFrameResult = ed.GetSelection(result1, frameFilter); PromptSelectionResult selectedFrameResult1 = ed.SelectAll(frameFilter); if (selectedFrameResult.Status == PromptStatus.OK) { List <ObjectId> selectedObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds()); List <ObjectId> resultObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds()); RemoveInnerPLine(acTrans, ref selectedObjectIds, ref resultObjectIds); foreach (ObjectId frameId in resultObjectIds) { Polyline framePline = acTrans.GetObject(frameId, OpenMode.ForRead) as Polyline; framePline.Highlight(); } PlotSettings acPlSet = new PlotSettings(acLayout.ModelType); acPlSet.CopyFrom(acLayout); //着色打印选项,设置按线框进行打印 acPlSet.ShadePlot = PlotSettingsShadePlotType.Wireframe; PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current; //打印比例 //用户标准打印 acPlSetVdr.SetUseStandardScale(acPlSet, true); acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit); //居中打印 acPlSetVdr.SetPlotCentered(acPlSet, true); //调用GetPlotStyleSheetList之后才可以使用SetCurrentStyleSheet System.Collections.Specialized.StringCollection sc = acPlSetVdr.GetPlotStyleSheetList(); //设置打印样式表 if (comboBoxStyleSheet.SelectedItem.ToString() == "无") { acPlSetVdr.SetCurrentStyleSheet(acPlSet, "acad.ctb"); } else { acPlSetVdr.SetCurrentStyleSheet(acPlSet, comboBoxStyleSheet.SelectedItem.ToString()); } //选择方向 if (radioButtonHorizontal.Checked) { //横向 acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName); acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090); } //竖向 if (radioButtonVertical.Checked) { acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);//获取打印图纸尺寸ComboxMedia acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000); } PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, resultObjectIds.Count, true); string imagename = ""; string[] files = new string[] { }; List <string> listfile = new List <string>(); foreach (var frame in resultObjectIds) { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } flag++; Entity ent = acTrans.GetObject(frame, OpenMode.ForRead) as Entity; imagename = string.Format("{0}-{1}.pdf", frame, flag); //imagelist.Add(directory + imagename); listfile.Add(directory + imagename); //设置是否使用打印样式 acPlSet.ShowPlotStyles = true; //设置打印区域 Extents3d extents3d = ent.GeometricExtents; Extents2d E2d = new Extents2d(extents3d.MinPoint.X, extents3d.MinPoint.Y, extents3d.MaxPoint.X, extents3d.MaxPoint.Y); acPlSetVdr.SetPlotWindowArea(acPlSet, E2d); acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window); //重载和保存打印信息 acPlInfo.OverrideSettings = acPlSet; //验证打印信息设置,看是否有误 PlotInfoValidator acPlInfoVdr = new PlotInfoValidator(); acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; acPlInfoVdr.Validate(acPlInfo); while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting) { continue; } #region BackUpCode //保存App的原参数 short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT"); //设定为前台打印,加快打印速度 Application.SetSystemVariable("BACKGROUNDPLOT", 0); PlotEngine acPlEng1 = PlotFactory.CreatePublishEngine(); // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出"); // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出"); //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度"); acPlProgDlg.LowerPlotProgressRange = 0; acPlProgDlg.UpperPlotProgressRange = 100; acPlProgDlg.PlotProgressPos = 0; acPlProgDlg.OnBeginPlot(); acPlProgDlg.IsVisible = true; acPlEng1.BeginPlot(acPlProgDlg, null); acPlEng1.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename); // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件")); acPlProgDlg.OnBeginSheet(); acPlProgDlg.LowerSheetProgressRange = 0; acPlProgDlg.UpperSheetProgressRange = 100; acPlProgDlg.SheetProgressPos = 0; PlotPageInfo acPlPageInfo = new PlotPageInfo(); acPlEng1.BeginPage(acPlPageInfo, acPlInfo, true, null); acPlEng1.BeginGenerateGraphics(null); acPlEng1.EndGenerateGraphics(null); acPlEng1.EndPage(null); acPlProgDlg.SheetProgressPos = 100; acPlProgDlg.OnEndSheet(); acPlEng1.EndDocument(null); acPlProgDlg.PlotProgressPos = 100; acPlProgDlg.OnEndPlot(); acPlEng1.EndPlot(null); acPlEng1.Dispose(); acPlEng1.Destroy(); Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot); #endregion } files = listfile.ToArray(); PlotConfig config = PlotConfigManager.CurrentConfig; //获取去除扩展名后的文件名(不含路径) string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(acDoc.Name, "dwg"); //定义保存文件对话框 PromptSaveFileOptions opt = new PromptSaveFileOptions("文件名") { //保存文件对话框的文件扩展名列表 Filter = "*" + config.DefaultFileExtension + "|*" + config.DefaultFileExtension, DialogCaption = "浏览打印文件", //保存文件对话框的标题 InitialDirectory = @"D:\", //缺省保存目录 InitialFileName = fileName + "-" + acLayout.LayoutName //缺省保存文件名 }; //根据保存对话框中用户的选择,获取保存文件名 PromptFileNameResult result = ed.GetFileNameForSave(opt); if (result.Status != PromptStatus.OK) { return; } fileName = result.StringResult; //string fileName = @"D:\输出.pdf"; PdfDocumentBase docx = PdfDocument.MergeFiles(files); docx.Save(fileName, FileFormat.PDF); System.Diagnostics.Process.Start(fileName); //保存App的原参数 short bgPlot1 = (short)Application.GetSystemVariable("BACKGROUNDPLOT"); //设定为前台打印,加快打印速度 Application.SetSystemVariable("BACKGROUNDPLOT", 0); PlotEngine acPlEng = PlotFactory.CreatePublishEngine(); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度"); acPlProgDlg.LowerPlotProgressRange = 0; acPlProgDlg.UpperPlotProgressRange = 100; acPlProgDlg.PlotProgressPos = 0; acPlProgDlg.OnBeginPlot(); acPlProgDlg.IsVisible = true; acPlEng.BeginPlot(acPlProgDlg, null); acPlEng.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件")); acPlProgDlg.OnBeginSheet(); acPlProgDlg.LowerSheetProgressRange = 0; acPlProgDlg.UpperSheetProgressRange = 100; acPlProgDlg.SheetProgressPos = 0; PlotPageInfo acPlPageInfo1 = new PlotPageInfo(); acPlEng.BeginPage(acPlPageInfo1, acPlInfo, true, null); acPlEng.BeginGenerateGraphics(null); acPlEng.EndGenerateGraphics(null); acPlEng.EndPage(null); acPlProgDlg.SheetProgressPos = 100; acPlProgDlg.OnEndSheet(); acPlEng.EndDocument(null); acPlProgDlg.PlotProgressPos = 100; acPlProgDlg.OnEndPlot(); acPlEng.EndPlot(null); acPlEng.Dispose(); acPlEng.Destroy(); Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot1); acPlProgDlg.Dispose(); acPlProgDlg.Destroy(); for (int i = 0; i < files.Length; i++) { File.Delete(files[i]); } } while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting) { continue; } //MessageBox.Show("打印完成!"); } } else { ed.WriteMessage("\n另一个打印进程正在进行中."); } } catch (System.Exception) { throw; } }
[CommandMethod("expsurfpts")] //Comanda pentru exportarea intr-un fisier PENZD.csv a punctelor unei suprafete public void ExpSurfPts() { CivilDocument civDoc = CivilApplication.ActiveDocument; Document acadDoc = Application.DocumentManager.MdiActiveDocument; Database db = HostApplicationServices.WorkingDatabase; Editor ed = acadDoc.Editor; ObjectIdCollection surfIds = civDoc.GetSurfaceIds(); //Verificarea existentei a cel putin unei suprafete if (surfIds.Count == 0) { ed.WriteMessage("\nNo Surfaces found!"); return; } using (Transaction trans = db.TransactionManager.StartTransaction()) { //Selectarea suprafetei Autodesk.Civil.DatabaseServices.Surface suprafata; if (surfIds.Count == 1) { suprafata = (Autodesk.Civil.DatabaseServices.Surface)trans.GetObject(surfIds[0], OpenMode.ForRead); } else { PromptEntityOptions PrEntOpt = new PromptEntityOptions("\nSelect Surface: "); PrEntOpt.AllowNone = false; PrEntOpt.SetRejectMessage("\nSelected object is not a Civil3D surface!"); PrEntOpt.AddAllowedClass(typeof(Autodesk.Civil.DatabaseServices.Surface), false); PromptEntityResult PrEntRes = ed.GetEntity(PrEntOpt); if (PrEntRes.Status != PromptStatus.OK) { ed.WriteMessage("\nAborting!"); return; } suprafata = (Autodesk.Civil.DatabaseServices.Surface)trans.GetObject(PrEntRes.ObjectId, OpenMode.ForRead); } //Obtinerea punctelor suprafetei List <string> puncte = new List <string>(); int nr = 0; if (suprafata is Autodesk.Civil.DatabaseServices.TinSurface) { Autodesk.Civil.DatabaseServices.TinSurface suprafTIN = (Autodesk.Civil.DatabaseServices.TinSurface)suprafata; //Autodesk.Civil.DatabaseServices.TinSurfaceVertexCollection vertecsiTIN = suprafTIN.Vertices; foreach (Autodesk.Civil.DatabaseServices.TinSurfaceVertex V in suprafTIN.Vertices) { nr = nr + 1; puncte.Add(nr.ToString() + "," + V.Location.ToString().Replace("(", "").Replace(")", "") + "," + suprafata.Name); } } else if (suprafata is Autodesk.Civil.DatabaseServices.GridSurface) { Autodesk.Civil.DatabaseServices.GridSurface suprafGRID = (Autodesk.Civil.DatabaseServices.GridSurface)suprafata; foreach (Autodesk.Civil.DatabaseServices.GridSurfaceVertex V in suprafGRID.Vertices) { nr = nr + 1; puncte.Add(nr.ToString() + "," + V.Location.ToString().Replace("(", "").Replace(")", "") + "," + suprafata.Name); } } else { ed.WriteMessage("\nSurface type not supported! Aborting."); return; } ////TEST: se listeaza punctele //foreach(string p in puncte) ed.WriteMessage(p); //Selectia fisierului .csv si scrierea punctelor PromptSaveFileOptions PrFileOpt = new PromptSaveFileOptions("\nSelect file for point export: "); PrFileOpt.Filter = ("CSV file (*.csv)|*.csv"); string caleDocAcad = HostApplicationServices.Current.FindFile(acadDoc.Name, acadDoc.Database, FindFileHint.Default); //PrFileOpt.InitialDirectory = caleDocAcad.Remove(caleDocAcad.LastIndexOf("\\"); PrFileOpt.InitialFileName = caleDocAcad.Replace(caleDocAcad.Substring(caleDocAcad.LastIndexOf('.')), ".csv"); ed.WriteMessage(PrFileOpt.InitialDirectory); PromptFileNameResult PrFileRes = ed.GetFileNameForSave(PrFileOpt); if (PrFileRes.Status != PromptStatus.OK) { ed.WriteMessage("\nPoint export unsuccessful!"); return; } StreamWriter scriitor = new StreamWriter(PrFileRes.StringResult); foreach (string p in puncte) { scriitor.WriteLine(p); } scriitor.Dispose(); } }