public static ViewDrafting CreateViewDrafting(Document doc, string name) { ViewFamilyType vd = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .FirstOrDefault(q => q.ViewFamily == ViewFamily.Drafting); ViewDrafting draftView; using (Transaction t = new Transaction(doc, "CreateViewDrafting")) { t.Start(); draftView = ViewDrafting.Create(doc, vd.Id); draftView.Name = name; t.Commit(); } if (draftView != null) { return(draftView); } else { throw (new Exception("Не удалось вставить DWG файл")); } }
/// <summary> /// /// </summary> /// <param name="app"></param> /// <param name="viewDrafting"></param> /// <returns></returns> private static Revit.Element CloneElement(Autodesk.Revit.UI.UIApplication app, ViewDrafting viewDrafting) { //ViewDrafting viewDraftingClone = app.ActiveUIDocument.Document.Create.NewViewDrafting(); // 2015, jeremy: 'Autodesk.Revit.Creation.Document.NewViewDrafting()' is obsolete: 'This method is obsolete in Revit 2015. Use ViewDrafting.Create() instead.' ViewDrafting viewDraftingClone = ViewDrafting.Create(app.ActiveUIDocument.Document, viewDrafting.GetTypeId()); // 2016, jeremy Utils.ParamUtil.SetParameters(viewDraftingClone.Parameters, viewDrafting.Parameters); return(viewDraftingClone); }
public static ViewDrafting viewDraftingCreate(Document doc, string viewName) { FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)); ViewFamilyType viewFamilyType = collector.Cast <ViewFamilyType>().First(vft => vft.ViewFamily == ViewFamily.Drafting); ViewDrafting view = ViewDrafting.Create(doc, viewFamilyType.Id); view.ViewName = viewName; return(view); }
View CreateDrafting(Document doc) { FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(ViewFamilyType)); ViewFamilyType viewFamilyType = collector.Cast <ViewFamilyType>().First(vft => vft.ViewFamily == ViewFamily.Drafting); ViewDrafting drafting = ViewDrafting.Create(doc, viewFamilyType.Id); return(drafting as View); }
private static void refreshProjBrowser(Document curDoc) { //create temp drafting view ViewDrafting tmpView = null; tmpView = ViewDrafting.Create(curDoc, mCollectors.getDraftingViewFamilyTypeID(curDoc)); tmpView.Name = "zzz_temp"; //delete view curDoc.Delete(tmpView.Id); }
void DrawAll(Document doc) { foreach (ARKModule b in ARKBLocks) { ViewFamilyType vt = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(vft => vft.ViewFamily == ViewFamily.Drafting); ElementId id = vt.Id; Transaction trans = new Transaction(doc); trans.Start("Lab"); ViewDrafting vd = ViewDrafting.Create(doc, id); trans.Commit(); } }
private ViewDrafting CreateNewDraftingView() { var drfViews = new FilteredElementCollector(CurrentDocument) .OfClass(typeof(ViewFamilyType)); var dvId = drfViews .Cast <ViewFamilyType>() .FirstOrDefault(v => v.ViewFamily == ViewFamily.Drafting).Id; var newView = ViewDrafting.Create(CurrentDocument, dvId); return(newView); }
void DrawAll(Document doc) { foreach (string s in staticFamilies) { try { string file_path = File.ReadAllText("C://ProgramData//Autodesk//Revit//Addins//2019//Linear//settings.set"); file_path += "\\static\\" + s; loader.LoadFamilyIntoProject(file_path, doc); } catch { throw new Exception("Ошибка загрузки семейств чертежных примитивов из папки static."); } } FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)); foreach (ARKModule b in ARKBLocks) { try { FamilySymbol famToPlace = null; ViewFamilyType vt = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(vft => vft.ViewFamily == ViewFamily.Drafting); ElementId id = vt.Id; Transaction trans = new Transaction(doc); trans.Start("Отрисовка"); ViewDrafting vd = ViewDrafting.Create(doc, id); b.setVD(vd); ElementId viewId = vd.Id; drawingviews.Add(viewId); famToPlace = collector.Cast <FamilySymbol>().Where(x => x.Name == b.filename).First(); b.revitSymbol = famToPlace; b.revitModule = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), famToPlace, vd); arkmoduleIds.Add(b.revitModule.Id); trans.Commit(); } catch { throw new Exception("Ошибка добавления АРК-модулей на чертежные листы."); } } SetArkIndexes(doc); DrawLines(doc); foreach (ARKModule b in ARKBLocks) { try { b.createTable(doc, new XYZ(10, 3, 0)); } catch { throw new Exception("Ошибка создания таблицы элементов."); } } }
IList <Element> GetViewsToDelete(Document doc) { using (Transaction trans = new Transaction(doc)) { // Collect all Views except ViewTemplates // Add one drafting view to project before deleting // all views because Revit will shut down when last view // is deleted from project. // Create a new Drafting view ViewFamilyType viewFamilyType = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>().First(vft => vft.ViewFamily == ViewFamily.Drafting); trans.Start("Delete All Views/Sheets"); ViewDrafting view = ViewDrafting.Create(doc, viewFamilyType.Id); view.ViewName = "TempDraftingView"; doc.Regenerate(); // Collect all Views except newly created one List <ElementId> exclude = new List <ElementId>(); exclude.Add(view.Id); ExclusionFilter filter = new ExclusionFilter(exclude); IList <Element> views = new FilteredElementCollector(doc) .OfClass(typeof(View)) .WhereElementIsNotElementType() .WherePasses(filter) .ToElements(); // Remove all ViewTemplates from views to be deleted for (var i = 0; i < views.Count; i++) { View v = views[i] as View; if (v.IsTemplate) { views.RemoveAt(i); } } trans.Commit(); return(views); } }
public Autodesk.Revit.UI.Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { try { Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "CreateDraftingView"); transaction.Start(); ViewFamilyType viewFamilyType = null; FilteredElementCollector collector = new FilteredElementCollector(doc); var viewFamilyTypes = collector.OfClass(typeof(ViewFamilyType)).ToElements(); foreach (Element e in viewFamilyTypes) { ViewFamilyType v = e as ViewFamilyType; if (v.ViewFamily == ViewFamily.Drafting) { viewFamilyType = v; break; } } ViewDrafting drafting = ViewDrafting.Create(doc, viewFamilyType.Id); if (null == drafting) { message = "Can't create the ViewDrafting."; return(Autodesk.Revit.UI.Result.Failed); } transaction.Commit(); TaskDialog.Show("Revit", "Create view drafting succeeded."); return(Autodesk.Revit.UI.Result.Succeeded); } catch (Exception e) { message = e.Message; return(Autodesk.Revit.UI.Result.Failed); } }
/// <summary> /// Initialize a DraftingView element /// </summary> private void InitDraftingView(string name) { TransactionManager.Instance.EnsureInTransaction(Document); FilteredElementCollector collector = new FilteredElementCollector(Document); var viewFamilyType = collector.OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>(). First(vft => vft.ViewFamily == ViewFamily.Drafting); var vd = ViewDrafting.Create(Document, viewFamilyType.Id); //rename the view if (!vd.Name.Equals(name)) { vd.Name = View3D.CreateUniqueViewName(name); } InternalSetDraftingView(vd); TransactionManager.Instance.TransactionTaskDone(); ElementBinder.CleanupAndSetElementForTrace(Document, this.InternalElement); }
public MaterialsCMSRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; ProgressBar progressBar = uiForm.materialsCMSExcelCreateSymbolsProgressBar; DataGridView dgv = uiForm.materialsCMSExcelDataGridView; int rowsCount = dgv.Rows.Count; int columnsCount = dgv.Columns.Count; List <string> familyTypesMade = new List <string>(); //Prepare the progress bar. The column count is one less because the first column is the column for family type names progressBar.Minimum = 0; progressBar.Maximum = (rowsCount) * (columnsCount - 1); progressBar.Step = 1; progressBar.Visible = true; RVTDocument doc = uiApp.ActiveUIDocument.Document; //Reset the progress bar uiForm.materialsCMSExcelCreateSymbolsProgressBar.Value = 0; //First, try to use the family from the project. If that fails, use the family file Family familyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); //Assuming nothing went to hell in the process of loading one famiy... if (familyToUse != null) { //Save out the family to use RVTDocument tempFamDoc = doc.EditFamily(familyToUse); RVTOperations.SaveRevitFile(uiApp, tempFamDoc, @"C:\Temp\" + tempFamDoc.Title, true); //Open the family to use and get its FamilyManager RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, @"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); FamilyManager famMan = famDoc.FamilyManager; //Get the parameters from the Family Manager and add them to a dictionary FamilyParameterSet parameters = famMan.Parameters; Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>(); foreach (FamilyParameter param in parameters) { famParamDict.Add(param.Definition.Name, param); } //Start a new transaction to make the new family types in the family to use using (Transaction t1 = new Transaction(famDoc, "MakeNewTypes")) { t1.Start(); //Cycle through the rows in the dgv for (int i = 0; i < rowsCount; i++) { //The first column cell will be the type name string newTypeName = dgv.Rows[i].Cells[0].Value.ToString(); //Get the family type names in the family Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(famMan); //If the family to make from the DGV does not exist in the dictionary keys... if (!existingTypeNames.Keys.Contains(newTypeName)) { //Make the family type and add it to the list of types made FamilyType newType = famMan.NewType(newTypeName); famMan.CurrentType = newType; familyTypesMade.Add(newType.Name); } else { //If the type exists, set the current type it from the dictionary and add it to the list of types made famMan.CurrentType = existingTypeNames[newTypeName]; familyTypesMade.Add(famMan.CurrentType.Name); } //Next, evaluate the columns that contain parameters for (int j = 1; j < columnsCount; j++) { //The parameter names will be retrieved from the column HeaderText property string paramName = dgv.Columns[j].HeaderText; //Meanwhile the parameter value will come from the DGV cells var paramValue = dgv.Rows[i].Cells[j].Value; try { //If the parameter dictionary contains the parameter and the value to assign it is not empty, continue. if (paramValue.ToString() != "" && famParamDict.Keys.Contains(paramName)) { //Get the family parameter and check if it is locked by a formula FamilyParameter param = famParamDict[paramName]; if (!param.IsDeterminedByFormula) { //If it is not locked by a formula, set the parameter ParameterType paramType = param.Definition.ParameterType; RVTOperations.SetFamilyParameterValue(famMan, param, paramValue); } } } catch {; } finally { //Always perform the step to indicate the progress. progressBar.PerformStep(); } } } t1.Commit(); } //Use another transaction to delete the types that were not needed using (Transaction t2 = new Transaction(famDoc, "DeleteOldTypes")) { t2.Start(); //Cycle through the family types and determine if it is in the list of types made foreach (FamilyType type in famMan.Types) { if (!familyTypesMade.Contains(type.Name)) { //If the type is not in the list of types made, delete it from the family file famMan.CurrentType = type; famMan.DeleteCurrentType(); } } t2.Commit(); } //Save the family document at this point as all of the types and their parameters have been set famDoc.Close(true); using (Transaction t3 = new Transaction(doc, "LoadFamily")) { t3.Start(); doc.LoadFamily(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule), new RVTFamilyLoadOptions(), out Family loadedFamily); t3.Commit(); } //Get the drafting view type in the project for BA Drafting View, else just get the first drafting view type ViewDrafting placementView = null; var draftingViews = new FilteredElementCollector(doc).OfClass(typeof(ViewDrafting)).WhereElementIsNotElementType().ToElements(); ViewFamilyType draftingViewType = null; try { //From the view family types collection, get the first one where its name is BA Drafting View draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().Where(elem => elem.Name == "BA Drafting View").First() as ViewFamilyType; } catch { //Well, crap. It doesn't exist. Just get the first type then and call it good. draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().First() as ViewFamilyType; } //Start a transaction for making the ID Material View and placing the family symbol types using (Transaction t4 = new Transaction(doc, "MakeIDMaterialView")) { t4.Start(); foreach (ViewDrafting view in draftingViews) { //Find the view named ID Material View, or whatever jibberish someone typed in the CMS text box for the name to use. in the drafting views if (view.Name == "ID Material View" || view.Name == uiForm.materialsCMSSetViewNameTextBox.Text) { //Delete the drafting view doc.Delete(view.Id); doc.Regenerate(); break; } else { continue; } } //Make a new view placementView = ViewDrafting.Create(doc, draftingViewType.Id); placementView.Scale = 1; if (uiForm.materialsCMSSetViewNameTextBox.Text != "") { //If someone defined a custom view name, use that and strip out brackets if they exist placementView.Name = uiForm.materialsCMSSetViewNameTextBox.Text.Replace("{", "").Replace("}", ""); } else { //Otherwise, this will be the new ID Material View placementView.Name = "ID Material View"; } try { //Set the view sort parameters if they exist placementView.GetParameters(Properties.Settings.Default.BAViewSort1).First().Set("2 Plans"); placementView.GetParameters(Properties.Settings.Default.BAViewSort2).First().Set("230 Finish Plans"); } catch (Exception e) { MessageBox.Show(e.ToString()); } doc.Regenerate(); t4.Commit(); } //Do magic to place each symbol in its view by calling the method below in this class PlaceSymbolsInView(uiApp, "ID Use", "Mark", placementView); //Clean up the files from the operations GeneralOperations.CleanRfaBackups(GeneralOperations.GetAllRvtBackupFamilies(@"C:\Temp\", false)); File.Delete(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); Application.thisApp.newMainUi.materialsCMSFamilyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)); } else { //If the family could not be found, well, let the user know of this. MessageBox.Show(String.Format("The {0} family could not be found in the project.", Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule))); } }
public MiscEDVRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; UIDocument uidoc = uiApp.ActiveUIDocument; if (uiForm.miscEDVSelectDirectoryTextBox.Text != "") { //Create a list for storing drafting views to export List <ViewDrafting> viewsToUse = new List <ViewDrafting>(); foreach (DataGridViewRow row in uiForm.miscEDVDataGridView.Rows) { //If the rows's Select column checkbox is checked, get the element and add it to the views to use if (row.Cells["Select"].Value.ToString() == "True") { DataRow dgvRow = (row.DataBoundItem as DataRowView).Row; viewsToUse.Add(dgvRow["View Element"] as ViewDrafting); } } //Preparing the progress bar int filesToProcess = viewsToUse.Count; uiForm.miscEDVProgressBar.Value = 0; uiForm.miscEDVProgressBar.Minimum = 0; uiForm.miscEDVProgressBar.Maximum = filesToProcess; uiForm.miscEDVProgressBar.Step = 1; uiForm.miscEDVProgressBar.Visible = true; //For each drafting view to export... foreach (ViewDrafting fromView in viewsToUse) { //Make a new Revit document file RVTDocument newDoc = uiApp.Application.NewProjectDocument(UnitSystem.Imperial); //Start the transaction Transaction t1 = new Transaction(newDoc, "ExportDraftingViews"); t1.Start(); //Start a subtransaction SubTransaction s1 = new SubTransaction(newDoc); s1.Start(); //In the new file, get the first view family type that is a drafting view type FilteredElementCollector collector = new FilteredElementCollector(newDoc); collector.OfClass(typeof(ViewFamilyType)); ViewFamilyType viewFamilyType = collector.Cast <ViewFamilyType>().First(vft => vft.ViewFamily == ViewFamily.Drafting); //In the new file, make a new drafting view using the view family type found in it ViewDrafting toView = ViewDrafting.Create(newDoc, viewFamilyType.Id); //Commit the sub transaction s1.Commit(); //Now the the drafting view exists in the new file, collect the elements in the originating drafting view List <ElementId> viewElementIds = new FilteredElementCollector(uidoc.Document, fromView.Id).ToElementIds().Cast <ElementId>().ToList(); CopyPasteOptions copyPasteOptions = new CopyPasteOptions(); copyPasteOptions.SetDuplicateTypeNamesHandler(new RVTDuplicateTypesHandler()); //Copy and paste the elements from the originating drafting view into the new file's drafting view ElementTransformUtils.CopyElements(fromView, viewElementIds, toView, null, copyPasteOptions); t1.Commit(); //Find the newly created drafting view's ID so the view can be used as the preview view when saving the new project file ElementId viewPreviewId = null; var newDocViews = new FilteredElementCollector(newDoc).OfClass(typeof(ViewDrafting)).ToElements().Cast <Element>().ToList(); foreach (ViewDrafting newDocView in newDocViews) { if (newDocView.Name == fromView.Name) { viewPreviewId = newDocView.Id; break; } } //Set the SaveAsOptions as follows, including the PreviewViewId SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.Compact = true; saveAsOptions.MaximumBackups = 1; saveAsOptions.OverwriteExistingFile = true; saveAsOptions.PreviewViewId = viewPreviewId; //The string array of illegal characters in the name is used to determine string[] illegalCharacters = { "<", ">", ":", "/", @"\", @"|", "?", "*" }; //Also remove quotation marks and periods from the view name string fileName = fromView.Name.Replace("\"", "").Replace(".", ""); //For each illegal character in the string array, remove it from the view name if it exists foreach (string item in illegalCharacters) { if (fileName.Contains(item)) { fileName.Replace(item, ""); } } //With a cleaned view name for saving to a file, save the new project file containing the new drafting view with the cleaned name string savePath = uiForm.miscEDVSelectDirectoryTextBox.Text + "\\" + fileName + ".rvt"; if (File.Exists(savePath)) { try { //Delete the file if it already exists File.Delete(savePath); } catch { continue; } } newDoc.SaveAs(savePath, saveAsOptions); newDoc.Close(false); //Step forward the progress bar. uiForm.miscEDVProgressBar.PerformStep(); } } else { //If the user forgot to set the directory of where to export the drafting views, let them know MessageBox.Show("No save directory is set. Please pick a directory."); } }
//Get the Selected Viewports from the linked model, check to see if the sheet they are on exists and if they are already placed. //If not, create and set the properties of both. private void btnOK_Click(object sender, EventArgs e) { int itemCount = 0; bool TitleLocation = true; ElementId typeId = (ElementId)cbViewPortTypes.SelectedValue; ElementType vpType = doc.GetElement(typeId) as ElementType; //Check to see if the Viewport Type has the Show Title property set to Yes, if it is not, we can't calculate its location //relative to the viewport to move it to the same location as the Linked Model if (vpType.LookupParameter("Show Title").AsInteger() != 1) { if (TaskDialog.Show("Viewport Show Title", "The Viewport Type selected does not have the 'Show Title' property set to Yes and the View placement may not be as expected.\nWould you like to continue?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No, TaskDialogResult.No) == TaskDialogResult.No) { return; } else { TitleLocation = false; } } //Use a Transaction Group for multiple transactions to be grouped as one. This enables the creation of sheets and views during the method //without throwing an exception that the elements don't exist using (TransactionGroup tGroup = new TransactionGroup(doc, "Create Linked Views")) { tGroup.Start(); using (Transaction t = new Transaction(doc)) { ElementId vpTypeId = ((Element)cboTitleBlock.SelectedValue).Id; foreach (DataGridViewRow row in dgvLinkedViews.SelectedRows) { //use a try block to make sure any errors don't crash revit try { t.Start("Create View"); string detailNumber = (string)row.Cells[1].Value; ViewFamilyType viewfamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.Drafting); TextNoteType textnoteType = new FilteredElementCollector(doc).OfClass(typeof(TextNoteType)).Cast <TextNoteType>().FirstOrDefault(); ViewDrafting draftingView = ViewDrafting.Create(doc, viewfamilyType.Id); draftingView.Name = (string)row.Cells[3].Value; draftingView.LookupParameter("Title on Sheet").Set("REFERENCE VIEW - DO NOT PRINT"); //Set additional View Parameters based on Firm standards and Project Broswer Sorting templates //if (dView.LookupParameter("Sheet Sort") is Parameter sSort) //{ // sSort.Set("PLANS"); //} //Set the Linked View Yes/No Parameter to "Yes" for the Reload Function to Track if (draftingView.LookupParameter("Linked View") is Parameter lView) { //Using 0 or 1 to set Yes (1) / No (0) parameters lView.Set(1); } else { TaskDialog.Show("Missing Parameter", "Linked View Yes/No parameter is missing from View category and cannot continue."); break; } //Set the Linked View GUID parameter to track the view in the Linked model if (draftingView.LookupParameter("Linked View GUID") is Parameter lGUID) { lGUID.Set((string)row.Cells[5].Value); } else { TaskDialog.Show("Missing Parameter", "Linked View GUID Text parameter is missing from View category and cannot continue."); break; } //Set the Link Name parameter to trak which Linked Model it came from. if (draftingView.LookupParameter("Link Name") is Parameter lName) { lName.Set(cboLinks.Text); } else { TaskDialog.Show("Missing Parameter", "Link Name Text parameter is missing from View category and cannot continue."); break; } //Creates one Text Note in the middle of the view to alert users that it is a Linked View and not to print it. TextNote.Create(doc, draftingView.Id, new XYZ(0, 0, 0), "REFERENCE VIEW - DO NOT PRINT", textnoteType.Id); t.Commit(); //Check to see if sheet with that number exits in the document t.Start("Create Sheet"); ViewSheet sheet = CheckSheet((string)row.Cells[2].Value, vpTypeId); t.Commit(); //Place the Drafting View reference on the sheet in the same location as in the Linked Model t.Start("Place View"); if (sheet != null) { //Check to see if Viewport can be placed on sheet if (Viewport.CanAddViewToSheet(doc, sheet.Id, draftingView.Id)) { if (CheckViewport(detailNumber, sheet)) { XYZ labelPoint = (XYZ)row.Cells[7].Value; Viewport vPort = Viewport.Create(doc, sheet.Id, draftingView.Id, labelPoint); draftingView.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).Set(detailNumber); if (typeId != ElementId.InvalidElementId) { vPort.ChangeTypeId(typeId); } if (TitleLocation) { //Get the location of the Viewport and Viewport Label and Move the Viewport to match the Linked Document ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint - vPort.GetLabelOutline().MinimumPoint); } else { //If the Viewport Type does not have the Show Title property set to yes, we can't calculate the location //and we just place it int he location from the Linked model. This may not be the same location. ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint); } } else { TaskDialog.Show("Existing Viewport", "Sheet " + sheet.SheetNumber + "-" + sheet.Name + " already contains a Viewport with Detail Number " + detailNumber + ", but detail " + draftingView.Name + " was created."); } } } t.Commit(); itemCount++; } catch (Exception ex) { //This Exception will check if the View already exits in the project if (ex.GetType() == typeof(Autodesk.Revit.Exceptions.ArgumentException)) { TaskDialog.Show("Existing View", "View '" + (string)row.Cells[3].Value + "' already exists and will not be created."); if (t.HasStarted()) { t.RollBack(); } continue; } else { TaskDialog.Show("Error", ex.ToString()); //Check to see if a Transaction is active and roll it back if so if (t.HasStarted()) { t.RollBack(); } //check to see if the Group Transaction has started and roll it back if so if (tGroup.HasStarted()) { tGroup.RollBack(); } } } } } //Commit all of the changes from the Transaction group and other transactions tGroup.Assimilate(); DialogResult = DialogResult.OK; Close(); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; IList <ElementId> elemIdList = new List <ElementId>(); Document templateDoc = null; ViewSheet tagVS = null; #region 打开模板文档,获得将要被复制的元素 //获得文档 templateDoc = uidoc.Application.Application.OpenDocumentFile(@"C:\Users\MyComputer\Desktop\TemplateRes.rvt"); //获得视图 FilteredElementCollector tagView = new FilteredElementCollector(doc); foreach (ViewSheet vs in tagView.OfClass(typeof(ViewSheet))) { if (vs.Name.StartsWith("设计说明(一)")) { tagVS = vs; break; } } //获得元素 ElementMulticategoryFilter categoryFilter = new ElementMulticategoryFilter(new List <BuiltInCategory> { BuiltInCategory.OST_LegendComponents, BuiltInCategory.OST_TextNotes, BuiltInCategory.OST_Lines, BuiltInCategory.OST_GenericAnnotation, BuiltInCategory.OST_InsulationLines, BuiltInCategory.OST_Dimensions, BuiltInCategory.OST_IOSDetailGroups, BuiltInCategory.OST_RevisionClouds, BuiltInCategory.OST_RevisionCloudTags, BuiltInCategory.OST_DetailComponents, BuiltInCategory.OST_DetailComponentTags }); FilteredElementCollector elems = new FilteredElementCollector(doc, tagVS.Id); foreach (Element elem in elems.WherePasses(categoryFilter)) { if (elem.GroupId.IntegerValue == -1) { elemIdList.Add(elem.Id); } } #endregion #region 新建图纸 #endregion #region 制元素 #endregion #region 关闭模板文档 #endregion CopyPasteOptions options = new CopyPasteOptions(); options.SetDuplicateTypeNamesHandler(new CopyHandler()); View v = templateDoc.GetElement(new ElementId(333550)) as View; using (Transaction tran = new Transaction(templateDoc, "CopyLegendView")) { tran.Start(); //创建图纸 ViewSheet viewSheet = ViewSheet.Create(doc, new ElementId(157755)); ViewDrafting.Create(doc, new ElementId(54529)); //View.copy //var s = doc.ActiveView.Scale; //ElementTransformUtils.CopyElements(doc.ActiveView, elemIdList, v, Transform.CreateTranslation(new XYZ(0, 0, 0)), options); //v.Scale = s; tran.Commit(); } return(Result.Succeeded); }
//****************************************************************************************** /// <summary> /// this function imports all views from the list and create new draft views for them based on m_path /// </summary> public void Import(bool argCopy, string argBrowse, string argBaseName, Autodesk.Revit.DB.DWGImportOptions argOpt, List <ViewPath> argViewList, IREXProgress argProgress) { ViewDrafting draftView; DWGImportOptions setDwgImp; IREXProgress Progress = argProgress; DialogMessageExists dlgMsg = new DialogMessageExists(ThisExtension); dlgMsg.Text = Resources.Strings.Texts.REX_ModuleDescription; //getting file list from the directory string[] FileList = Directory.GetFiles(m_path, "*.dwg"); List <string> SelectFileList = new List <string>(); string newname; string strPost = " (" + Resources.Strings.Texts.Freezed + ")"; Progress.Position = 0; Progress.Steps = 2 * argViewList.Count; Progress.Header = Resources.Strings.Texts.FreezeInProgress + " - " + Resources.Strings.Texts.Import; ViewFamilyType viewFamilyType = null; FilteredElementCollector collector = new FilteredElementCollector(m_CommandData.Application.ActiveUIDocument.Document); var viewFamilyTypes = collector.OfClass(typeof(ViewFamilyType)).ToElements(); foreach (Element e in viewFamilyTypes) { ViewFamilyType v = e as ViewFamilyType; if (v.ViewFamily == ViewFamily.Drafting) { viewFamilyType = v; break; } } //importing files to Revit foreach (ViewPath v in argViewList) { draftView = ViewDrafting.Create(m_CommandData.Application.ActiveUIDocument.Document, viewFamilyType.Id); newname = ReplaceForbiddenSigns(v.fullViewName); string tempName = newname; int i = 1; for (;;) { try { draftView.Name = newname + strPost; break; } catch { if (i > 10) { try { draftView.Name = draftView.Name + strPost; } catch { } break; } newname = tempName + "-" + i.ToString(); i++; } } draftView.Scale = v.ViewRevit.Scale; Progress.Step(draftView.Name); //properties setDwgImp = new DWGImportOptions(); setDwgImp.ColorMode = argOpt.ColorMode; setDwgImp.OrientToView = argOpt.OrientToView; setDwgImp.Unit = argOpt.Unit; setDwgImp.CustomScale = argOpt.CustomScale; //import RevitElement el = (RevitElement)draftView; if (File.Exists(v.path)) { ElementId id; m_CommandData.Application.ActiveUIDocument.Document.Import(v.path, setDwgImp, draftView, out id); v.DraftingName = draftView.Name; //copying to user directory if (argCopy) { CopyToUserDirViewPath(v, argBaseName, argBrowse, dlgMsg); } } Progress.Step(draftView.Name); } dlgMsg.Dispose(); }
public Result Execute(ExternalCommandData commandData, ref string messages, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Selection sel = uidoc.Selection; Transaction trans = new Transaction(doc, "ExComm"); trans.Start(); DWGExportOptions options = new DWGExportOptions(); //SUPPORT.PARAMETER.PARAMETER Para = new SUPPORT.PARAMETER.PARAMETER(); View view = doc.ActiveView; ElementId eleid = view.Id; ICollection <ElementId> views = new List <ElementId>(); FilteredElementCollector filter = new FilteredElementCollector(doc); FilteredElementCollector Filter = filter.OfCategory(BuiltInCategory.OST_Views).WhereElementIsNotElementType(); IList <Element> list = Filter.ToElements(); IList <Element> lishname = new List <Element>(); ViewDrafting drafting = null; ElementId newlegend = null; string currentview = doc.ActiveView.ViewName; string test = "Zz_" + currentview + "##"; ElementId id = null; View viewlegend = null; foreach (var ele1 in list) { Parameter parameter = ele1.get_Parameter(BuiltInParameter.VIEW_NAME); string viewname = parameter.AsString(); ViewFamilyType vd = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>() .FirstOrDefault(q => q.ViewFamily == ViewFamily.Drafting); views.Add(doc.ActiveView.Id); doc.Export(@"C:\Autodesk", "exportdwg.dwg", views, options); drafting = ViewDrafting.Create(doc, vd.Id); doc.Regenerate(); DWGImportOptions importOptions = new DWGImportOptions(); importOptions.ColorMode = ImportColorMode.BlackAndWhite; doc.Import(@"C:\Autodesk\\exportdwg.dwg", importOptions, drafting, out id); try { drafting.Name = test; trans.Commit(); commandData.Application.ActiveUIDocument.ActiveView = drafting; } catch { TaskDialog.Show("ERROR", "SECTION NÀY ĐÃ ĐƯỢC TẠO FROZEN"); trans.RollBack(); break; } break; } using (Transaction tx = new Transaction(doc)) { tx.Start("Transaction Name"); Element curElem = doc.GetElement(id); ImportInstance curLink = (ImportInstance)curElem; List <GeometryObject> curveobject = GetLinkedDWGCurves(curLink, doc); foreach (GeometryObject curGeom in curveobject) { if (curGeom.GetType() == typeof(PolyLine)) { // create polyline in current view PolyLine curPolyline = (PolyLine)curGeom; // get polyline coordinate points IList <XYZ> ptsList = curPolyline.GetCoordinates(); for (var i = 0; i <= ptsList.Count - 2; i++) { // create detail curve from polyline coordinates try { DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); } catch { } } } else { try { DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, (Curve)curGeom); } catch { } } } FilteredElementCollector legCollector = new FilteredElementCollector(doc).OfClass(typeof(View)).WhereElementIsNotElementType(); List <View> alllegends = new List <View>(); foreach (ElementId eid in legCollector.ToElementIds()) { View v = doc.GetElement(eid) as View; if (v.ViewType == ViewType.Legend) { alllegends.Add(v); } } newlegend = alllegends.Last().Duplicate(ViewDuplicateOption.WithDetailing); viewlegend = doc.GetElement(newlegend) as View; tx.Commit(); } using (Form_FrozenSection form = new Form_FrozenSection(doc, uiapp)) { form.ShowDialog(); if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return(Result.Cancelled); } if (form.DialogResult == System.Windows.Forms.DialogResult.OK) { using (Transaction tx1 = new Transaction(doc)) { tx1.Start("Transaction Name"); tx1.Commit(); uiapp.ActiveUIDocument.ActiveView = form.vsheet(); } } using (Transaction tx2 = new Transaction(doc)) { tx2.Start("Transaction Name"); XYZ pos = uidoc.Selection.PickPoint(ObjectSnapTypes.None, "Chon diem dat legend"); Viewport.Create(doc, form.vsheet().Id, newlegend, pos); FilteredElementCollector allElementsInView = new FilteredElementCollector(doc, viewlegend.Id).WhereElementIsNotElementType(); ICollection <ElementId> elementsInView = allElementsInView.WhereElementIsNotElementType().Where(x => x.Category != null).Select(x => x.Id).ToList(); doc.Delete(elementsInView); FilteredElementCollector detailine = new FilteredElementCollector(doc, drafting.Id); IList <ElementId> listdetailine = detailine.OfCategory(BuiltInCategory.OST_Lines).WhereElementIsNotElementType().ToElementIds().ToList(); Transform tranform = ElementTransformUtils.GetTransformFromViewToView(viewlegend, doc.ActiveView); ElementTransformUtils.CopyElements(drafting, listdetailine, viewlegend, tranform, new CopyPasteOptions()); viewlegend.Scale = 16; Parameter viewname = viewlegend.LookupParameter("View Name"); string name = form.Viewname(); viewname.Set(name); doc.Delete(drafting.Id); tx2.Commit(); } } return(Result.Succeeded); }
public void ImportDWGsToDraftingViews() { //Get the current document Document curDoc = this.Application.ActiveUIDocument.Document; int counter = 0; //open form using (frmImportDWG curForm = new frmImportDWG()) { //show form curForm.ShowDialog(); if (curForm.DialogResult == System.Windows.Forms.DialogResult.Cancel) { //Result.Cancelled } else { //get selected DWG files List <string> drawingList = curForm.getSelectedDWGs(); using (Transaction curTrans = new Transaction(curDoc, "Import DWGs to Drafting View")) { if (curTrans.Start() == TransactionStatus.Started) { //loop through DWGs, create drafting view and insert foreach (string curDWG in drawingList) { //get view family type for drafting view ElementId curVFT = getDraftingViewFamilyType(curDoc); //create drafting view View curView = ViewDrafting.Create(curDoc, curVFT); //rename drafting view to DWG filename string tmpName = getFilenameFromPath(curDWG); string viewName = tmpName.Substring(0, tmpName.Length - 4); try { curView.Name = viewName; } catch (Exception ex) { TaskDialog.Show("Error", "There is already a drafting view named " + viewName + " in this project file. The view will be named " + curView.Name + " instead."); } //set insert settings DWGImportOptions curImportOptions = new DWGImportOptions(); switch (curForm.getColorSetting()) { case "Invert": curImportOptions.ColorMode = ImportColorMode.Inverted; break; case "Preserve": curImportOptions.ColorMode = ImportColorMode.Preserved; break; default: curImportOptions.ColorMode = ImportColorMode.BlackAndWhite; break; } switch (curForm.getPosSetting()) { case "Origin to Origin": curImportOptions.Placement = ImportPlacement.Origin; break; case "Center to Center": curImportOptions.Placement = ImportPlacement.Centered; break; } //import / link current DWG to current view ElementId curLinkID = null; if (curForm.getInsertType() == "Link") { curDoc.Link(curDWG, curImportOptions, curView, out curLinkID); counter = counter + 1; } else { curDoc.Import(curDWG, curImportOptions, curView, out curLinkID); counter = counter + 1; } } } //commit changes curTrans.Commit(); } } } //alert user TaskDialog.Show("Complete", "Inserted " + counter + " DWG files."); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { if (null == commandData) { throw new ArgumentNullException("commandData"); } Initilize c = new Initilize(); bool success = c.IsAppInitialized(); if (!success) { return(Result.Cancelled); } UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document doc = uidoc.Document; //Set counter int counter = 0; //Open the form using (frmRevitize curForm = new frmRevitize(commandData)) { //Show the form curForm.ShowDialog(); if (curForm.DialogResult == System.Windows.Forms.DialogResult.Cancel) { //The user canceled return(Result.Cancelled); } else { //Get the selected DWG files List <string> drawingList = curForm.getSelectedDWGs(); using (Transaction tx = new Transaction(doc, "Import DWGs to Drafting Views")) { if (tx.Start() == TransactionStatus.Started) { //Loop through DWGs, create Drafting View and insert foreach (string curDWG in drawingList) { //get family type for drafting view ElementId curVFT = getDraftingViewFamilyType(doc); //create drafting view Autodesk.Revit.DB.View curView = ViewDrafting.Create(doc, curVFT); //add the view to the list to be passed out of this createdViewList.Insert(curView); //rename the view to the DWG filename string tmpName = getFilenameFromPath(curDWG); string viewName = tmpName.Substring(0, tmpName.Length - 4); try { curView.Name = viewName; } catch (Exception ex) { TaskDialog.Show("Error", "These is already a Drafting View named " + viewName + "in this project file. The view will be named " + curView.Name + " instead."); throw; } //set insert settings DWGImportOptions curImportOptions = new DWGImportOptions(); switch (curForm.getColorSetting()) { case "Invert": curImportOptions.ColorMode = ImportColorMode.Inverted; break; case "Preserve": curImportOptions.ColorMode = ImportColorMode.Preserved; break; default: curImportOptions.ColorMode = ImportColorMode.BlackAndWhite; break; } switch (curForm.getPosSetting()) { case "Origin to Origin": curImportOptions.Placement = ImportPlacement.Origin; break; case "Center to Center": curImportOptions.Placement = ImportPlacement.Centered; break; } //import / link current DWG to current view ElementId curLinkID = null; if (curForm.getInsertType() == "Link") { doc.Link(curDWG, curImportOptions, curView, out curLinkID); counter = counter + 1; } else { doc.Import(curDWG, curImportOptions, curView, out curLinkID); counter = counter + 1; } } } //commit changes tx.Commit(); } } } //ask user if they want to create a sheet string summeryMessage = " Inserted " + counter + " DWG Files."; bool createSheet = createSheetYesNo(summeryMessage); frmRevitize f1 = new frmRevitize(commandData); f1.Close(); if (createSheet) { cmdSheetsFromViews cmd = new cmdSheetsFromViews(); cmd.Execute(commandData, ref message, elements, createdViewList); } return(Result.Succeeded); }
private void FreezeDrawing(Document doc, View view, OptionsForm optionsForm, String viewName) { // Create the ViewSheetToExport ViewSheet tempViewSheet = CreateViewSheetToExport(doc); // Create the viewport with the view on tempViewSheet _ = Viewport.Create(doc, tempViewSheet.Id, view.Id, new XYZ()); // Create a list, because the method export needs it List <ElementId> viewSheets = new List <ElementId> { tempViewSheet.Id }; // Export doc.Export(this.Directory, this._dwgName, viewSheets, DWGExportOptions.GetPredefinedOptions(doc, optionsForm.DWGExportOptionsName)); // Copying file according to optionsForm if (optionsForm.CopyDWGToFolder) { // try to copy try { File.Copy(this.Directory + "\\" + this._dwgName + ".dwg", String.Join("\\", optionsForm.FolderToSave, viewName + ".dwg")); } catch (IOException ex) { if (MessageBox.Show(ex.Message + " Deseja substituir arquivo?", "Substituir arquivo", MessageBoxButtons.YesNo) == DialogResult.Yes) { File.Copy(this.Directory + "\\" + this._dwgName + ".dwg", String.Join("\\", optionsForm.FolderToSave, viewName + ".dwg"), true); } } } // Creating view ViewFamilyType viewFamilyType = (from element in (new List <Element> (new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .ToElements()).ToList()) where (element as ViewFamilyType).ViewFamily.Equals(ViewFamily.Drafting) select(element as ViewFamilyType)) .First(); View draftingView = ViewDrafting.Create(doc, viewFamilyType.Id); // Import ElementId elementId; doc.Import(this.Directory + "\\" + this._dwgName + ".dwg", optionsForm.DWGImportOptions, draftingView, out elementId); // Deleting aux ViewSheet (according to optionsForm and DWG doc.Delete(tempViewSheet.Id); File.Delete(this.Directory + "\\" + this._dwgName + ".dwg"); }