public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Get application and document objects UIApplication ui_app = commandData.Application; UIDocument ui_doc = ui_app?.ActiveUIDocument; Document doc = ui_doc?.Document; ViewSheet vs = doc.ActiveView as ViewSheet; try { using (Transaction t = new Transaction(doc, "Duplicate Sheet")) { t.Start(); FamilyInstance titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>().First(q => q.OwnerViewId == vs.Id); ViewSheet newsheet = ViewSheet.Create(doc, titleblock.GetTypeId()); newsheet.SheetNumber = vs.SheetNumber + "-COPY"; newsheet.Name = vs.Name; // all views but schedules foreach (ElementId eid in vs.GetAllPlacedViews()) { View ev = doc.GetElement(eid) as View; View newview = null; // legends if (ev.ViewType == ViewType.Legend) { newview = ev; } // all non-legend and non-schedule views else { if (ev.CanViewBeDuplicated(ViewDuplicateOption.AsDependent)) { ElementId newviewid = ev.Duplicate(ViewDuplicateOption.AsDependent); newview = doc.GetElement(newviewid) as View; //newview.Name = ev.Name + "-COPY"; } } foreach (Viewport vp in new FilteredElementCollector(doc).OfClass(typeof(Viewport))) { if (vp.SheetId == vs.Id && vp.ViewId == ev.Id) { BoundingBoxXYZ vpbb = vp.get_BoundingBox(vs); XYZ initialCenter = (vpbb.Max + vpbb.Min) / 2; Viewport newvp = Viewport.Create(doc, newsheet.Id, newview.Id, XYZ.Zero); BoundingBoxXYZ newvpbb = newvp.get_BoundingBox(newsheet); XYZ newCenter = (newvpbb.Max + newvpbb.Min) / 2; ElementTransformUtils.MoveElement(doc, newvp.Id, new XYZ( initialCenter.X - newCenter.X, initialCenter.Y - newCenter.Y, 0)); } } // end for each } // end for each // schedules foreach (ScheduleSheetInstance si in (new FilteredElementCollector(doc).OfClass(typeof(ScheduleSheetInstance)))) { if (si.OwnerViewId == vs.Id) { if (!si.IsTitleblockRevisionSchedule) { foreach (ViewSchedule vsc in new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule))) { if (si.ScheduleId == vsc.Id) { BoundingBoxXYZ sibb = si.get_BoundingBox(vs); XYZ initialCenter = (sibb.Max + sibb.Min) / 2; ScheduleSheetInstance newssi = ScheduleSheetInstance.Create(doc, newsheet.Id, vsc.Id, XYZ.Zero); BoundingBoxXYZ newsibb = newssi.get_BoundingBox(newsheet); XYZ newCenter = (newsibb.Max + newsibb.Min) / 2; ElementTransformUtils.MoveElement(doc, newssi.Id, new XYZ( initialCenter.X - newCenter.X, initialCenter.Y - newCenter.Y, 0)); } } } } }// end foreach t.Commit(); }// end using // Implement Selection Filter to select curves // Measure their total length // Return a message window that displays total length to user // Assuming that everything went right return Result.Succeeded return(Result.Succeeded); } // This is where we "catch" potential errors and define how to deal with them catch (Autodesk.Revit.Exceptions.OperationCanceledException) { // If user decided to cancel the operation return Result.Canceled return(Result.Cancelled); } catch (Exception ex) { // If something went wrong return Result.Failed message = ex.Message; return(Result.Failed); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; View view = doc.ActiveView; FamilySymbol fs = null; FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(FamilySymbol)); collector.OfCategory(BuiltInCategory.OST_TitleBlocks); IEnumerable <Element> titleblock = from element in collector where element.Name.Equals("A0h") select element; foreach (Element element in titleblock) { if (element.Name.Equals("A0h")) { fs = element as FamilySymbol; } } if (fs == null) { TaskDialog.Show("Sheet", "no titleblocks"); } //FamilySymbol fs = collector.FirstElement() as FamilySymbol; if (fs != null) { using (Transaction t = new Transaction(doc, "Create a new ViewSheet")) { t.Start(); try { // Create a sheet view ViewSheet viewSheet = ViewSheet.Create(doc, fs.Id); if (null == viewSheet) { throw new Exception("Failed to create new ViewSheet."); } // Add passed in view onto the center of the sheet UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2, (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2); //viewSheet.AddView(view3D, location); Viewport.Create(doc, viewSheet.Id, view.Id, new XYZ(location.U, location.V, 0)); // Print the sheet out if (viewSheet.CanBePrinted) { TaskDialog taskDialog = new TaskDialog("Revit"); taskDialog.MainContent = "Print the sheet?"; TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No; taskDialog.CommonButtons = buttons; TaskDialogResult result = taskDialog.Show(); if (result == TaskDialogResult.Yes) { viewSheet.Print(); } } t.Commit(); } catch { t.RollBack(); } } } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document document = uidoc.Document; List <string> packageValues = new List <string>(); ICollection <Element> fecSheets = new FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToElements(); foreach (ViewSheet item in fecSheets) { string p = item.LookupParameter("Package").AsString(); if (null != p && !packageValues.Contains(p)) { packageValues.Add(p); } } //List<string> tblocksNames = new List<string>(); ICollection <Element> fecTitleblocks = new FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_TitleBlocks).WhereElementIsElementType().ToElements(); //foreach (Element item in fecTitleblocks) //{ // tblocksNames.Add(item.Name); //} using (var form = new FormCreateSheet()) { form.Packages = packageValues; form.TitleblocksNames = fecTitleblocks; form.ShowDialog(); //if the user hits cancel just drop out of macro if (form.DialogResult == forms.DialogResult.Cancel) { return(Result.Cancelled); } FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(FamilySymbol)); collector.OfCategory(BuiltInCategory.OST_TitleBlocks); FamilySymbol fs = collector.Last() as FamilySymbol; if (form.ChosenTitleblock != null) { fs = form.ChosenTitleblock as FamilySymbol; } if (fs != null) { using (Transaction t = new Transaction(document, "Create a new ViewSheet")) { t.Start(); int sheetQuantity = form.Count; for (int i = 0; i < sheetQuantity; i++) { try { // Create a sheet view ViewSheet viewSheet = ViewSheet.Create(document, fs.Id); if (sheetQuantity == 1) { viewSheet.SheetNumber = form.SheetNumber; } else { viewSheet.SheetNumber = form.SheetNumber + i.ToString(); } viewSheet.LookupParameter("Package").Set(form.PackageName); if (null == viewSheet) { throw new Exception("Failed to create new ViewSheet."); } } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } } t.Commit(); } } } return(Result.Succeeded); }
public ViewPlan setup_view(ViewType vt) { IList <Level> levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).Cast <Level>().OrderBy(l => l.Elevation).ToList(); Transaction trans = new Transaction(doc); ViewFamily vf = ViewFamily.Invalid; if (vt == ViewType.FloorPlan) { vf = ViewFamily.StructuralPlan; } else if (vt == ViewType.CeilingPlan) { vf = ViewFamily.CeilingPlan; } ViewFamilyType FviewFamily = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .First(x => x.ViewFamily == vf); ViewPlan view = new FilteredElementCollector(doc) .OfClass(typeof(ViewPlan)) .Cast <ViewPlan>().FirstOrDefault(q => q.Name == level.Name && q.ViewType == vt); // FIXME : need to filter by vf using (trans = new Transaction(doc)) { trans.Start("View plans"); if (view is null) { view = ViewPlan.Create(doc, FviewFamily.Id, level.Id); } trans.Commit(); } if (vt == ViewType.FloorPlan) { FilteredElementCollector col_ = new FilteredElementCollector(doc); col_.OfClass(typeof(FamilySymbol)); col_.OfCategory(BuiltInCategory.OST_TitleBlocks); FamilySymbol fs = col_.FirstElement() as FamilySymbol; using (trans = new Transaction(doc)) { trans.Start("Sheet"); Family tf = null; //Choose appropriate path string tfamilyPath = @"C:\Users\John\Documents\owncloud\revit\Families\11x8 title block.rfa"; doc.LoadFamily(tfamilyPath, out tf); // Get the available title block from document FamilySymbol FS = null; FilteredElementCollector col__ = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_TitleBlocks); Element TB = null; foreach (Element e in col__) { if (e.Name.Contains("11x8")) { TB = e; } } ViewSheet viewSheet = ViewSheet.Create(doc, TB.Id); UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2, (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2); //viewSheet.AddView(view3D, location); Viewport.Create(doc, viewSheet.Id, view.Id, new XYZ(location.U, location.V, 0)); viewSheet.Name = level.Name; trans.Commit(); } } return(view); }
/// <summary> /// Submits request to create new sheet. /// </summary> /// <param name="app"></param> private void CreateSheet(UIApplication app) { var doc = app.ActiveUIDocument.Document; CentralPath = FileInfoUtil.GetCentralFilePath(doc); IsUpdatingSheet = true; app.Application.FailuresProcessing += FailureProcessing; using (var trans = new Transaction(doc, "CreateSheet")) { trans.Start(); try { ViewSheet sheet; if (SheetTask.IsPlaceholder) { sheet = ViewSheet.CreatePlaceholder(doc); } else { // TODO: This should be exposed to user in Mission Control. var titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).FirstOrDefault(x => x.Category.Name == "Title Blocks"); if (titleblock == null) { IsUpdatingSheet = false; Messenger.Default.Send(new SheetTaskCompletedMessage { Completed = false, Message = "Could not find a valid TitleBlock.", CentralPath = CentralPath }); return; } sheet = ViewSheet.Create(doc, titleblock.Id); } sheet.get_Parameter(BuiltInParameter.SHEET_NUMBER)?.Set(SheetTask.Number); sheet.get_Parameter(BuiltInParameter.SHEET_NAME)?.Set(SheetTask.Name); // (Konrad) We can set this here and pick up in the UI before sending off to MongoDB. var newSheetItem = new SheetItem(sheet, CentralPath) { Tasks = SheetItem.Tasks, CollectionId = SheetItem.CollectionId, Id = SheetItem.Id, IsNewSheet = true // this was overriden to false by default constructor }; SheetItem = newSheetItem; trans.Commit(); IsUpdatingSheet = false; } catch (Exception e) { trans.RollBack(); IsUpdatingSheet = false; Log.AppendLog(LogMessageType.EXCEPTION, "Failed to create sheet."); Messenger.Default.Send(new SheetTaskCompletedMessage { Completed = false, Message = e.Message, CentralPath = CentralPath }); } } // (Konrad) We don't want Revit to keep triggering this even when we are not processing updates. app.Application.FailuresProcessing -= FailureProcessing; }
public void insertImages(Document doc, string path) { //Parameter p; string imagePath = Path.GetDirectoryName(path); imagePath = imagePath + @"\Master Schedule (Images)\"; DirectoryInfo X = new DirectoryInfo(imagePath); FileInfo[] someFiles = X.GetFiles("*.png"); var orderedFiles = someFiles.OrderBy(f => f.FullName); FileInfo[] listOfFiles = orderedFiles.ToArray(); string sheetSize = Command.thisCommand.getSheetSize(); if (sheetSize == "24 x 36") { formatHeight = 22.25; centerLine = (12.0 / 12); imagePerSheet = 4; initialEdgeOffset = (3.875 / 12); finalYLocation = (23.125 / 12); } else if (sheetSize == "30 x 42") { formatHeight = 28.25; centerLine = (15.0 / 12); imagePerSheet = 5; initialEdgeOffset = (3.0 / 12); finalYLocation = (29.125 / 12); } else if (sheetSize == "36 x 48") { formatHeight = 34.25; centerLine = (18.0 / 12); imagePerSheet = 6; initialEdgeOffset = (2.125 / 12); finalYLocation = (35.125 / 12); } else { } int totalImages = listOfFiles.Count(); int fullSheets = totalImages / imagePerSheet; int lastSheetImageQuantity = totalImages - (imagePerSheet * fullSheets); int sheetEndNumber = 70; string sheetBegining; string templateCategory = Command.thisCommand.getTemplateCategory(); if (templateCategory == "ARCHITECTURE") { sheetBegining = "A0."; } else { sheetBegining = "IA0."; } int imgCount = 0; ImageImportOptions iIOptions = new ImageImportOptions(); iIOptions.Resolution = 150; iIOptions.RefPoint = (new XYZ(0, 0, 0)); iIOptions.Placement = BoxPlacement.TopLeft; Autodesk.Revit.DB.View currentImageSheet; SetupProgress(listOfFiles.Count(), "Task: Placing Master Schedule Images"); //Start with full sheets if (fullSheets > 0) { bool fullSheetsExist = true; while (fullSheetsExist) { //search for sheet string searchSheet = sheetBegining + sheetEndNumber.ToString("D2"); currentImageSheet = FindSheet(doc, searchSheet); if (currentImageSheet == null) { ElementId tBlockID = Command.thisCommand.getTitleBlockID(); using (Transaction tx = new Transaction(doc)) { tx.Start("Create Sheet"); ViewSheet myViewSheet = ViewSheet.Create(doc, tBlockID); myViewSheet.Name = "MASTER SCHEDULE"; myViewSheet.SheetNumber = searchSheet; tx.Commit(); } currentImageSheet = FindSheet(doc, searchSheet); SetSheetParameters(currentImageSheet, doc); double startLocation = initialEdgeOffset; for (int imgOnSheet = 1; imgOnSheet <= imagePerSheet; imgOnSheet++) { if (imgCount < listOfFiles.Count()) { iIOptions.RefPoint = (new XYZ(startLocation, finalYLocation, 0)); var imageLocation = listOfFiles[imgCount].Directory.FullName + @"\" + listOfFiles[imgCount].Name; Element e = null; using (Transaction tx = new Transaction(doc)) { tx.Start("Import Image"); doc.Import(imageLocation, iIOptions, currentImageSheet, out e); tx.Commit(); } IncrementProgress(); startLocation = startLocation + (6.875 / 12); imgCount++; } } } else { double startLocation = initialEdgeOffset; for (int imgOnSheet = 1; imgOnSheet <= imagePerSheet; imgOnSheet++) { if (imgCount < listOfFiles.Count()) { iIOptions.RefPoint = (new XYZ(startLocation, finalYLocation, 0)); var imageLocation = listOfFiles[imgCount].Directory.FullName + @"\" + listOfFiles[imgCount].Name; Element e = null; using (Transaction tx = new Transaction(doc)) { tx.Start("Import Image"); doc.Import(imageLocation, iIOptions, currentImageSheet, out e); tx.Commit(); } IncrementProgress(); startLocation = startLocation + (6.875 / 12); imgCount++; } } } sheetEndNumber++; fullSheets--; if (fullSheets < 1) { fullSheetsExist = false; } } } if (lastSheetImageQuantity > 0) { int imageInitialOffset = imagePerSheet - lastSheetImageQuantity; string searchSheet = sheetBegining + sheetEndNumber.ToString("D2"); currentImageSheet = FindSheet(doc, searchSheet); if (currentImageSheet == null) { ElementId tBlockID = Command.thisCommand.getTitleBlockID(); using (Transaction tx = new Transaction(doc)) { tx.Start("Create Sheet"); ViewSheet myViewSheet = ViewSheet.Create(doc, tBlockID); myViewSheet.Name = "MASTER SCHEDULE"; myViewSheet.SheetNumber = searchSheet; tx.Commit(); } currentImageSheet = FindSheet(doc, searchSheet); SetSheetParameters(currentImageSheet, doc); double startLocation = initialEdgeOffset + (imageInitialOffset * (6.875 / 12)); for (int imgOnSheet = imageInitialOffset; imgOnSheet <= imagePerSheet; imgOnSheet++) { if (imgCount < listOfFiles.Count()) { iIOptions.RefPoint = (new XYZ(startLocation, finalYLocation, 0)); var imageLocation = listOfFiles[imgCount].Directory.FullName + @"\" + listOfFiles[imgCount].Name; Element e = null; using (Transaction tx = new Transaction(doc)) { tx.Start("Import Image"); doc.Import(imageLocation, iIOptions, currentImageSheet, out e); tx.Commit(); } IncrementProgress(); startLocation = startLocation + (6.875 / 12); imgCount++; } } } else { double startLocation = initialEdgeOffset + (imageInitialOffset * (6.875 / 12)); for (int imgOnSheet = imageInitialOffset; imgOnSheet <= imagePerSheet; imgOnSheet++) { if (imgCount < listOfFiles.Count()) { iIOptions.RefPoint = (new XYZ(startLocation, finalYLocation, 0)); var imageLocation = listOfFiles[imgCount].Directory.FullName + @"\" + listOfFiles[imgCount].Name; Element e = null; using (Transaction tx = new Transaction(doc)) { tx.Start("Import Image"); doc.Import(imageLocation, iIOptions, currentImageSheet, out e); tx.Commit(); } IncrementProgress(); startLocation = startLocation + (6.875 / 12); imgCount++; } } } } }
private void CreateSheets() { TaskDialog taskDialog = new TaskDialog("Create Sheets"); taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconNone; taskDialog.MainInstruction = "Are you sure you want to create these sheets?"; taskDialog.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No; string EXviewId = string.Empty; string EXviewToAdd = string.Empty; if (this.cbTitleblocks.Items.Count == 0) { TaskDialog.Show("No Titleblocks Loaded", "Make sure you have a titleblock loaded and selected before continuing."); } else { if (taskDialog.Show() == TaskDialogResult.Yes) { Transaction trans = new Transaction(revitDoc, "Create Sheets"); try { #region SELECTS SPECIFIC TITLEBLOCK AND VIEW FROM DOCUMENT var query = from element in titleblockCollector where element.Name == this.titleBlockName select element; List <Element> titleblockList = query.ToList <Element>(); ElementId titleBlockid = titleblockList[0].Id; #endregion #region READ FROM lstSheetsToCreate AND CREATE SHEETS trans.Start(); //STARTS THE Create Sheets TRANSACTION foreach (DataGridViewRow row in dgvSheetToCreate.Rows) { string sheet = string.Empty; sheet = Convert.ToString(row.Cells["Sheet"].Value); char[] separator = new char[] { ':' }; string[] values = sheet.Split(separator, StringSplitOptions.None); string viewToAdd = string.Empty; viewToAdd = Convert.ToString(row.Cells["View"].Value); //SELECT A SPECIFIC VIEW EXviewToAdd = viewToAdd; if (viewToAdd != string.Empty) //IF THERE IS A VIEW ASSIGNED TO A SHEET THEN CREATE A VIEWPORT { ViewSheet vsSheet = ViewSheet.Create(revitDoc, titleBlockid); //CREATES A NEW SHEET vsSheet.SheetNumber = values[0]; //SETS THE SHEET NUMBER vsSheet.Name = values[1]; //SETS THE SHEET NAME ElementId viewId = null; viewId = viewDictionary[viewToAdd]; EXviewId = viewId.ToString(); //GETS THE CENTER OF THE SCREEN TO ADD THE VIEW UV location = new UV((vsSheet.Outline.Max.U - vsSheet.Outline.Min.U) / 2, (vsSheet.Outline.Max.V - vsSheet.Outline.Min.V) / 2); Viewport.Create(revitDoc, vsSheet.Id, viewId, new XYZ(location.U, location.V, 0)); //PLACES THE VIEW ONTO THE SHEET } else //IF THERE IS NOT A VIEW ASSIGNED TO A SHEET THEN JUST CREATE AN EMPTY SHEET { ViewSheet vsSheet = ViewSheet.Create(revitDoc, titleBlockid); //CREATES A NEW SHEET vsSheet.SheetNumber = values[0]; //SETS THE SHEET NUMBER vsSheet.Name = values[1]; //SETS THE SHEET NAME } } trans.Commit(); this.Close(); #endregion } catch (Exception ex) { TaskDialog errorMessage = new TaskDialog("Create Sheet Error"); errorMessage.MainInstruction = "An error occurrued while creating sheets." + Environment.NewLine + "Please read the following error message below"; errorMessage.MainContent = ex.Message + Environment.NewLine + "viewId: " + EXviewId + Environment.NewLine + "View Name: " + EXviewToAdd; errorMessage.Show(); trans.Dispose(); } } } }
////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void CreateViewAndSheet(RoomConversionCandidate candidate) { // Create Sheet var sheet = ViewSheet.Create(doc, TitleBlockId); sheet.Name = candidate.DestinationSheetName; sheet.SheetNumber = candidate.DestinationSheetNumber; // Get Centre before placing any views var sheetCentre = CentreOfSheet(sheet, doc); if (CreatePlan) { // Create plan of room var plan = ViewPlan.Create(doc, GetFloorPlanViewFamilyTypeId(doc), candidate.Room.Level.Id); plan.CropBoxActive = true; plan.ViewTemplateId = ElementId.InvalidElementId; plan.Scale = Scale; var originalBoundingBox = candidate.Room.get_BoundingBox(plan); // Put them on sheets plan.CropBox = CreateOffsetBoundingBox(50000, originalBoundingBox); plan.Name = candidate.DestinationViewName; // Shrink the bounding box now that it is placed var vp = Viewport.Create(doc, sheet.Id, plan.Id, sheetCentre); // Shrink the bounding box now that it is placed plan.CropBox = CreateOffsetBoundingBox(CropRegionEdgeOffset, originalBoundingBox); // FIXME - To set an empty view title - so far this seems to work with the standard revit template... vp.ChangeTypeId(vp.GetValidTypes().Last()); // FIXME Apply a view template // NOTE This could cause trouble with view scales plan.ViewTemplateId = ViewTemplateId; } if (CreateRCP) { // Create rcp of room var rcp = ViewPlan.Create(doc, GetRCPViewFamilyTypeId(doc), candidate.Room.Level.Id); rcp.CropBoxActive = true; rcp.ViewTemplateId = ElementId.InvalidElementId; rcp.Scale = Scale; var originalBoundingBox = candidate.Room.get_BoundingBox(rcp); // Put them on sheets rcp.CropBox = CreateOffsetBoundingBox(50000, originalBoundingBox); rcp.Name = candidate.DestinationViewName; // Shrink the bounding box now that it is placed var vp = Viewport.Create(doc, sheet.Id, rcp.Id, sheetCentre); // Shrink the bounding box now that it is placed rcp.CropBox = CreateOffsetBoundingBox(CropRegionEdgeOffset, originalBoundingBox); // FIXME - To set an empty view title - so far this seems to work with the standard revit template... vp.ChangeTypeId(vp.GetValidTypes().Last()); // FIXME Apply a view template // NOTE This could cause trouble with view scales rcp.ViewTemplateId = ViewTemplateId; } if (CreateAreaPlan) { // Create plan of room var plan = ViewPlan.CreateAreaPlan(doc, AreaPlanTypeId, candidate.Room.Level.Id); //// var plan = ViewPlan.Create(doc, GetAreaPlanViewFamilyTypeId(doc), candidate.Room.Level.Id); plan.CropBoxActive = true; plan.ViewTemplateId = ElementId.InvalidElementId; plan.Scale = Scale; var originalBoundingBox = candidate.Room.get_BoundingBox(plan); // Put them on sheets plan.CropBox = CreateOffsetBoundingBox(50000, originalBoundingBox); plan.Name = candidate.DestinationViewName; // Shrink the bounding box now that it is placed var vp = Viewport.Create(doc, sheet.Id, plan.Id, sheetCentre); // Shrink the bounding box now that it is placed plan.CropBox = CreateOffsetBoundingBox(CropRegionEdgeOffset, originalBoundingBox); // FIXME - To set an empty view title - so far this seems to work with the standard revit template... vp.ChangeTypeId(vp.GetValidTypes().Last()); // FIXME Apply a view template // NOTE This could cause trouble with view scales plan.ViewTemplateId = ViewTemplateId; SCaddinsApp.WindowManager.ShowMessageBox("test"); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; string Path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string ImageFileName = "GitHub\\TokyoAECIndustryDevGroup-Revit\\TokyoAECDev.extension\\TokyoAECDev.tab\\cstest.panel\\OgreCall.pushbutton\\Image\\Ogre.jpg"; string ImagePath = Path + "\\" + ImageFileName; ImagePlacementOptions Opt = new ImagePlacementOptions(); // Create View ViewSheet vs = null; using (Transaction tx = new Transaction(doc)) { tx.Start("Create View"); vs = ViewSheet.Create(doc, ElementId.InvalidElementId); vs.Name = "Ogre"; ImageType IT = ImageType.Create(doc, ImagePath); ImageInstance ImageonSheet = ImageInstance.Create(doc, vs, IT.Id, Opt); Guid schemaGuid = new Guid("67DA32DE-E851-4DAD-B5EA-5450897DBFF0"); Schema schema = Schema.Lookup(schemaGuid); if (schema == null) { SchemaBuilder schemaBuilder = new SchemaBuilder(schemaGuid); schemaBuilder.SetReadAccessLevel(AccessLevel.Public); schemaBuilder.SetWriteAccessLevel(AccessLevel.Public); schemaBuilder.SetVendorId("TokyoAECIndustryDevGroup"); schemaBuilder.SetSchemaName("OgreSample"); schemaBuilder.SetDocumentation("Sheet & ImageInstance ElementId"); FieldBuilder sheetBuilder = schemaBuilder.AddSimpleField("CreatedSheet", typeof(ElementId)); sheetBuilder.SetDocumentation("Sheet ElementId"); FieldBuilder imageBuilder = schemaBuilder.AddSimpleField("CreatedImage", typeof(ElementId)); imageBuilder.SetDocumentation("Sheet ElementId"); schema = schemaBuilder.Finish(); } DataStorage createdData = DataStorage.Create(vs.Document); Entity entity = new Entity(schema); Field sheetfield = schema.GetField("CreatedSheet"); entity.Set <ElementId>(sheetfield, vs.Id, DisplayUnitType.DUT_UNDEFINED); Field imagefield = schema.GetField("CreatedImage"); entity.Set <ElementId>(imagefield, ImageonSheet.Id, DisplayUnitType.DUT_UNDEFINED); createdData.SetEntity(entity); tx.Commit(); } if (vs != null) { uidoc.ActiveView = (View)vs; } return(Result.Succeeded); }
public static void makeSheets(Document curDoc, string[] tblockName, string vPortName, string CSVFile, string sheetType) { //arguments are: document, title block to use for new sheets, viewport type for views and path to CSV file with sheet names, numbers and views //check if title block exists FamilySymbol tblock = null; if (mFunctions.doesTblockExist(curDoc, tblockName) == true) { //get tblock tblock = mFunctions.getTitleblock(curDoc, tblockName); } else { TaskDialog.Show("alert", "Could not find titleblock"); return; } //success and failures List <string> m_s = new List <string>(); List <string> m_f = new List <string>(); //check if CSV file exists if (System.IO.File.Exists(CSVFile) == false) { //file doesn't exist - abort TaskDialog.Show("Error", "The CSV file " + CSVFile + " cannot be found."); return; } //transaction using (Transaction t = new Transaction(curDoc, "Create Sheets")) { if (t.Start() == TransactionStatus.Started) { //the sheet object ViewSheet m_vs = null; //read CSV file and create sheet based on info IList <structSheet> sheetList = null; sheetList = mFunctions.ReadCSV(CSVFile, true); //create sheet for each sheet in list foreach (structSheet curSheet in sheetList) { try { //create sheets if (sheetType == "Placeholder Sheet") { m_vs = ViewSheet.CreatePlaceholder(curDoc); } else { m_vs = ViewSheet.Create(curDoc, tblock.Id); } m_vs.Name = curSheet.sheetName; m_vs.SheetNumber = curSheet.sheetNum; //record success m_s.Add("Created sheet: " + m_vs.SheetNumber + " " + Constants.vbCr); //loop through view string and add views to sheet foreach (string tmpView in curSheet.viewName.Split(new char[] { ',' })) { //get current view View curView = mFunctions.getView(tmpView.Trim(), curDoc); Viewport curVP = null; try { if (Viewport.CanAddViewToSheet(curDoc, m_vs.Id, curView.Id)) { //add it curVP = Viewport.Create(curDoc, m_vs.Id, curView.Id, new XYZ(0, 0, 0)); //center viewport on sheet mFunctions.centerViewOnSheet(curVP, curView, m_vs, curDoc); //change viewport type of plan view to no title ElementId vpTypeID = null; vpTypeID = mFunctions.getViewportTypeID(vPortName, curDoc); curVP.ChangeTypeId(vpTypeID); //record success m_s.Add("Added view: " + curView.Name + " " + Constants.vbCr); } } catch (Exception ex1) { m_f.Add("Could not add view " + tmpView + " to sheet " + m_vs.SheetNumber + Constants.vbCr); } } } catch (Exception ex2) { //record failure m_f.Add("sheet error: " + ex2.Message); } } //commit t.Commit(); //report sheets created if (m_s.Count > 0) { using (TaskDialog m_td = new TaskDialog("Success!!")) { m_td.MainInstruction = "Created Sheets:"; foreach (string x_loopVariable in m_s) { //x = x_loopVariable; m_td.MainContent += x_loopVariable; } //show dialog m_td.Show(); } } if (m_f.Count > 0) { using (TaskDialog m_td2 = new TaskDialog("Failures")) { m_td2.MainInstruction = "Problems:"; foreach (string x_loopVariable in m_f) { //x = x_loopVariable; m_td2.MainContent += x_loopVariable; } //show dialog m_td2.Show(); } } } } }
/// <summary> /// Duplicates the input sheet a number of times. It allows for ViewDuplicateOption for dependent views. /// </summary> /// <param name="m_doc"></param> /// <param name="sourceSheet"></param> /// <param name="copies"></param> /// <param name="dependentOption"></param> private void DuplicateSheets(Document m_doc, ViewSheet sourceSheet, int copies, ViewDuplicateOption dependentOption) { // get Title Block FamilyInstance titleBlock = new FilteredElementCollector(m_doc) .OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks) .Cast <FamilyInstance>() .First(q => q.OwnerViewId == sourceSheet.Id); using (TransactionGroup tg = new TransactionGroup(m_doc, "Duplicate Sheet")) { tg.Start(); for (int i = 0; i < copies; i++) { // create unique sheet number string uniqueSheetNumber = Data.Helpers.CreateUniqueSheetNumber(m_doc, sourceSheet); using (Transaction t = new Transaction(m_doc, "Duplicate Sheet")) { t.Start(); // create new SHEET, new NUMBER and new NAME ViewSheet newSheet = ViewSheet.Create(m_doc, titleBlock.GetTypeId()); newSheet.SheetNumber = uniqueSheetNumber; newSheet.Name = sourceSheet.Name; #region Loop through viewports (except schedules) because GetAllPlacedViews() does not return Schedules foreach (ElementId eid in sourceSheet.GetAllPlacedViews()) { // get view element Autodesk.Revit.DB.View sourceView = m_doc.GetElement(eid) as Autodesk.Revit.DB.View; Autodesk.Revit.DB.View newView = null; // declare newView variable // DUPLICATE views // if view element is legend newView is equal to sourceView if (sourceView.ViewType == ViewType.Legend) { newView = sourceView; } else // for non-legend views { if (sourceView.GetPrimaryViewId() == ElementId.InvalidElementId) // if parent view { ElementId newViewId = sourceView.Duplicate(ViewDuplicateOption.WithDetailing); newView = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View; newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView); //newView.ChangeTypeId(sourceTypeId); } else // if dependent view { ElementId newViewId = sourceView.Duplicate(dependentOption); newView = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View; newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView); //newView.ChangeTypeId(sourceTypeId); } } // CREATE viewport and MOVE it foreach (Viewport vp in new FilteredElementCollector(m_doc).OfClass(typeof(Viewport))) { if (vp.SheetId == sourceSheet.Id && vp.ViewId == sourceView.Id) { XYZ sourceCenter = vp.GetBoxCenter(); ElementId sourceTypeId = vp.GetTypeId(); Viewport newViewport = Viewport.Create(m_doc, newSheet.Id, newView.Id, XYZ.Zero); newViewport.ChangeTypeId(sourceTypeId); Ana_NoOfViewports += 1; // add 1 to the viewport counter XYZ newCenter = newViewport.GetBoxCenter(); ElementTransformUtils.MoveElement(m_doc, newViewport.Id, new XYZ( sourceCenter.X - newCenter.X, sourceCenter.Y - newCenter.Y, 0)); } } } #endregion #region Loop through schedules foreach (ScheduleSheetInstance si in (new FilteredElementCollector(m_doc).OfClass(typeof(ScheduleSheetInstance)))) { if (si.OwnerViewId == sourceSheet.Id) { if (!si.IsTitleblockRevisionSchedule) { foreach (ViewSchedule viewSchedule in new FilteredElementCollector(m_doc).OfClass(typeof(ViewSchedule))) { if (si.ScheduleId == viewSchedule.Id) { XYZ sourceCenter = si.Point; ScheduleSheetInstance newSSheetInstance = ScheduleSheetInstance.Create(m_doc, newSheet.Id, viewSchedule.Id, XYZ.Zero); XYZ newCenter = newSSheetInstance.Point; ElementTransformUtils.MoveElement(m_doc, newSSheetInstance.Id, new XYZ( sourceCenter.X - newCenter.X, sourceCenter.Y - newCenter.Y, 0)); } } } } } #endregion t.Commit(); } } tg.Assimilate(); } }
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); }
public void DuplicateSheet() { UIDocument uidoc = this.ActiveUIDocument; Document revDoc = uidoc.Document; ViewSheet revSheet = revDoc.ActiveView as ViewSheet; #region do stuff if (null != revSheet) { TaskDialog.Show("Title", revSheet.Name + " " + revSheet.SheetNumber); using (Transaction t = new Transaction(revDoc, "Duplicating sheet with parameters")) { var title = new FilteredElementCollector(revDoc).OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>() .First(block => block.OwnerViewId == revSheet.Id); var newSheet = ViewSheet.Create(revDoc, title.GetTypeId()); newSheet.SheetNumber = revSheet.SheetNumber + "1"; newSheet.Name = revSheet.Name; foreach (var item in revSheet.GetAllViewports()) { View newView = null; var actualViewport = revDoc.GetElement(item) as Viewport; var actualView = revDoc.GetElement(actualViewport.ViewId) as View; var actualViewTemp = actualView.ViewTemplateId; if (actualView.ViewType != ViewType.Legend) { var newViewId = actualView.Duplicate(ViewDuplicateOption.WithDetailing); newView = revDoc.GetElement(newViewId) as View; newView.Name = actualView.Name + "Suffix"; if (null != actualViewTemp) { newView.ViewTemplateId = actualViewTemp; } } else { newView = actualView; } var newViewport = Viewport .Create(revDoc, newSheet.Id, newView.Id, actualViewport.GetBoxCenter()); } #region Getting User Created Parameters from the Project var defList = new List <Definition>(); var it = revSheet.ParametersMap.ForwardIterator(); it.Reset(); while (it.MoveNext()) { var param = it.Current as Parameter; var definition = param.Definition as InternalDefinition; if (definition.BuiltInParameter == BuiltInParameter.INVALID) { defList.Add(definition); } } #endregion //Getting User Created Parameters from the Project string parameters = null; foreach (var definition in defList) { var actualParam = revSheet.get_Parameter(definition); var newParam = newSheet.get_Parameter(definition); parameters += actualParam; if (actualParam.HasValue) { newParam.SetValueString(actualParam.AsString()); } } TaskDialog.Show("Parameters", parameters); } } else { TaskDialog.Show("Title", "This view is not a sheet"); } #endregion }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var doc = commandData.Application.ActiveUIDocument.Document; try { var transaction = new Transaction(doc, "创建图纸"); transaction.Start(); #region 创建楼层平面 var level = Level.Create(doc, 1); var viewTypeList = from element in new FilteredElementCollector(doc). OfClass(typeof(ViewFamilyType)) let type = element as ViewFamilyType where type.ViewFamily == ViewFamily.FloorPlan select type; var viewTypeId = viewTypeList?.FirstOrDefault()?.Id; if (viewTypeId == null) { throw new Exception("没有找到楼层平面"); } var viewPlan = ViewPlan.Create(doc, viewTypeId, level.Id); #endregion #region 添加文字 #region 创建文字类型 TextNoteType newTextNoteType; var textFamilyName = "3.5mm 宋体"; var textNoteTypeList = from element in new FilteredElementCollector(doc). OfClass(typeof(TextNoteType)) let type = element as TextNoteType where type.FamilyName == "文字" && type.Name == textFamilyName select type; if (textNoteTypeList.Count() > 0) { newTextNoteType = textNoteTypeList.FirstOrDefault(); } else { textNoteTypeList = from element in new FilteredElementCollector(doc). OfClass(typeof(TextNoteType)) let type = element as TextNoteType where type.FamilyName == "文字" select type; var textNoteType = textNoteTypeList.FirstOrDefault(); newTextNoteType = textNoteType.Duplicate(textFamilyName) as TextNoteType; newTextNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).Set(3.5 / 304.8);//文字大小 newTextNoteType.get_Parameter(BuiltInParameter.TEXT_FONT).Set("宋体"); newTextNoteType.get_Parameter(BuiltInParameter.TEXT_BACKGROUND).Set(1); } #endregion #region 创建文字 var option = new TextNoteOptions(); option.HorizontalAlignment = HorizontalTextAlignment.Center; option.TypeId = newTextNoteType.Id; var textNote = TextNote.Create(doc, viewPlan.Id, new XYZ(0, 0, 0), viewPlan.Name, option); #endregion #endregion #region 应用视图样板 var viewTemplateList = from element in new FilteredElementCollector(doc). OfClass(typeof(ViewPlan)) let view = element as ViewPlan where view.IsTemplate && view.Name == "Architectural Plan" select view; var viewTemplate = viewTemplateList?.FirstOrDefault(); if (viewTemplate == null) { throw new Exception("没有找到视图样板"); } viewPlan.ViewTemplateId = viewTemplate.Id; #endregion #region 添加标注 var dimTypeList = from element in new FilteredElementCollector(doc). OfClass(typeof(DimensionType)) let type = element as DimensionType where type.Name == "Feet & Inches" select type; var targetDimensionType = dimTypeList?.FirstOrDefault(); var wall = doc.GetElement(new ElementId(1101836)) as Wall; var wallLocationCurve = (wall.Location as LocationCurve).Curve; var wallDirection = (wallLocationCurve as Line).Direction; var options = new Options(); options.ComputeReferences = true; var wallSolid = wall.GetGeometryObjects(options).FirstOrDefault() as Solid; var references = new ReferenceArray(); foreach (Face face in wallSolid.Faces) { if (face is PlanarFace pFace && pFace.FaceNormal.CrossProduct(wallDirection).IsAlmostEqualTo(XYZ.Zero) ) { references.Append(face.Reference); } } var offset = 1000 / 304.8; var line = Line.CreateBound(wallLocationCurve.GetEndPoint(0) + XYZ.BasisY * offset, wallLocationCurve.GetEndPoint(1) + XYZ.BasisY * offset); var dimension = doc.Create.NewDimension(viewPlan, line, references); dimension.DimensionType = targetDimensionType; #endregion #region 创建图纸 var sheet = ViewSheet.Create(doc, new ElementId(382615)); #endregion #region 添加视图到图纸 if (Viewport.CanAddViewToSheet(doc, sheet.Id, viewPlan.Id)) { var uv = new XYZ(698 / 304.8 / 2, 522 / 304.8 / 2, 0); var viewPort = Viewport.Create(doc, sheet.Id, viewPlan.Id, uv); } #endregion transaction.Commit(); } catch (Exception e) { return(Result.Failed); } return(Result.Succeeded); }
private static ViewSheet DuplicateSheet(PreviewMap previewMap) { ViewSheet viewSheet = null; try { Document toDoc = previewMap.RecipientModelInfo.Doc; //check existing viewsheets in recipient model FilteredElementCollector collector = new FilteredElementCollector(toDoc);; List <ViewSheet> viewsheets = collector.OfClass(typeof(ViewSheet)).WhereElementIsNotElementType().ToElements().Cast <ViewSheet>().ToList(); var sheets = from view in viewsheets where view.ViewName == previewMap.SourceViewProperties.SheetName && view.SheetNumber == previewMap.SourceViewProperties.SheetNumber select view; if (sheets.Count() > 0) { viewSheet = sheets.First(); } else //create sheet from source model { //ElementId titleBlockTypeId = GetTitleBlockId(previewMap); using (Transaction transaction = new Transaction(toDoc, "Create Sheet")) { transaction.Start(); try { FailureHandlingOptions failOpt = transaction.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor(new WarningMessagePreprocessor()); transaction.SetFailureHandlingOptions(failOpt); viewSheet = ViewSheet.Create(toDoc, ElementId.InvalidElementId); transaction.Commit(); } catch (Exception ex) { string message = ex.Message; transaction.RollBack(); } } if (null != viewSheet) { using (Transaction trans = new Transaction(toDoc, "Copy Title Block")) { FilteredElementCollector vCollector = new FilteredElementCollector(previewMap.SourceModelInfo.Doc, previewMap.SourceViewProperties.SheetObj.Id); List <FamilyInstance> instances = vCollector.OfCategory(BuiltInCategory.OST_TitleBlocks).OfClass(typeof(FamilyInstance)).ToElements().Cast <FamilyInstance>().ToList(); if (instances.Count > 0) { List <ElementId> copiedIds = new List <ElementId>(); CopyPasteOptions options = new CopyPasteOptions(); options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler()); foreach (FamilyInstance instance in instances) { try { trans.Start(); List <ElementId> titleBlock = new List <ElementId>(); titleBlock.Add(instance.Id); ICollection <ElementId> copiedId = ElementTransformUtils.CopyElements(previewMap.SourceViewProperties.SheetObj, titleBlock, viewSheet, Transform.Identity, options); copiedIds.AddRange(copiedId); FailureHandlingOptions failureOptions = trans.GetFailureHandlingOptions(); failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor()); trans.Commit(failureOptions); if (null != copiedId) { trans.Start(); LocationPoint slocation = instance.Location as LocationPoint; XYZ sourcePoint = slocation.Point; FamilyInstance copiedTitleBlock = toDoc.GetElement(copiedId.First()) as FamilyInstance; LocationPoint tlocation = copiedTitleBlock.Location as LocationPoint; XYZ targetPoint = tlocation.Point; XYZ moveVector = sourcePoint - targetPoint; ElementTransformUtils.MoveElement(toDoc, copiedTitleBlock.Id, moveVector); trans.Commit(failureOptions); } } catch (Exception ex) { string message = ex.Message; trans.RollBack(); } } } } using (Transaction transaction = new Transaction(toDoc, "Write Sheet Parameter")) { transaction.Start(); FailureHandlingOptions failOpt = transaction.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor(new WarningMessagePreprocessor()); transaction.SetFailureHandlingOptions(failOpt); try { foreach (Parameter param in previewMap.SourceViewProperties.SheetObj.Parameters) { if (!param.IsReadOnly) { #if RELEASE2014 Parameter rParam = viewSheet.get_Parameter(param.Definition.Name); #elif RELEASE2015 || RELEASE2016 || RELEASE2017 Parameter rParam = viewSheet.LookupParameter(param.Definition.Name); #endif if (null != rParam) { if (rParam.StorageType == param.StorageType) { switch (param.StorageType) { case StorageType.Double: rParam.Set(param.AsDouble()); break; case StorageType.Integer: rParam.Set(param.AsInteger()); break; case StorageType.String: rParam.Set(param.AsString()); break; } } } } } transaction.Commit(); } catch (Exception ex) { string message = ex.Message; transaction.RollBack(); } } return(viewSheet); } } } catch (Exception ex) { errorMessage.AppendLine(previewMap.SourceViewProperties.SheetName + ": failed to create sheet.\n" + ex.Message); //MessageBox.Show(previewMap.SourceViewProperties.SheetName + " Failed to create sheet.\n" + ex.Message, "Duplicate Sheet", MessageBoxButton.OK, MessageBoxImage.Warning); } return(viewSheet); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; // Call WPF for user input using (DuplicateSheetsWPF customWindow = new DuplicateSheetsWPF(commandData)) { // Revit application as window's owner System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(customWindow); helper.Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; customWindow.ShowDialog(); // Retrieve all user input List <int> sheetIds = customWindow.sheetIds; var titleBlockComboBox = customWindow.SelectedComboItemTitleBlock; var copyViews = customWindow.copyViews; var optDuplicate = customWindow.optDuplicate; var optDuplicateDetailing = customWindow.optDuplicateDetailing; var optDuplicateDependant = customWindow.optDuplicateDependant; var viewPrefix = customWindow.viewPrefix; var viewSuffix = customWindow.viewSuffix; var sheetPrefix = customWindow.sheetPrefix; var sheetSuffix = customWindow.sheetSuffix; // Establish duplicate options at top to avoid reassignment inside loop var viewDuplicateOption = ViewDuplicateOption.Duplicate; if (optDuplicateDetailing == true) { viewDuplicateOption = ViewDuplicateOption.WithDetailing; } else if (optDuplicateDependant == true) { viewDuplicateOption = ViewDuplicateOption.AsDependent; } // Group transacation TransactionGroup tg = new TransactionGroup(doc, "Duplicate sheets"); tg.Start(); // List to store sheets duplicated var viewSheetSuccess = new List <string>(); // Duplicate all selected sheets foreach (var sId in sheetIds) { // Retrieve sheet and sheet Id ElementId sheetId = new ElementId(sId); ViewSheet vSheet = doc.GetElement(sheetId) as ViewSheet; // Retrieve title block according to user input FamilyInstance titleblock = null; if (titleBlockComboBox.Content as string != "Current Title Block") { titleblock = titleBlockComboBox.Tag as FamilyInstance; } else { // Retrieve titleblock from current sheet titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>() .First(q => q.OwnerViewId == vSheet.Id); } // Guard against no loaded titleblocks in project or in sheet if (titleblock == null) { titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>() .First(); } // Retrieve elements on sheet var elementsInViewId = new FilteredElementCollector(doc, sheetId).ToElementIds(); // Retrieve viewports in view FilteredElementCollector viewPorts = new FilteredElementCollector(doc, sheetId).OfClass(typeof(Viewport)); // Retrieve schedules in view FilteredElementCollector schedules = new FilteredElementCollector(doc).OwnedByView(sheetId) .OfClass(typeof(ScheduleSheetInstance)); // Retrieve viewSchedules FilteredElementCollector viewSchedules = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule)); // Store copied elements and annotation elements var copiedElementIds = new List <ElementId>(); var annotationElementsId = new List <ElementId>(); using (Transaction t = new Transaction(doc, "Duplicate Sheet")) { // Start transaction to duplicate sheet t.Start(); // Duplicate sheet ViewSheet newsheet = ViewSheet.Create(doc, titleblock.GetTypeId()); newsheet.SheetNumber = sheetPrefix + vSheet.SheetNumber + sheetSuffix; newsheet.Name = vSheet.Name; // Get origin of the titleblock XYZ originTitle = titleblock.GetTransform().Origin; // Check titleblock position Element copyTitleBlock = new FilteredElementCollector(doc).OwnedByView(newsheet.Id).OfCategory(BuiltInCategory.OST_TitleBlocks).FirstElement(); LocationPoint titleLoc = copyTitleBlock.Location as LocationPoint; XYZ titleLocPoint = titleLoc.Point; // Check if title block is in the same position as original if (titleLocPoint.DistanceTo(originTitle) != 0) { // Move it in case it is not titleLoc.Move(originTitle); } // Check if user selected copy views if (copyViews) { // Retrieve all views placed on sheet except schedules foreach (ElementId eId in vSheet.GetAllPlacedViews()) { View origView = doc.GetElement(eId) as View; View newView = null; // Legends if (origView.ViewType == ViewType.Legend) { newView = origView; } // Rest of view types else { if (origView.CanViewBeDuplicated(viewDuplicateOption)) { ElementId newViewId = origView.Duplicate(viewDuplicateOption); newView = doc.GetElement(newViewId) as View; newView.Name = viewPrefix + origView.Name + viewSuffix; } } // Loop through viewports foreach (Viewport vp in viewPorts) { if (vp.SheetId == vSheet.Id && vp.ViewId == origView.Id) { // Retrieve centerpoint of original viewport XYZ center = vp.GetBoxCenter(); // Create viewport in the original spot Viewport newVp = Viewport.Create(doc, newsheet.Id, newView.Id, center); } // Add element in copied list copiedElementIds.Add(vp.Id); } // Add element in copied list copiedElementIds.Add(eId); } // Retrieve and copy schedules foreach (ScheduleSheetInstance sch in schedules) { // Check schedule is not a revision inside titleblock if (!sch.IsTitleblockRevisionSchedule) { foreach (ViewSchedule vsc in viewSchedules) { if (sch.ScheduleId == vsc.Id) { // Retrieve center of schedule XYZ schCenter = sch.Point; // Create schedule in the same position ScheduleSheetInstance newSch = ScheduleSheetInstance.Create(doc, newsheet.Id, vsc.Id, schCenter); } copiedElementIds.Add(vsc.Id); } } } // Duplicate annotation elements foreach (ElementId eId in elementsInViewId) { if (!copiedElementIds.Contains(eId)) { annotationElementsId.Add(eId); } } // Copy annotation elements ElementTransformUtils.CopyElements(vSheet, annotationElementsId, newsheet, null, null); } viewSheetSuccess.Add(newsheet.SheetNumber + " - " + newsheet.Name); // Commit transaction t.Commit(); } } // Commit group transaction tg.Assimilate(); // Display result message to user if (viewSheetSuccess.Count > 0) { TaskDialog.Show("Success", "The following sheets have been duplicated: \n" + string.Join("\n", viewSheetSuccess)); } return(Result.Succeeded); } }