private DWGExportOptions GetDwgOptions() { List <string> setupNames = BaseExportOptions.GetPredefinedSetupNames(this.Doc).ToList(); string prompt = ""; prompt += "setupNames: \n"; foreach (string setupName in setupNames) { prompt += " " + setupName + "\n"; } prompt += "this.SetupName: \n"; prompt += this.SetupName; if (!(from name in setupNames select name.ToLower()).Contains(this.SetupName.ToLower())) { System.Windows.Forms.MessageBox.Show(String.Format("Não há configuração de exportação." + "Crie uma configuração com nome {0}, que será utilizada para exportar.", this.SetupName)); return(null); } DWGExportOptions dwgExportOptions = DWGExportOptions.GetPredefinedOptions(this.Doc, this.SetupName); return(dwgExportOptions); }
public void ExportToDwg() { // get output dir to save DWGs to System.Windows.Forms.FolderBrowserDialog dbox = new System.Windows.Forms.FolderBrowserDialog(); dbox.Description = "Folder to save exported DWG files to"; dbox.ShowNewFolderButton = true; if (dbox.ShowDialog() == DialogResult.OK) { ViewSet viewsToExport = Utils.View.GetAvailableViewsToExport(m_revitApp.ActiveUIDocument.Document); List <ElementId> views = new List <ElementId>(); foreach (Autodesk.Revit.DB.View view in viewsToExport) { views.Add(view.Id); } DWGExportOptions opts = new DWGExportOptions(); // The ACIS option has supposedly been fixed, will have to verify this with the latest code // at a later time. opts.ExportOfSolids = SolidGeometry.ACIS; opts.TargetUnit = ExportUnit.Millimeter; m_revitApp.ActiveUIDocument.Document.Export(dbox.SelectedPath, "", views, opts); } }
private bool ExportDWG(Document doc, string folder, string name, ElementId viewid, string optionname) { DWGExportOptions dwgOptions = null; IList <string> setupNames = BaseExportOptions.GetPredefinedSetupNames(doc); List <ElementId> ids = new List <ElementId>(); foreach (string n in setupNames) { if (n == optionname) { dwgOptions = DWGExportOptions.GetPredefinedOptions(doc, name); } } ids.Add(viewid); try { doc.Export(folder, name, ids, dwgOptions); return(true); } catch (Exception e) { string message = e.Message; return(false); } }
public void ExportToDwg() { // get output dir to save DWGs to System.Windows.Forms.FolderBrowserDialog dbox = new System.Windows.Forms.FolderBrowserDialog(); dbox.Description = "Folder to save exported DWG files to"; dbox.ShowNewFolderButton = true; if (dbox.ShowDialog() == DialogResult.OK) { ViewSet viewsToExport = Utils.View.GetAvailableViewsToExport(m_revitApp.ActiveUIDocument.Document); List<ElementId> views = new List<ElementId>(); foreach (Autodesk.Revit.DB.View view in viewsToExport) { views.Add(view.Id); } DWGExportOptions opts = new DWGExportOptions(); // The ACIS option has supposedly been fixed, will have to verify this with the latest code // at a later time. opts.ExportOfSolids = SolidGeometry.ACIS; opts.TargetUnit = ExportUnit.Millimeter; m_revitApp.ActiveUIDocument.Document.Export(dbox.SelectedPath, "", views, opts); } }
/// <summary> /// Exports the view to DWG with the view name as the output file name. /// </summary> /// <param name="view"></param> /// <param name="destination"></param> /// <param name="exportOptionsName"></param> /// <returns></returns> public static bool ExportDWG(Revit.Elements.Views.View view, string destination, string exportOptionsName) { var doc = DocumentManager.Instance.CurrentDBDocument; var iView = view.InternalElement as Autodesk.Revit.DB.View; doc.Export(destination, iView.ViewName, new[] { iView.Id }, DWGExportOptions.GetPredefinedOptions(doc, exportOptionsName)); return(true); }
public ExportToDwg(Document doc, List <ViewSheet> viewSheets) { this.Doc = doc; this.SetupName = "BFS"; this.DWGExportOptions = this.GetDwgOptions(); this.ViewSheets = viewSheets; this.SheetSizes = this.GetSheetSizes(); this.FileNames = this.GetFileNames(); this.FolderPath = this.GetFolderPath(); }
//exports a given sheet as a DWG file usign the given options //if multiple sheets of same name found exports all public bool ExportSheetAsDWG(string sheetName, string filePath, DWGExportOptions options) { //make sure we have data to work with if (options == null || filePath == string.Empty) { return(false); } //make sure we got sheets to work with ICollection <ElementId> coll = GetSheetIdList(sheetName); if (coll == null) { return(false); } //count how many sheets we have gone through int count = 1; foreach (ElementId id in coll) { using (Transaction t = new Transaction(doc)) { //get the sheet name and check if we need to add a number to the end string name = sheetName; if (count > 1) { name += "-" + count.ToString(); } t.Start("exporting '" + name + "' as a DWG file."); ICollection <ElementId> ele = new List <ElementId>(); ele.Add(id);//add the file to a list as required //attempt to export the sheet and rollback if it fails try { doc.Export(filePath, name, ele, options); } catch { t.RollBack(); return(false); } t.Commit(); } count++; } return(true); }
void Createdrafting(Document doc, Selection sel, UIDocument uidoc, List <ElementId> list) { var list1 = HideIsolate(doc, list); uidoc.RefreshActiveView(); string file = null; string file2 = null; try { using (Transaction tr = new Transaction(doc, "Delete")) { tr.Start(); bool exported = false; ElementId outid = ElementId.InvalidElementId; DWGExportOptions dwgOptions = new DWGExportOptions(); dwgOptions.FileVersion = ACADVersion.R2007; View v = null; var option = new CopyPasteOptions(); option.SetDuplicateTypeNamesHandler(new CopyHandler()); ICollection <ElementId> views = new List <ElementId>(); views.Add(doc.ActiveView.Id); var fd = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); exported = doc.Export(fd, "234567", views, dwgOptions); file = Path.Combine(fd, "234567" + ".dwg"); file2 = Path.Combine(fd, "234567" + ".PCP"); var dwgimport = new DWGImportOptions(); dwgimport.ColorMode = ImportColorMode.BlackAndWhite; if (exported) { v = CreateDrafting(doc); doc.Import(file, dwgimport, v, out outid); File.Delete(file); File.Delete(file2); } if (doc.GetElement(outid).Pinned) { doc.GetElement(outid).Pinned = false; } ElementTransformUtils.CopyElements(v, new List <ElementId> { outid }, doc.ActiveView, Transform.Identity, option); doc.ActiveView.UnhideElements(list1); doc.Delete(v.Id); tr.Commit(); } } catch { File.Delete(file); File.Delete(file2); } }
private void Stream(ArrayList data, DWGExportOptions dwgExpOptions) { data.Add(new Snoop.Data.ClassSeparator(typeof(DWGExportOptions))); data.Add(new Snoop.Data.Bool("Exporting areas", dwgExpOptions.ExportingAreas)); data.Add(new Snoop.Data.String("Export of solids", dwgExpOptions.ExportOfSolids.ToString())); data.Add(new Snoop.Data.String("File version", dwgExpOptions.FileVersion.ToString())); data.Add(new Snoop.Data.String("File version", dwgExpOptions.LayerMapping)); data.Add(new Snoop.Data.String("Line scaling", dwgExpOptions.LineScaling.ToString())); data.Add(new Snoop.Data.String("Prop overrides", dwgExpOptions.PropOverrides.ToString())); data.Add(new Snoop.Data.Bool("Shared coords", dwgExpOptions.SharedCoords)); data.Add(new Snoop.Data.String("Target unit", dwgExpOptions.TargetUnit.ToString())); data.Add(new Snoop.Data.Bool("Merged view", dwgExpOptions.MergedViews)); }
private void DesignAutomationBridge_DesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e) { LogTrace("Design Automation Ready event triggered..."); e.Succeeded = true; DesignAutomationData data = e.DesignAutomationData; Application rvtApp = data.RevitApp; string modelPath = data.FilePath; Document doc = data.RevitDoc; using (Transaction t = new Transaction(doc)) { // Start the transaction t.Start("Export Sheets DWG"); try { var viewSheets = new FilteredElementCollector(doc).OfClass(typeof(ViewSheet)).Cast <ViewSheet>().Where(vw => vw.ViewType == ViewType.DrawingSheet && !vw.IsTemplate); // create DWG export options DWGExportOptions dwgOptions = new DWGExportOptions(); dwgOptions.MergedViews = true; dwgOptions.SharedCoords = true; dwgOptions.FileVersion = ACADVersion.R2018; List <ElementId> views = new List <ElementId>(); foreach (var sheet in viewSheets) { if (!sheet.IsPlaceholder) { views.Add(sheet.Id); } } // For Web Deployment //doc.Export(@"D:\sheetExporterLocation", "TEST", views, dwgOptions); // For Local doc.Export(Directory.GetCurrentDirectory() + "//exportedDwgs", "rvt", views, dwgOptions); } catch (Exception ex) { } // Commit the transaction t.Commit(); } }
/// <summary> /// Collect the parameters and export /// </summary> /// <returns></returns> public override bool Export() { base.Export(); bool exported = false; //parameter : views IList <ElementId> views = new List <ElementId>(); if (m_currentViewOnly) { views.Add(m_activeDoc.ActiveView.Id); } else { foreach (View view in m_selectViewsData.SelectedViews) { views.Add(view.Id); } } // Default values m_exportFileVersion = ACADVersion.R2010; //parameter : DWGExportOptions dwgExportOptions DWGExportOptions dwgExportOptions = new DWGExportOptions(); dwgExportOptions.ExportingAreas = m_exportOptionsData.ExportAreas; dwgExportOptions.ExportOfSolids = m_exportOptionsData.ExportSolid; dwgExportOptions.FileVersion = m_exportFileVersion; dwgExportOptions.LayerMapping = m_exportOptionsData.ExportLayerMapping; dwgExportOptions.LineScaling = m_exportOptionsData.ExportLineScaling; dwgExportOptions.MergedViews = m_exportOptionsData.ExportMergeFiles; dwgExportOptions.PropOverrides = m_exportOptionsData.ExportLayersAndProperties; dwgExportOptions.SharedCoords = m_exportOptionsData.ExportCoorSystem; dwgExportOptions.TargetUnit = m_exportOptionsData.ExportUnit; //Export exported = m_activeDoc.Export(m_exportFolder, m_exportFileName, views, dwgExportOptions); return(exported); }
public static bool ExportDWG(Document document, Autodesk.Revit.DB.View view, string setupName, string fileName, string folder) { bool exported = false; // Get the predefined setups and use the one with the given name. IList <string> setupNames = BaseExportOptions.GetPredefinedSetupNames(document); foreach (string name in setupNames) { if (name.CompareTo(setupName) == 0) { // Export using the predefined options DWGExportOptions dwgOptions = DWGExportOptions.GetPredefinedOptions(document, name); // Export the active view ICollection <ElementId> views = new List <ElementId>(); views.Add(view.Id); // The document has to be saved already, therefore it has a valid PathName. exported = document.Export(folder, fileName, views, dwgOptions); break; } } return(exported); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { //Goal: convert the Viewport centre coordinates on a Sheet to Project Base Point (and then Survey Point) coordinates. //Solution: Find the Viewport's view centre point which is in PBP coordinates. //Problem: the Vieport centre does not always match the View centre. Annotations, Matchlines and Grids can affect the extent of the viewport. //Solution: hide all these categories and find the Viewport centre that matches the View centre. Then find the View centre point in PBP coordinates and translate it //by the vector from Viewport original centre and the centre of the Viewport with the categories hidden. //https://thebuildingcoder.typepad.com/blog/2018/03/boston-forge-accelerator-and-aligning-plan-views.html UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; StringBuilder sb = new StringBuilder(); sb.AppendLine($"Sheet Number,View Centre WCS-X,View Centre WCS-Y,View Centre WCS-Z,Angle to North,Viewport Centre-X,Viewport Centre-Y,Viewport Centre-Z,Viewport Width,Viewport Height,Xref name,Group"); string outputFile = "summary.csv"; ProjectLocation pl = doc.ActiveProjectLocation; Transform ttr = pl.GetTotalTransform().Inverse; ProjectPosition projPosition = doc.ActiveProjectLocation.GetProjectPosition(new XYZ(0, 0, 0)); //rotation IEnumerable <ViewSheet> allSheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets) .WhereElementIsNotElementType().ToElements().Cast <ViewSheet>(); IList <string> dWGExportOptions = DWGExportOptions.GetPredefinedSetupNames(doc); //List<ViewScheduleOption> viewScheduleOptions = Helpers.GetViewScheduleOptions(doc); //find all the sheet list List <ViewSchedule> viewSchedule = Helpers.SheetList(doc); int counter = 0; try { using (var form = new Form1()) { form.CboxExportSettingsDataSource = dWGExportOptions; //set the form sheets form.CboxSheetDataSource = viewSchedule; //set the form title form.Text = "Mx CADD Export Xrefs"; //use ShowDialog to show the form as a modal dialog box. form.ShowDialog(); //if the user hits cancel just drop out of macro if (form.DialogResult == winForm.DialogResult.Cancel) { return(Result.Cancelled); } string destinationFolder = form.TBoxDestinationFolder; //string[] sheetNumbers = form.tboxSelectedSheets.Split(' '); //selected Sheet List ViewSchedule selectedSheetList = form.selectedViewSchedule; //Sheets in selected sheet list var selectedSheets = new FilteredElementCollector(doc, selectedSheetList.Id).OfClass(typeof(ViewSheet)).ToElements().Cast <ViewSheet>(); string exportSettings = form.TBoxExportSettings; int n = selectedSheets.Count(); string s = "{0} of " + n.ToString() + " plans exported..."; string caption = "Export xrefs"; string sheetWithoutArchOrEngViewports = ""; var watch = System.Diagnostics.Stopwatch.StartNew(); using (ProgressForm pf = new ProgressForm(caption, s, n)) { foreach (ViewSheet vs in selectedSheets) { if (pf.abortFlag) { break; } try { //Collect all the viewports on the sheet ICollection <ElementId> viewportIds = vs.GetAllViewports(); //Collect all views on the sheet ISet <ElementId> placedViewsIds = vs.GetAllPlacedViews(); //Filter the views that are plans (Floor,Ceiling,Engineering or Area) and exclude Keyplans. I need the //viewport associate with the view so I cannot reuse this filter List <View> planViews = Helpers.FilterPlanViewport(doc, placedViewsIds); //Collect the viewports that shows a Floor Plan (Architecture) or Structural Plan (Engineering). Dictionary <Viewport, View> viewportViewDict = new Dictionary <Viewport, View>(); //if the sheet does not contain FloorPlan, EngineeringPlan or CeilingPlan, do not export it int hasArchOrStrViewports = 0; foreach (ElementId eid in viewportIds) { Viewport vport = doc.GetElement(eid) as Viewport; View planView = doc.GetElement(vport.ViewId) as View; //Filter the views that are plans (Floor,Ceiling,Engineering or Area) if (planView.ViewType == ViewType.FloorPlan || planView.ViewType == ViewType.EngineeringPlan || planView.ViewType == ViewType.CeilingPlan || planView.ViewType == ViewType.AreaPlan) { //if planview is not a keyplan do not export it if (Helpers.IsNotKeyplan(planView)) { viewportViewDict.Add(vport, planView); //vpPlan.Add(planView); hasArchOrStrViewports += 1; } } } if (hasArchOrStrViewports != 0) { //if the parameter does not exists use the SheetNumber string CAADparameter = vs.LookupParameter("CADD File Name").AsString() ?? vs.SheetNumber; //remove white spaces from the name string fileName = Helpers.RemoveWhitespace(CAADparameter); foreach (Viewport vp in viewportViewDict.Keys) { View vpPlan = viewportViewDict[vp]; //Get the current Viewport Centre for Autocad Viewport XYZ unchangedVPcenter = vp.GetBoxCenter(); //Set its Z value to 0 XYZ flattenVPcenter = new XYZ(unchangedVPcenter.X, unchangedVPcenter.Y, 0); //The current Viewport Centre does not match the view center. Hide all the elements in the view and set the annotation crop to the minimum (3mm). Now the //Viewport centre will match the View centre. We can then use the unchangedCenter to changedCenter vector to move the view centerpoint to the original //viewport centre. //Instead of hiding categories, we can isolate an empty one. Check that this category (OST_Loads) exists in the model or it will throw an error ICollection <ElementId> categoryToIsolate = new List <ElementId>(); Categories groups = doc.Settings.Categories; categoryToIsolate.Add(groups.get_Item(BuiltInCategory.OST_Loads).Id); //This is the new Viewport centre, aligned with the View centre XYZ changedVPcenter = null; // This is the View centre XYZ centroid = null; double scale = 304.8; using (Transaction t = new Transaction(doc, "Hide categories")) { t.Start(); vpPlan.IsolateCategoriesTemporary(categoryToIsolate); //Use the annotation crop region to find the view centroid ViewCropRegionShapeManager vcr = vpPlan.GetCropRegionShapeManager(); //Set the annotation offset to the minimum (3mm) vcr.BottomAnnotationCropOffset = 3 / scale; vcr.TopAnnotationCropOffset = 3 / scale; vcr.LeftAnnotationCropOffset = 3 / scale; vcr.RightAnnotationCropOffset = 3 / scale; //Get the Viewport Center. This will match the View centroid changedVPcenter = vp.GetBoxCenter(); //Find the view centroid using the annotation crop shape (it should always be a rectangle, while the cropbox shape can be a polygon). CurveLoop cloop = vcr.GetAnnotationCropShape(); List <XYZ> pts = new List <XYZ>(); foreach (Curve crv in cloop) { pts.Add(crv.GetEndPoint(0)); pts.Add(crv.GetEndPoint(1)); } //View centroid with elements hidden centroid = Helpers.GetCentroid(pts, pts.Count); t.RollBack(); } //Set ChangedVP center Z value to 0 XYZ flattenChangedVPcenter = new XYZ(changedVPcenter.X, changedVPcenter.Y, 0); //This is the vector from the Viewport original centre to Viewport centre with all the elements hidden and the cropbox set to 3mm evenly XYZ viewPointsVector = (flattenVPcenter - flattenChangedVPcenter) * vpPlan.Scale; //View center adjusted to Viewport original centre (the one to be used in Autocad) XYZ translatedCentroid = centroid + viewPointsVector; //View center per Survey Point coordinates XYZ viewCentreWCS = ttr.OfPoint(translatedCentroid); XYZ viewCentreWCSZ = new XYZ(viewCentreWCS.X, viewCentreWCS.Y, vpPlan.get_BoundingBox(vpPlan).Transform.Origin.Z); //Viewport outline width and height to be used to update the autocad viewport XYZ maxPt = vp.GetBoxOutline().MaximumPoint; XYZ minPt = vp.GetBoxOutline().MinimumPoint; int width = Convert.ToInt32((maxPt.X - minPt.X) * 304.8); int height = Convert.ToInt32((maxPt.Y - minPt.Y) * 304.8); //string xrefName = $"{vs.SheetNumber}-{vp.Id}-xref"; //Set the file name to CAAD parameter string xrefName = $"{fileName}-{vp.Id}-xref"; if (!Helpers.ExportDWG(doc, vpPlan, exportSettings, xrefName, destinationFolder)) { TaskDialog.Show("Error", "Check that the destination folder exists"); } else { counter += 1; } //Check if views are overlapping. If they are, xref should not be bind string group = ""; // TBC dictionary values are working. Seems to work more accurately than planViews. TBC2 they seem to // give the same output //if (Helpers.CheckSingleViewOverlaps(doc, vpPlan, planViews)) if (Helpers.CheckSingleViewOverlaps(doc, vpPlan, viewportViewDict.Values.ToList())) { group = "xref"; } else { group = "bind"; } sb.AppendLine($"{ fileName}," + $"{ Helpers.PointToString(viewCentreWCSZ)}," + $"{projPosition.Angle * 180 / Math.PI}," + $"{Helpers.PointToString(flattenVPcenter)}," + $"{width.ToString()},{height.ToString()}," + $"{xrefName}," + $"{group}"); } //close foreach } //close if sheet has viewports to export else { sheetWithoutArchOrEngViewports += $"{vs.SheetNumber}\n"; } pf.Increment(); } catch (Exception ex) { sheetWithoutArchOrEngViewports += $"{vs.SheetNumber}: {ex.Message}\n"; //TaskDialog.Show("r", vs.SheetNumber); } } File.WriteAllText($"{destinationFolder}\\{outputFile}", sb.ToString()); }//close form watch.Stop(); var elapsedMinutes = watch.ElapsedMilliseconds / 1000 / 60; TaskDialog.Show("Done", $"{counter} plans have been exported and the csv has been created in {elapsedMinutes} min.\nNot exported:\n{sheetWithoutArchOrEngViewports}"); return(Result.Succeeded); }//close form } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); return(Result.Failed); } }
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); }
/// <summary> /// Collect the parameters and export /// </summary> /// <returns></returns> public override bool Export() { base.Export(); bool exported = false; //parameter : views IList<ElementId> views = new List<ElementId>(); if (m_currentViewOnly) { views.Add(m_activeDoc.ActiveView.Id); } else { foreach (View view in m_selectViewsData.SelectedViews) { views.Add(view.Id); } } //parameter : DWGExportOptions dwgExportOptions DWGExportOptions dwgExportOptions = new DWGExportOptions(); dwgExportOptions.ExportingAreas = m_exportOptionsData.ExportAreas; dwgExportOptions.ExportOfSolids = m_exportOptionsData.ExportSolid; dwgExportOptions.FileVersion = m_exportFileVersion; dwgExportOptions.LayerMapping = m_exportOptionsData.ExportLayerMapping; dwgExportOptions.LineScaling = m_exportOptionsData.ExportLineScaling; dwgExportOptions.MergedViews = m_exportOptionsData.ExportMergeFiles; dwgExportOptions.PropOverrides = m_exportOptionsData.ExportLayersAndProperties; dwgExportOptions.SharedCoords = m_exportOptionsData.ExportCoorSystem; dwgExportOptions.TargetUnit = m_exportOptionsData.ExportUnit; //Export exported = m_activeDoc.Export(m_exportFolder, m_exportFileName, views, dwgExportOptions); return exported; }
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; //Handling and Dismissing a Warning Message //https://thebuildingcoder.typepad.com/blog/2013/03/export-wall-parts-individually-to-dxf.html uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing); IList <string> dWGExportOptions = DWGExportOptions.GetPredefinedSetupNames(doc); // List<ViewScheduleOption> viewScheduleOptions = Helpers.GetViewScheduleOptions(doc); //find all the sheet list List <ViewSchedule> viewSchedule = Helpers.SheetList(doc); int counter = 0; try { using (var form = new Form1()) { //set the form export settings form.CboxExportSettingsDataSource = dWGExportOptions; //set the form sheets form.CboxSheetDataSource = viewSchedule; //set the form title form.Text = "Mx CADD Export Sheets"; //use ShowDialog to show the form as a modal dialog box. form.ShowDialog(); //if the user hits cancel just drop out of macro if (form.DialogResult == winForm.DialogResult.Cancel) { return(Result.Cancelled); } string destinationFolder = form.TBoxDestinationFolder; //string[] sheetNumbers = form.tboxSelectedSheets.Split(' '); string exportSettings = form.TBoxExportSettings; DWGExportOptions dwgOptions = DWGExportOptions.GetPredefinedOptions(doc, form.TBoxExportSettings); if (dwgOptions == null) { TaskDialog.Show("Error", "Export setting not found"); return(Result.Failed); } if (dwgOptions.MergedViews == false) { TaskDialog.Show("Error", "Please unselect export view as external reference."); return(Result.Failed); } if (dwgOptions.TargetUnit != ExportUnit.Millimeter) { TaskDialog.Show("Error", "Export units not set to Millimeter. Please fix this before exporting."); return(Result.Failed); } ICollection <ElementId> categoryToIsolate = new List <ElementId>(); Categories groups = doc.Settings.Categories; categoryToIsolate.Add(groups.get_Item(BuiltInCategory.OST_Loads).Id); //selected Sheet List ViewSchedule selectedSheetList = form.selectedViewSchedule; //Sheets in selected sheet list var selectedSheets = new FilteredElementCollector(doc, selectedSheetList.Id).OfClass(typeof(ViewSheet)).ToElements().Cast <ViewSheet>(); int n = selectedSheets.Count(); string s = "{0} of " + n.ToString() + " sheets exported..."; string caption = "Export Sheets"; var watch = System.Diagnostics.Stopwatch.StartNew(); using (ProgressForm pf = new ProgressForm(caption, s, n)) { using (Transaction t = new Transaction(doc, "Hide categories")) { t.Start(); foreach (ViewSheet vs in selectedSheets) { if (pf.abortFlag) { break; } //ViewSheet vs = allSheets.Where(x => x.SheetNumber == sheetNumber).First(); //if the parameter does not exists use the SheetNumber string CAADparameter = vs.LookupParameter("CADD File Name").AsString() ?? vs.SheetNumber; //IList<Parameter> viewParams = vs.GetParameters("CADD File Name"); //string CAADparameter = viewParams.First().AsString(); //remove white spaces from the name string fileName = Helpers.RemoveWhitespace(CAADparameter); //select all the views placed on the sheet ISet <ElementId> views = vs.GetAllPlacedViews(); //select planViewsOnly List <View> planViewsOnly = Helpers.FilterPlanViewport(doc, views); //select keynote and exports them before isolating categories //count the sheets with Floor,Ceiling,Engineering and Area plans int hasArchOrStrViewports = 0; foreach (View planView in planViewsOnly) { if (form.HideViewportContent) { planView.IsolateCategoriesTemporary(categoryToIsolate); } hasArchOrStrViewports += 1; } if (!Helpers.ExportDWG(doc, vs, exportSettings, fileName, destinationFolder)) { TaskDialog.Show("Error", "Check that the destination folder exists"); } else { counter += 1; } pf.Increment(); } t.RollBack(); //t.Commit(); }//close using transaction } watch.Stop(); var elapsedMinutes = watch.ElapsedMilliseconds / 1000 / 60; TaskDialog.Show("Done", $"{counter} sheets have been exported in {elapsedMinutes} min."); }//close using form return(Result.Succeeded); } catch (System.NullReferenceException) { TaskDialog.Show("Error", "Check parameter \"CADD File Name exists\" "); return(Result.Failed); } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); return(Result.Failed); } finally { uiapp.DialogBoxShowing -= new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing); } }
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"); }
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; ViewSet myViewSet = new ViewSet(); DWGExportOptions DwgOptions = new DWGExportOptions { ExportingAreas = false, MergedViews = true }; int c_f = 0; Selection SelectedObjs = uidoc.Selection; ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); foreach (ElementId eid in ids) { try { View view = doc.GetElement(eid) as View; myViewSet.Insert(view); } catch { c_f += 1; } } List <ElementId> viewIds = new List <ElementId>(); Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); Nullable <bool> result = dlg.ShowDialog(); if (result == true) { string path = dlg.FileName; path = path.Remove(dlg.FileName.LastIndexOf(@"\")) + "\\DWG"; var ToRename = new List <String>(); string display = "List of Views:"; foreach (View View in myViewSet) { viewIds.Add(View.Id); String Filename = doc.Title.Replace(" ", "").Replace(".", "-") + "-" + View.Title.Replace(":", " -") + ".dwg"; ToRename.Add(Filename); display = display + Environment.NewLine + View.Title; } if (ToRename.Count == 0) { TaskDialog.Show("Exit", "No Selection to Export"); return(Result.Succeeded); } TaskDialog td = new TaskDialog("Exporting DWGs") { MainInstruction = ToRename.Count + " Views will be Exported to: " + path, CommonButtons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.No, VerificationText = "Compatibility mode (Autocad 2007)", ExpandedContent = display }; if (c_f != 0) { td.MainInstruction = td.MainInstruction + Environment.NewLine + c_f + " Selected item was not a view"; } TaskDialogResult response = td.Show(); if ((response != TaskDialogResult.Cancel) && (response != TaskDialogResult.No)) { if (td.WasVerificationChecked()) { DwgOptions.FileVersion = ACADVersion.R2007; } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } doc.Export(path, "", viewIds, DwgOptions); for (int i = 0; i < ToRename.Count; i++) { string renamed = path + "\\" + ToRename[i].Substring(ToRename[i].LastIndexOf(" - ") + 3); if (File.Exists(renamed)) { File.Delete(renamed); } File.Move(path + "\\" + ToRename[i], renamed); } } } return(Result.Succeeded); }
public View ExportDWG(Document document, View view, out string file) { bool exported = false; ElementId outid = ElementId.InvalidElementId; DWGExportOptions dwgOptions = new DWGExportOptions(); dwgOptions.FileVersion = ACADVersion.R2007; dwgOptions.ExportOfSolids = SolidGeometry.Polymesh; View v = null; ICollection <ElementId> views = new List <ElementId>(); views.Add(view.Id); var pathfile = SettingFreeze.Instance.GetFolderPath(); exported = document.Export(pathfile, "Forzen view", views, dwgOptions); file = Path.Combine(pathfile, "Forzen view" + ".dwg"); if (exported) { TaskDialog taskDialog = new TaskDialog("Freeze View"); taskDialog.Id = "Freeze"; taskDialog.Title = "Freeze Drawing"; taskDialog.TitleAutoPrefix = true; taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconInformation; taskDialog.AllowCancellation = true; taskDialog.MainInstruction = ("Select View Type :"); taskDialog.AddCommandLink((TaskDialogCommandLinkId)1001, "Drafting View"); taskDialog.AddCommandLink((TaskDialogCommandLinkId)1002, "Legend"); taskDialog.CommonButtons = TaskDialogCommonButtons.Cancel; taskDialog.DefaultButton = ((TaskDialogResult)2); TaskDialogResult taskDialogResult = taskDialog.Show(); var dwgimport = new DWGImportOptions(); dwgimport.ColorMode = ImportColorMode.BlackAndWhite; if (taskDialogResult == TaskDialogResult.CommandLink2) { v = GetLegend(document); } else if (taskDialogResult == TaskDialogResult.CommandLink1) { v = CreateDrafting(document); } if (v != null) { document.Import(file, dwgimport, v, out outid); } string strPost = "(Forzen)"; string newname = this.ReplaceForbiddenSigns(doc.ActiveView.Name); string tempName = newname; if (v != null) { int j = 1; for (; ;) { try { v.Name = newname + strPost; break; } catch { bool flag2 = j > 10; if (flag2) { try { v.Name += strPost; } catch { } break; } newname = tempName + "-" + j.ToString(); j++; } } } } return(v); }
public bool ExportToDWG() { bool result = false; try { string inputFolder = GetInputDirectory(); string fileName = Path.GetFileNameWithoutExtension(filePath); bool exported = false; if (Directory.Exists(inputFolder)) { DWGExportOptions options = new DWGExportOptions(); options.ExportOfSolids = SolidGeometry.ACIS; exportUnit = GetExportUnit(); options.TargetUnit = exportUnit; ICollection <ElementId> views = new List <ElementId>(); views.Add(selectedView); Guid transId = new Guid(); using (Transaction trans = new Transaction(m_doc)) { try { transId = Guid.NewGuid(); trans.Start(transId.ToString()); exported = m_doc.Export(inputFolder, fileName, views, options); trans.Commit(); } catch (Exception ex) { trans.RollBack(); MessageBox.Show("DWG Export was failed.\n" + ex.Message, "DWG Export", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } string dwgFileName = Path.Combine(inputFolder, fileName + ".dwg"); if (exported && File.Exists(dwgFileName)) { string unitString = "F"; switch (exportUnit) { case ExportUnit.Default: unitString = "F"; break; case ExportUnit.Inch: unitString = "I"; break; case ExportUnit.Foot: unitString = "F"; break; case ExportUnit.Millimeter: unitString = "M"; break; case ExportUnit.Centimeter: unitString = "C"; break; case ExportUnit.Meter: unitString = "e"; break; } if (InitializeRhino()) { string script = string.Format("-DivaDocumentUnits {0} {1}", unitString, unitString); //document units to foot rhino.RunScript(script, false); script = string.Format("-Import \"{0}\" Enter", dwgFileName); //model and layout unit to foot rhino.RunScript(script, false); rhinoFileName = dwgFileName.Replace(".dwg", ".3dm"); if (File.Exists(rhinoFileName)) { File.Delete(rhinoFileName); } script = string.Format("-SaveAs \"{0}\" Enter", rhinoFileName); rhino.RunScript(script, false); if (File.Exists(rhinoFileName)) { result = true; } } } } catch (Exception ex) { MessageBox.Show("Failed to export to dwg.\n" + ex.Message, "Export to DWG", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(result); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Get application and documnet objects UIApplication uiapp = commandData.Application; Document doc = uiapp.ActiveUIDocument.Document; //DWG Settings export settings DWGExportOptions opt = new DWGExportOptions { HideScopeBox = true, HideReferencePlane = true, SharedCoords = false, MergedViews = true, NonplotSuffix = "NPL", ExportingAreas = false, FileVersion = ACADVersion.R2013, }; //collect sheets in revit FilteredElementCollector viewCollector = new FilteredElementCollector(doc); viewCollector.OfClass(typeof(ViewSheet)); //list of sheets to send to the windows form viewList List <string> listSheetNums = new List <string>(); foreach (ViewSheet view in viewCollector) { listSheetNums.Add(view.SheetNumber); } //initate list of sheets form var l = new Export_Sheets.viewList(listSheetNums); l.ShowDialog(); //select save folder string folderPath = ""; FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { folderPath = folderBrowserDialog1.SelectedPath; } //list of sheets exported List <string> Sheetlist = new List <string>(); //check if revit sheet is in list and export to DWG if it is foreach (ViewSheet view in viewCollector) { foreach (var item in l.ExportViewList) { if (view.SheetNumber == item) { List <ElementId> SheetlistID = new List <ElementId>(); SheetlistID.Add(view.Id); Sheetlist.Add(view.SheetNumber); doc.Export(folderPath, view.SheetNumber + ".dwg", SheetlistID, opt); } } } //Display form listing sheets that were exported var d = new Export_Sheets_Final.ExportedList(Sheetlist); d.ShowDialog(); return(Result.Succeeded); }
private void DesignAutomationBridge_DesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e) { LogTrace("Design Automation Ready event triggered..."); e.Succeeded = true; DesignAutomationData data = e.DesignAutomationData; if (data == null) { throw new ArgumentNullException(nameof(data)); } Application rvtApp = data.RevitApp; if (rvtApp == null) { throw new InvalidDataException(nameof(rvtApp)); } string modelPath = data.FilePath; if (String.IsNullOrWhiteSpace(modelPath)) { throw new InvalidDataException(nameof(modelPath)); } Document doc = data.RevitDoc; if (doc == null) { throw new InvalidOperationException("Could not open document."); } using (Autodesk.Revit.DB.Transaction trans = new Transaction(doc, "ExportToDwgs")) { try { trans.Start(); List <View> views = new FilteredElementCollector(doc) .OfClass(typeof(View)) .Cast <View>() .Where(vw => vw.ViewType == ViewType.DrawingSheet && !vw.IsTemplate ).ToList(); List <ElementId> viewIds = new List <ElementId>(); foreach (View view in views) { ViewSheet viewSheet = view as ViewSheet; viewIds.Add(viewSheet.Id); } DWGExportOptions dwgOptions = new DWGExportOptions(); dwgOptions.MergedViews = true; Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\exportedDwgs"); if (Directory.Exists(Directory.GetCurrentDirectory() + "\\exportedDwgs")) { LogTrace("ExportedDwgs directory exists"); } doc.Export(Directory.GetCurrentDirectory() + "\\exportedDwgs", "result.dwg", viewIds, dwgOptions); LogTrace("Export Process Completedd"); trans.Commit(); } catch (Exception ee) { System.Diagnostics.Debug.WriteLine(ee.Message); System.Diagnostics.Debug.WriteLine(ee.StackTrace); return; } finally { if (trans.HasStarted()) { trans.RollBack(); } } } }
public DWGExportOptions GetExportOptions(bool argCopy) { DWGExportOptions setDwg = new DWGExportOptions(); switch (m_units) { case 0: setDwg.TargetUnit = Autodesk.Revit.DB.ExportUnit.Millimeter; break; case 1: setDwg.TargetUnit = Autodesk.Revit.DB.ExportUnit.Centimeter; break; case 2: setDwg.TargetUnit = Autodesk.Revit.DB.ExportUnit.Meter; break; case 3: setDwg.TargetUnit = Autodesk.Revit.DB.ExportUnit.Inch; break; case 4: setDwg.TargetUnit = Autodesk.Revit.DB.ExportUnit.Foot; break; default: setDwg.TargetUnit = Autodesk.Revit.DB.ExportUnit.Foot; break; } switch (m_lineScale) { case 0: setDwg.LineScaling = Autodesk.Revit.DB.LineScaling.ModelSpace; break; case 1: setDwg.LineScaling = Autodesk.Revit.DB.LineScaling.PaperSpace; break; case 2: setDwg.LineScaling = Autodesk.Revit.DB.LineScaling.ViewScale; break; } setDwg.LayerMapping = combo_layMap.SelectedItem.ToString(); switch (m_layAndProp) { case 0: setDwg.PropOverrides = Autodesk.Revit.DB.PropOverrideMode.ByEntity; break; case 1: setDwg.PropOverrides = Autodesk.Revit.DB.PropOverrideMode.ByLayer; break; case 2: setDwg.PropOverrides = Autodesk.Revit.DB.PropOverrideMode.NewLayer; break; } setDwg.ExportingAreas = m_exportRooms; if (argCopy) { switch (m_coord) { case 0: setDwg.SharedCoords = false; break; case 1: setDwg.SharedCoords = true; break; } } setDwg.ExportOfSolids = Autodesk.Revit.DB.SolidGeometry.Polymesh; return(setDwg); }
public Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { try { m_app = commandData.Application; m_doc = m_app.ActiveUIDocument.Document; DialogResult dr = MessageBox.Show("Would you like to export the active view as DWG and open the file in Rhino?", "Export to DWG", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (dr == DialogResult.Yes) { Autodesk.Revit.DB.View activeView = m_doc.ActiveView; string revitPath = m_doc.PathName; if (!string.IsNullOrEmpty(revitPath)) { string directory = Path.GetDirectoryName(revitPath); if (Directory.Exists(directory)) { string fileName = Path.GetFileNameWithoutExtension(revitPath); DWGExportOptions options = new DWGExportOptions(); options.ExportOfSolids = SolidGeometry.ACIS; options.TargetUnit = ExportUnit.Foot; ICollection <ElementId> views = new List <ElementId>(); views.Add(activeView.Id); bool exported = false; Guid transId = new Guid(); using (Transaction trans = new Transaction(m_doc)) { try { transId = Guid.NewGuid(); trans.Start(transId.ToString()); exported = m_doc.Export(directory, fileName, views, options); trans.Commit(); } catch (Exception ex) { trans.RollBack(); MessageBox.Show("DWG Export was failed.\n" + ex.Message, "DWG Export", MessageBoxButtons.OK, MessageBoxIcon.Information); } } if (exported) { string dwgFileName = Path.Combine(directory, fileName + ".dwg"); if (File.Exists(dwgFileName)) { RegistryKeyManager.SetRegistryKeyValue("RevitOutgoing", exported.ToString()); RegistryKeyManager.SetRegistryKeyValue("RevitOutgoingViewId", activeView.Id.IntegerValue.ToString()); RegistryKeyManager.SetRegistryKeyValue("RevitOutgoingPath", dwgFileName); RegistryKeyManager.SetRegistryKeyValue("RevitOutgoingId", transId.ToString()); //Run Rhino Script dynamic rhino = AppCommand.Instance.RhinoInstance; if (File.Exists(dwgFileName)) { string script = string.Format("-DocumentProperties Enter U Enter U Enter F Enter Enter Enter Enter"); //document units to foot rhino.RunScript(script, false); script = string.Format("-Import \"{0}\" Enter o Enter F Enter y Enter F Enter", dwgFileName); //model and layout unit to foot rhino.RunScript(script, false); string rhinoFileName = dwgFileName.Replace(".dwg", ".3dm"); if (File.Exists(rhinoFileName)) { File.Delete(rhinoFileName); } script = string.Format("-SaveAs \"{0}\" Enter", rhinoFileName); rhino.RunScript(script, false); string weatherFile = @"C:\DIVA\WeatherData\USA_AK_Anchorage.Intl.AP.702730_TMY3.epw"; script = string.Format("-ProjectInfo \"{0}\" Enter", weatherFile); if (File.Exists(rhinoFileName)) { RegistryKeyManager.SetRegistryKeyValue("RhinoIncoming", true.ToString()); RegistryKeyManager.SetRegistryKeyValue("RhinoIncomingPath", rhinoFileName); RegistryKeyManager.SetRegistryKeyValue("RhinoIncoming", transId.ToString()); rhino.Visible = 1; } } } } } } } else if (dr == DialogResult.No) { MessageBox.Show("Please open a view to be exported as DWG format.", "Active View", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show("Failed to send data to Rhino.\n" + ex.Message, "Send to Rhino", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(Result.Succeeded); }
//****************************************************************************************** /// <summary> /// this function export View from the list /// </summary> public List <ViewPath> Export(List <View> argListView, DWGExportOptions setDwg, IREXProgress argProgress) { IREXProgress Progress = argProgress; Progress.Steps = 2 * argListView.Count; Progress.Position = 0; Progress.Header = Resources.Strings.Texts.FreezeInProgress + " - " + Resources.Strings.Texts.Export; List <ViewPath> nameStr = new List <ViewPath>(); m_path = getTempPath(); //reading files from temp directory setDwg.LayerMapping = GetLayMap(setDwg.LayerMapping); foreach (View v in argListView) { List <ElementId> vSet = new List <ElementId>(); if (v != null) { View3D tmp3D = null; Autodesk.Revit.DB.ViewSheet viewSheet = null; bool proceed = false; if (v is Autodesk.Revit.DB.View3D) { try { FilteredElementCollector filteredElementCollector = new FilteredElementCollector(ThisExtension.Revit.ActiveDocument); filteredElementCollector.OfClass(typeof(FamilySymbol)); filteredElementCollector.OfCategory(BuiltInCategory.OST_TitleBlocks); IList <RevitElement> titleBlocks = filteredElementCollector.ToElements(); List <FamilySymbol> familySymbols = new List <FamilySymbol>(); foreach (Element element in titleBlocks) { FamilySymbol f = element as FamilySymbol; if (f != null) { familySymbols.Add(f); } } if (titleBlocks.Count != 0) { Autodesk.Revit.DB.FamilySymbol fs = null; foreach (Autodesk.Revit.DB.FamilySymbol f in familySymbols) { if (null != f) { fs = f; break; } } viewSheet = Autodesk.Revit.DB.ViewSheet.Create(ThisExtension.Revit.ActiveDocument, fs.Id); if (null != viewSheet) { UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2, (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2); try { Viewport.Create(ThisExtension.Revit.ActiveDocument, viewSheet.Id, v.Id, new XYZ(location.U, location.V, 0.0)); } catch { try { XYZ tmpXYZ = new XYZ(-v.ViewDirection.X, -v.ViewDirection.Y, -v.ViewDirection.Z); BoundingBoxXYZ tmpBoundingBox = v.CropBox; bool tmpCropBoxActive = v.CropBoxActive; IList <Element> viewTypes = REXGeometryRvt.FilterElements(ThisExtension.Revit.ActiveDocument, typeof(ViewFamilyType)); ElementId viewTypeid = null; foreach (Element viewType in viewTypes) { ViewFamilyType famType = viewType as ViewFamilyType; if (famType != null && famType.ViewFamily == ViewFamily.ThreeDimensional) { viewTypeid = famType.Id; break; } } if (viewTypeid != null) { tmp3D = View3D.CreateIsometric(ThisExtension.Revit.ActiveDocument, viewTypeid); tmp3D.ApplyViewTemplateParameters(v); tmp3D.CropBox = tmpBoundingBox; Viewport.Create(ThisExtension.Revit.ActiveDocument, viewSheet.Id, tmp3D.Id, new XYZ(location.U, location.V, 0.0)); } } catch { } } vSet.Add(viewSheet.Id); proceed = true; } } } catch { } } else { vSet.Add(v.Id); proceed = true; } if (proceed) { string fam = v.get_Parameter(BuiltInParameter.VIEW_FAMILY).AsString(); Progress.Step(fam + "-" + v.Name); string vName = ValidateFileName(v.Name); m_CommandData.Application.ActiveUIDocument.Document.Export(m_path, fam + "-" + vName, vSet, setDwg); nameStr.Add(new ViewPath(m_path + "\\" + fam + "-" + vName + ".dwg", v, fam + "-" + v.Name)); Progress.Step(fam + "-" + v.Name); if (viewSheet != null) { ElementId elementId = viewSheet.Id; ThisExtension.Revit.ActiveDocument.Delete(elementId); } if (tmp3D != null) { ElementId elementId = tmp3D.Id; ThisExtension.Revit.ActiveDocument.Delete(elementId); } } } } return(nameStr); }
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; ViewSet myViewSet = new ViewSet(); //create ExportOptions DWGExportOptions DwgOptions = new DWGExportOptions(); DwgOptions.ExportingAreas = false; DwgOptions.MergedViews = true; NavisworksExportOptions nweOptions = new NavisworksExportOptions(); nweOptions.ExportScope = NavisworksExportScope.View; // create a new ViewSet - add views to it that match the desired criteria string match = "Export"; // Use Title on Sheet for select the export views foreach (View vs in new FilteredElementCollector(doc).OfClass(typeof(View)).Cast <View>()) { if (vs.IsTemplate == false && vs.Category != null && vs.get_Parameter(BuiltInParameter.VIEW_DESCRIPTION).AsString().Contains(match)) { myViewSet.Insert(vs); } } List <ElementId> viewIds = new List <ElementId>(); string display = "List of Views:"; Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); Nullable <bool> result = dlg.ShowDialog(); if (result == true) { string path = dlg.FileName; string rootpath = path.Remove(dlg.FileName.LastIndexOf(@"\")); path = path.Remove(dlg.FileName.LastIndexOf(@"\")) + "\\NWC"; TaskDialog td = new TaskDialog("Exporting DWGs"); td.MainInstruction = myViewSet.Size + " Views will be Exported to: " + path; td.CommonButtons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.No; td.ExpandedContent = display; TaskDialogResult response = td.Show(); if ((response != TaskDialogResult.Cancel) && (response != TaskDialogResult.No)) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } TaskDialog.Show("Exporting to Navis and DWG", myViewSet.Size + " Views will be Exported to: " + rootpath); // export var ToRename = new List <String>(); foreach (View View in myViewSet) { nweOptions.ViewId = View.Id; doc.Export(path, View.get_Parameter(BuiltInParameter.VIEW_NAME).AsString() + ".nwc", options: nweOptions); viewIds.Add(View.Id); display = display + Environment.NewLine + View.Title; String Filename = doc.Title.Replace(" ", "") + "-" + View.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).AsValueString() + " - " + View.Name + ".dwg"; ToRename.Add(Filename); } path = rootpath + "\\DWG"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } doc.Export(path, "", viewIds, DwgOptions); for (int i = 0; i < ToRename.Count; i++) { if (File.Exists(path + "\\" + ToRename[i].Substring(ToRename[i].LastIndexOf(" - ") + 3))) { File.Delete(path + "\\" + ToRename[i].Substring(ToRename[i].LastIndexOf(" - ") + 3)); } File.Move(path + "\\" + ToRename[i], path + "\\" + ToRename[i].Substring(ToRename[i].LastIndexOf(" - ") + 3)); } } } return(Result.Succeeded); }
public View ExportDWG(Document document, View view, out string file) { bool exported = false; ElementId outid = ElementId.InvalidElementId; DWGExportOptions dwgOptions = new DWGExportOptions(); dwgOptions.FileVersion = ACADVersion.R2007; dwgOptions.ExportOfSolids = SolidGeometry.Polymesh; dwgOptions.ACAPreference = ACAObjectPreference.Geometry; dwgOptions.MergedViews = true; dwgOptions.PropOverrides = PropOverrideMode.ByEntity; View v = null; ICollection <ElementId> views = new List <ElementId>(); views.Add(view.Id); var pathfile = SettingFreeze.Instance.GetFolderPath(); if (view is View3D) { List <ElementId> vSet = new List <ElementId>(); bool flag = view != null; if (flag) { View3D tmp3D = null; ViewSheet viewSheet = null; bool proceed = false; try { FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc); filteredElementCollector.OfClass(typeof(FamilySymbol)); filteredElementCollector.OfCategory(BuiltInCategory.OST_TitleBlocks); IList <Element> titleBlocks = filteredElementCollector.ToElements(); List <FamilySymbol> familySymbols = new List <FamilySymbol>(); foreach (Element element in titleBlocks) { FamilySymbol f = element as FamilySymbol; bool flag3 = f != null; if (flag3) { familySymbols.Add(f); } } bool flag4 = titleBlocks.Count != 0; if (flag4) { FamilySymbol fs = null; foreach (FamilySymbol f2 in familySymbols) { bool flag5 = f2 != null; if (flag5) { fs = f2; break; } } viewSheet = ViewSheet.Create(doc, fs.Id); bool flag6 = viewSheet != null; if (flag6) { UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2.0, (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2.0); try { Viewport.Create(doc, viewSheet.Id, view.Id, new XYZ(location.U, location.V, 0.0)); } catch { try { XYZ tmpXYZ = new XYZ(-view.ViewDirection.X, -view.ViewDirection.Y, -view.ViewDirection.Z); BoundingBoxXYZ tmpBoundingBox = view.CropBox; bool tmpCropBoxActive = view.CropBoxActive; IList <Element> viewTypes = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).ToElements(); ElementId viewTypeid = null; foreach (Element viewType in viewTypes) { ViewFamilyType famType = viewType as ViewFamilyType; bool flag7 = famType != null && famType.ViewFamily == ViewFamily.ThreeDimensional; if (flag7) { viewTypeid = famType.Id; break; } } bool flag8 = viewTypeid != null; if (flag8) { tmp3D = View3D.CreateIsometric(doc, viewTypeid); tmp3D.ApplyViewTemplateParameters(view); tmp3D.CropBox = tmpBoundingBox; Viewport.Create(doc, viewSheet.Id, tmp3D.Id, new XYZ(location.U, location.V, 0.0)); } } catch { } } vSet.Add(viewSheet.Id); proceed = true; } } } catch { } bool flag9 = proceed; if (flag9) { exported = document.Export(pathfile, view.Name, vSet, dwgOptions); bool flag10 = viewSheet != null; if (flag10) { ElementId elementId = viewSheet.Id; doc.Delete(elementId); } bool flag11 = tmp3D != null; if (flag11) { ElementId elementId2 = tmp3D.Id; doc.Delete(elementId2); } } } } else { exported = document.Export(pathfile, view.Name, views, dwgOptions); } if (tmp3D != null) { file = Path.Combine(pathfile, tmp3D.Name + ".dwg"); } else { file = Path.Combine(pathfile, view.Name + ".dwg"); } if (exported) { TaskDialog taskDialog = new TaskDialog("Freeze View"); taskDialog.Id = "Freeze"; taskDialog.Title = "Freeze Drawing"; taskDialog.TitleAutoPrefix = true; taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconInformation; taskDialog.AllowCancellation = true; taskDialog.MainInstruction = ("Select View Type :"); taskDialog.AddCommandLink((TaskDialogCommandLinkId)1001, "Drafting View"); taskDialog.AddCommandLink((TaskDialogCommandLinkId)1002, "Legend"); taskDialog.CommonButtons = TaskDialogCommonButtons.Cancel; taskDialog.DefaultButton = ((TaskDialogResult)2); TaskDialogResult taskDialogResult = taskDialog.Show(); var dwgimport = new DWGImportOptions(); dwgimport.ColorMode = ImportColorMode.BlackAndWhite; dwgimport.ThisViewOnly = true; dwgimport.OrientToView = true; dwgimport.Placement = ImportPlacement.Origin; if (taskDialogResult == TaskDialogResult.CommandLink2) { v = GetLegend(document); } else if (taskDialogResult == TaskDialogResult.CommandLink1) { v = CreateDrafting(document); } if (v != null) { document.Import(file, dwgimport, v, out outid); } string strPost = "(Forzen)"; string newname = this.ReplaceForbiddenSigns(doc.ActiveView.Name); string tempName = newname; if (v != null) { int j = 1; for (; ;) { try { v.Name = newname + strPost; break; } catch { bool flag2 = j > 10; if (flag2) { try { v.Name += strPost; } catch { } break; } newname = tempName + "-" + j.ToString(); j++; } } } } return(v); }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; List <Element> titleBlocks = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_TitleBlocks) .WhereElementIsNotElementType() .ToElements() .ToList(); List <ElementId> elt = uidoc.Selection.GetElementIds().ToList(); List <Element> beta = new List <Element>(); foreach (ElementId i in elt) { beta.Add(doc.GetElement(i)); } ViewSheet a; a = doc.GetElement(elt.First()) as ViewSheet; ViewSet b = new ViewSet(); List <List <Element> > elementOnSheet = new List <List <Element> >(); for (int i = 0; i < elt.Count(); i++) { List <Element> sheetEl = new List <Element>(); foreach (Element e in new FilteredElementCollector(doc).OwnedByView(elt[i])) { sheetEl.Add(e); } elementOnSheet.Add(sheetEl); } List <Element> titleOnSheet = new List <Element>(); for (int i = 0; i < elt.Count(); i++) { titleOnSheet.Add(null); foreach (Element e in elementOnSheet[i]) { foreach (Element tb in titleBlocks) { if (e.Id == tb.Id) { titleOnSheet[i] = tb; } } } } List <int> formatA = new List <int>(); List <int> kratn = new List <int>(); List <int> knign = new List <int>(); for (int i = 0; i < titleOnSheet.Count(); i++) { try { formatA.Add(titleOnSheet[i].LookupParameter("Формат А").AsInteger()); kratn.Add(titleOnSheet[i].LookupParameter("Кратность").AsInteger()); knign.Add(titleOnSheet[i].LookupParameter("Книжная ориентация").AsInteger()); } catch (Exception) { } } string namePrefix = "Export"; //string nameOfExportDWFX = "AutoExport " + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString(); List <string> viewName = new List <string>(); List <ViewSheet> listNum = new List <ViewSheet>(); foreach (ElementId i in elt) { b.Insert(doc.GetElement(i) as ViewSheet); listNum.Add(doc.GetElement(i) as ViewSheet); } DWGExportOptions options = new DWGExportOptions(); options.MergedViews = true; options.Colors = ExportColorMode.TrueColorPerView; options.FileVersion = ACADVersion.R2013; //options. string dir = doc.PathName.Substring(0, doc.PathName.Length - doc.Title.Length - 4); ModelPath mp = doc.GetWorksharingCentralModelPath(); string vmp = ModelPathUtils.ConvertModelPathToUserVisiblePath(mp); int arr = 0; for (int i = vmp.Length - 1; i != 0; i--) { if (vmp.ElementAt(i) == '\\') { arr = i; break; } } //string newPath = Path.GetTempPath(); string newPath = vmp.Substring(0, arr + 1) + "DWG"; for (int i = 0; i < listNum.Count(); i++) { viewName.Add(newPath + listNum[i].SheetNumber + listNum[i].Name + ".dwfx"); } string fileName = newPath + namePrefix + ".dwg"; System.IO.DirectoryInfo printDir = System.IO.Directory.CreateDirectory(newPath); using (Transaction tr = new Transaction(doc, "MyExort")) { tr.Start(); /* * foreach (ViewSheet i in listNum) * { * ViewSet vSet = new ViewSet(); * vSet.Insert(i); * * doc.Export(newPath, i.SheetNumber + i.Name,vSet, options); * } */ doc.Export(newPath, "", elt, options); //doc.Export(newPath.Substring(0, newPath.Length - 1), namePrefix, b, options); tr.Commit(); } //Form1 SheetControl = new Form1(); //SheetControl.ShowDialog(); //string[] amm=Directory.GetFiles(newPath+"\\"); return(Result.Succeeded); }
CollectEvent(object sender, CollectorEventArgs e) { // cast the sender object to the SnoopCollector we are expecting Collector snoopCollector = sender as Collector; if (snoopCollector == null) { Debug.Assert(false); // why did someone else send us the message? return; } // see if it is a type we are responsible for Color color = e.ObjToSnoop as Color; if (color != null) { Stream(snoopCollector.Data(), color); return; } LayoutRule layoutRule = e.ObjToSnoop as LayoutRule; if (layoutRule != null) { Stream(snoopCollector.Data(), layoutRule); return; } FormatOptions formatOptions = e.ObjToSnoop as FormatOptions; if (formatOptions != null) { Stream(snoopCollector.Data(), formatOptions); return; } CurtainGrid curtainGrid = e.ObjToSnoop as CurtainGrid; if (curtainGrid != null) { Stream(snoopCollector.Data(), curtainGrid); return; } CurtainCell curtainCell = e.ObjToSnoop as CurtainCell; if (curtainCell != null) { Stream(snoopCollector.Data(), curtainCell); return; } RebarHostData rebarHostData = e.ObjToSnoop as RebarHostData; if (rebarHostData != null) { Stream(snoopCollector.Data(), rebarHostData); return; } Leader leader = e.ObjToSnoop as Leader; if (leader != null) { Stream(snoopCollector.Data(), leader); return; } AreaVolumeSettings areaSettings = e.ObjToSnoop as AreaVolumeSettings; if (areaSettings != null) { Stream(snoopCollector.Data(), areaSettings); return; } ViewSheetSetting viewSheetSetting = e.ObjToSnoop as ViewSheetSetting; if (viewSheetSetting != null) { Stream(snoopCollector.Data(), viewSheetSetting); return; } Autodesk.Revit.UI.Events.DialogBoxData dlgBoxData = e.ObjToSnoop as Autodesk.Revit.UI.Events.DialogBoxData; if (dlgBoxData != null) { Stream(snoopCollector.Data(), dlgBoxData); return; } Construction construct = e.ObjToSnoop as Construction; if (construct != null) { Stream(snoopCollector.Data(), construct); return; } FamilyElementVisibility famElemVisib = e.ObjToSnoop as FamilyElementVisibility; if (famElemVisib != null) { Stream(snoopCollector.Data(), famElemVisib); return; } FamilyManager famManager = e.ObjToSnoop as FamilyManager; if (famManager != null) { Stream(snoopCollector.Data(), famManager); return; } FamilyParameter famParam = e.ObjToSnoop as FamilyParameter; if (famParam != null) { Stream(snoopCollector.Data(), famParam); return; } FamilyType famType = e.ObjToSnoop as FamilyType; if (famType != null) { Stream(snoopCollector.Data(), famType); return; } MEPSpaceConstruction mepSpaceConstuct = e.ObjToSnoop as MEPSpaceConstruction; if (mepSpaceConstuct != null) { Stream(snoopCollector.Data(), mepSpaceConstuct); return; } BuildingSiteExportOptions bldSiteExpOptions = e.ObjToSnoop as BuildingSiteExportOptions; if (bldSiteExpOptions != null) { Stream(snoopCollector.Data(), bldSiteExpOptions); return; } DGNExportOptions dgnExpOptions = e.ObjToSnoop as DGNExportOptions; if (dgnExpOptions != null) { Stream(snoopCollector.Data(), dgnExpOptions); return; } DWFExportOptions dwfExpOptions = e.ObjToSnoop as DWFExportOptions; if (dwfExpOptions != null) { Stream(snoopCollector.Data(), dwfExpOptions); return; } DWGExportOptions dwgExpOptions = e.ObjToSnoop as DWGExportOptions; if (dwgExpOptions != null) { Stream(snoopCollector.Data(), dwgExpOptions); return; } DWGImportOptions dwgImpOptions = e.ObjToSnoop as DWGImportOptions; if (dwgImpOptions != null) { Stream(snoopCollector.Data(), dwgImpOptions); return; } FBXExportOptions fbxExpOptions = e.ObjToSnoop as FBXExportOptions; if (fbxExpOptions != null) { Stream(snoopCollector.Data(), fbxExpOptions); return; } TrussMemberInfo trussInfo = e.ObjToSnoop as TrussMemberInfo; if (trussInfo != null) { Stream(snoopCollector.Data(), trussInfo); return; } VertexIndexPair vertIndPair = e.ObjToSnoop as VertexIndexPair; if (vertIndPair != null) { Stream(snoopCollector.Data(), vertIndPair); return; } PointElementReference ptElemRef = e.ObjToSnoop as PointElementReference; if (ptElemRef != null) { Stream(snoopCollector.Data(), ptElemRef); return; } Autodesk.Revit.DB.Architecture.BoundarySegment boundSeg = e.ObjToSnoop as Autodesk.Revit.DB.Architecture.BoundarySegment; if (boundSeg != null) { Stream(snoopCollector.Data(), boundSeg); return; } PointLocationOnCurve ptLocOnCurve = e.ObjToSnoop as PointLocationOnCurve; if (ptLocOnCurve != null) { Stream(snoopCollector.Data(), ptLocOnCurve); return; } Entity entity = e.ObjToSnoop as Entity; if (entity != null) { Stream(snoopCollector.Data(), entity); return; } Field field = e.ObjToSnoop as Field; if (field != null) { Stream(snoopCollector.Data(), field); return; } ExtensibleStorageField storeagefield = e.ObjToSnoop as ExtensibleStorageField; if (storeagefield != null) { Stream(snoopCollector.Data(), storeagefield); return; } IList <Autodesk.Revit.DB.BoundarySegment> boundSegs = e.ObjToSnoop as IList <Autodesk.Revit.DB.BoundarySegment>; if (boundSegs != null) { Stream(snoopCollector.Data(), boundSegs); return; } if (e.ObjToSnoop is KeyValuePair <String, String> ) { KeyValuePair <String, String> stringspair = (KeyValuePair <String, String>)e.ObjToSnoop; Stream(snoopCollector.Data(), stringspair); return; } Schema schema = e.ObjToSnoop as Schema; if (schema != null) { Stream(snoopCollector.Data(), schema); return; } ElementId elemId = e.ObjToSnoop as ElementId; if (elemId != null) { Stream(snoopCollector.Data(), elemId); return; } PlanViewRange plvr = e.ObjToSnoop as PlanViewRange; if (plvr != null) { Stream(snoopCollector.Data(), plvr); return; } //TF RebarConstraintsManager rbcm = e.ObjToSnoop as RebarConstraintsManager; if (rbcm != null) { Stream(snoopCollector.Data(), rbcm); return; } RebarConstrainedHandle rbch = e.ObjToSnoop as RebarConstrainedHandle; if (rbch != null) { Stream(snoopCollector.Data(), rbch); return; } RebarConstraint rbc = e.ObjToSnoop as RebarConstraint; if (rbc != null) { Stream(snoopCollector.Data(), rbc); return; } //TFEND if (Utils.IsSupportedType(e.ObjToSnoop) && e.ObjToSnoop != null) { Utils.StreamWithReflection(snoopCollector.Data(), e.ObjToSnoop.GetType(), e.ObjToSnoop); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiApp = commandData.Application; string keystr = @"Software\FamilyToDWG"; string revityear = "2017"; string subkeystr = "TemplateLocation" + revityear; RegistryKey key = Registry.CurrentUser.OpenSubKey(keystr, true); if (key == null) { key = Registry.CurrentUser.CreateSubKey(keystr); key.SetValue(subkeystr, ""); } if (key.GetValue(subkeystr, null).ToString() == "" || File.Exists(key.GetValue(subkeystr).ToString()) == false) { var templateFD = new OpenFileDialog(); templateFD.Filter = "rte files (*.rte)|*.rte"; templateFD.Title = "Choose a Template"; templateFD.ShowDialog(); string docdir = templateFD.FileName; key.SetValue(subkeystr, @docdir); } if (key.GetValue(subkeystr, null).ToString() == null) { return(Result.Failed); } Autodesk.Revit.DB.Document uiDoc; try { uiDoc = uiApp.Application.NewProjectDocument(key.GetValue(subkeystr).ToString()); } catch { return(Result.Failed); } if (uiDoc == null) { return(Result.Failed); } if (!Directory.Exists(@"C:\temp\")) { Directory.CreateDirectory(@"C:\temp\"); } if (File.Exists(@"C:\temp\new_project.rvt")) { File.Delete(@"C:\temp\new_project.rvt"); } SaveAsOptions options1 = new SaveAsOptions(); options1.OverwriteExistingFile = true; uiDoc.SaveAs(@"C:/temp/new_project.rvt", options1); uiApp.OpenAndActivateDocument(@"C:/temp/new_project.rvt"); var FD = new OpenFileDialog(); FD.Filter = "rfa files (*.rfa)|*.rfa"; FD.Title = "Choose A RevitRFA Family file"; FD.ShowDialog(); string filename = FD.SafeFileName; string filedir = FD.FileName.Replace(filename, ""); if (File.Exists(FD.FileName)) { using (Transaction tx = new Transaction(uiDoc)) { tx.Start("Load Family"); Autodesk.Revit.DB.Family family = null; uiDoc.LoadFamily(FD.FileName, out family); tx.Commit(); string name = family.Name; foreach (ElementId id in family.GetFamilySymbolIds()) { FamilySymbol famsymbol = family.Document.GetElement(id) as FamilySymbol; XYZ origin = new XYZ(0, 0, 0); tx.Start("Load Family Member"); famsymbol.Activate(); FamilyInstance instance = uiDoc.Create.NewFamilyInstance(origin, famsymbol, StructuralType.NonStructural); tx.Commit(); DWGExportOptions options = new DWGExportOptions(); options.FileVersion = ACADVersion.R2007; options.ExportOfSolids = SolidGeometry.ACIS; options.HideUnreferenceViewTags = true; //options.FileVersion = (ACADVersion)(3); var collector = new FilteredElementCollector(uiDoc); var viewFamilyType = collector .OfClass(typeof(ViewFamilyType)) .OfType <ViewFamilyType>() .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional); // Export the active view ICollection <ElementId> views = new List <ElementId>(); tx.Start("ChangeView"); View3D view = View3D.CreateIsometric(uiDoc, viewFamilyType.Id); view.DisplayStyle = DisplayStyle.Shading; tx.Commit(); views.Add(view.Id); string dwgfilename = famsymbol.Name + ".dwg"; string dwgfullfilename = filedir + dwgfilename; if (File.Exists(dwgfullfilename)) { File.Delete(dwgfullfilename); } uiDoc.Export(@filedir, @dwgfilename, views, options); tx.Start("Delete Family Member"); uiDoc.Delete(instance.Id); tx.Commit(); } } } else { Console.WriteLine("Please Create Export Directory For the chosen CAPS file."); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Debug.Listeners.Clear(); Debug.Listeners.Add(new RbsLogger.Logger("BatchPrint")); Debug.WriteLine("Print started"); App.assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location; Selection sel = commandData.Application.ActiveUIDocument.Selection; Document mainDoc = commandData.Application.ActiveUIDocument.Document; string mainDocTitle = SheetSupport.GetDocTitleWithoutRvt(mainDoc.Title); YayPrintSettings printSettings = YayPrintSettings.GetSavedPrintSettings(); printSettings.dwgProfiles = DwgSupport.GetAllDwgExportSettingsNames(mainDoc); //листы из всех открытых файлов, ключ - имя файла, значение - список листов Dictionary <string, List <MySheet> > allSheets = SheetSupport.GetAllSheets(commandData, printSettings); //получаю выбранные листы в диспетчере проекта List <ElementId> selIds = sel.GetElementIds().ToList(); //List<MySheet> mSheets0 = new List<MySheet>(); bool sheetsIsChecked = false; foreach (ElementId id in selIds) { Element elem = mainDoc.GetElement(id); ViewSheet sheet = elem as ViewSheet; if (sheet == null) { continue; } sheetsIsChecked = true; MySheet sheetInBase = allSheets[mainDocTitle].Where(i => i.sheet.Id.IntegerValue == sheet.Id.IntegerValue).First(); sheetInBase.IsPrintable = true; //mSheets0.Add(new MySheet(sheet)); } if (!sheetsIsChecked) { message = "Не выбраны листы. Выберите листы в Диспетчере проекта через Shift."; Debug.WriteLine("Печать остановлена, не выбраны листы"); return(Result.Failed); } //запись статистики по файлу //ProjectRating.Worker.Execute(commandData); //очистка старых Schema при необходимости /*try * { * Autodesk.Revit.DB.ExtensibleStorage.Schema sch = * Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD4")); * Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch, true); * * Autodesk.Revit.DB.ExtensibleStorage.Schema sch2 = * Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD5")); * Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch2, true); * Debug.WriteLine("Schema очищены"); * } * catch * { * Debug.WriteLine("Не удалось очистить Schema"); * } */ FormPrint form = new FormPrint(allSheets, printSettings); form.ShowDialog(); if (form.DialogResult != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } Debug.WriteLine("В окне печати нажат ОК, переход к печати"); printSettings = form.printSettings; string printerName = printSettings.printerName; allSheets = form.sheetsSelected; Debug.WriteLine("Выбранные для печати листы"); foreach (var kvp in allSheets) { Debug.WriteLine(" Файл " + kvp.Key); foreach (MySheet ms in kvp.Value) { Debug.WriteLine(" Лист " + ms.sheet.Name); } } string outputFolderCommon = printSettings.outputFolder; YayPrintSettings.SaveSettings(printSettings); Debug.WriteLine("Настройки печати сохранены"); //Дополнительные возможности работают только с PDFCreator if (printerName != "PDFCreator") { if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs || printSettings.useOrientation) { string errmsg = "Объединение PDF и печать \"Штампа\" в цвете поддерживаются только для PDFCreator."; errmsg += "\nВо избежание ошибок эти настройки будут отключены."; TaskDialog.Show("Предупреждение", errmsg); printSettings.mergePdfs = false; printSettings.excludeColors = new List <PdfColor>(); printSettings.useOrientation = false; Debug.WriteLine("Выбранные настройки несовместимы с принтером " + printerName); } } else { if (!printSettings.useOrientation) { SupportRegistry.SetOrientationForPdfCreator(OrientationType.Automatic); Debug.WriteLine("Установлена ориентация листа Automatic"); } } bool printToFile = form.printToFile; string outputFolder = ""; if (printToFile) { outputFolder = PrintSupport.CreateFolderToPrint(mainDoc, printerName, outputFolderCommon); Debug.WriteLine("Создана папка для печати: " + outputFolder); } //List<string> pfdFileNames = new List<string>(); //печатаю листы из каждого выбранного revit-файла List <MySheet> printedSheets = new List <MySheet>(); foreach (string docTitle in allSheets.Keys) { Document openedDoc = null; Debug.WriteLine("Печать листов из файла " + docTitle); RevitLinkType rlt = null; //проверяю, текущий это документ или полученный через ссылку if (docTitle == mainDocTitle) { openedDoc = mainDoc; Debug.WriteLine("Это не ссылочный документ"); } else { List <RevitLinkType> linkTypes = new FilteredElementCollector(mainDoc) .OfClass(typeof(RevitLinkType)) .Cast <RevitLinkType>() .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Name) == docTitle) .ToList(); if (linkTypes.Count == 0) { throw new Exception("Cant find opened link file " + docTitle); } rlt = linkTypes.First(); //проверю, не открыт ли уже документ, который пытаемся печатать foreach (Document testOpenedDoc in commandData.Application.Application.Documents) { if (testOpenedDoc.IsLinked) { continue; } if (testOpenedDoc.Title == docTitle || testOpenedDoc.Title.StartsWith(docTitle) || docTitle.StartsWith(testOpenedDoc.Title)) { openedDoc = testOpenedDoc; Debug.WriteLine("Это открытый ссылочный документ"); } } //иначе придется открывать документ через ссылку if (openedDoc == null) { Debug.WriteLine("Это закрытый ссылочный документ, пытаюсь его открыть"); List <Document> linkDocs = new FilteredElementCollector(mainDoc) .OfClass(typeof(RevitLinkInstance)) .Cast <RevitLinkInstance>() .Select(i => i.GetLinkDocument()) .Where(i => i != null) .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Title) == docTitle) .ToList(); if (linkDocs.Count == 0) { throw new Exception("Cant find link file " + docTitle); } Document linkDoc = linkDocs.First(); if (linkDoc.IsWorkshared) { Debug.WriteLine("Это файл совместной работы, открываю с отсоединением"); ModelPath mpath = linkDoc.GetWorksharingCentralModelPath(); OpenOptions oo = new OpenOptions(); oo.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; WorksetConfiguration wc = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets); oo.SetOpenWorksetsConfiguration(wc); rlt.Unload(new SaveCoordinates()); openedDoc = commandData.Application.Application.OpenDocumentFile(mpath, oo); } else { Debug.WriteLine("Это однопользательский файл"); string docPath = linkDoc.PathName; rlt.Unload(new SaveCoordinates()); openedDoc = commandData.Application.Application.OpenDocumentFile(docPath); } } Debug.WriteLine("Файл-ссылка успешно открыт"); } // List <MySheet> mSheets = allSheets[docTitle]; if (docTitle != mainDocTitle) { List <ViewSheet> linkSheets = new FilteredElementCollector(openedDoc) .OfClass(typeof(ViewSheet)) .Cast <ViewSheet>() .ToList(); List <MySheet> tempSheets = new List <MySheet>(); foreach (MySheet ms in mSheets) { foreach (ViewSheet vs in linkSheets) { if (ms.SheetId == vs.Id.IntegerValue) { MySheet newMs = new MySheet(vs, printSettings.alwaysColorParamName); tempSheets.Add(newMs); } } } mSheets = tempSheets; } Debug.WriteLine("Листов для печати найдено в данном файле: " + mSheets.Count.ToString()); Debug.WriteLine(": " + mSheets.Count.ToString()); PrintManager pManager = openedDoc.PrintManager; Debug.WriteLine("Текущий выбранный принтер: " + pManager.PrinterName); Debug.WriteLine("Попытка назначить принтер: " + printerName); pManager.SelectNewPrintDriver(printerName); pManager = openedDoc.PrintManager; pManager.PrintRange = PrintRange.Current; pManager.Apply(); Debug.WriteLine("Настройки менеджера печати успешно применены"); //список основных надписей нужен потому, что размеры листа хранятся в них //могут быть примечания, сделанные Основной надписью, надо их отфильровать, поэтому >0.6 List <FamilyInstance> titleBlocks = new FilteredElementCollector(openedDoc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_TitleBlocks) .Cast <FamilyInstance>() .Where(t => t.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble() > 0.6) .ToList(); Debug.WriteLine("Найдено основных надписей: " + titleBlocks.Count.ToString()); //получаю имя формата и проверяю, настроены ли размеры бумаги в Сервере печати string formatsCheckinMessage = PrintSupport.PrintFormatsCheckIn(openedDoc, printerName, titleBlocks, ref mSheets); if (formatsCheckinMessage != "") { message = formatsCheckinMessage; Debug.WriteLine("Проверка форматов листов неудачна: " + message); return(Result.Failed); } Debug.WriteLine("Проверка форматов листов выполнена успешно, переход к печати"); //если включен экспорт dwg - нахожу параметры экспорта по имени DWGExportOptions dwgOptions = null; if (printSettings.exportToDwg) { List <ExportDWGSettings> curDwgSettings = DwgSupport.GetAllDwgExportSettingsNames(openedDoc) .Where(i => i.Name == printSettings.selectedDwgExportProfileName) .ToList(); if (curDwgSettings.Count == 0) { TaskDialog.Show("Ошибка", "В файле " + openedDoc.Title + " не найден dwg профиль " + printSettings.selectedDwgExportProfileName); dwgOptions = DwgSupport.GetAllDwgExportSettingsNames(openedDoc).First().GetDWGExportOptions(); } else { dwgOptions = curDwgSettings.First().GetDWGExportOptions(); } } //печатаю каждый лист foreach (MySheet msheet in mSheets) { Debug.WriteLine(" "); Debug.WriteLine("Печатается лист: " + msheet.sheet.Name); if (printSettings.refreshSchedules) { SchedulesRefresh.Start(openedDoc, msheet.sheet); Debug.WriteLine("Спецификации обновлены успешно"); } using (Transaction t = new Transaction(openedDoc)) { t.Start("Профили печати"); string fileName0 = ""; if (printSettings.mergePdfs) { string guid = Guid.NewGuid().ToString(); fileName0 = msheet.sheet.SheetNumber + "_" + guid + ".pdf"; } else { fileName0 = msheet.NameByConstructor(printSettings.nameConstructor); } string fileName = SheetSupport.ClearIllegalCharacters(fileName0); if (fileName.Length > 128) { Debug.WriteLine("Имя листа длиннее 128 символов, будет урезано"); string cutname = fileName.Substring(0, 63); cutname += fileName.Substring(fileName.Length - 64); fileName = cutname; } if (printerName == "PDFCreator" && printSettings.useOrientation) { if (msheet.IsVertical) { SupportRegistry.SetOrientationForPdfCreator(OrientationType.Portrait); Debug.WriteLine("Принудительно установлена Portrait ориентация"); } if (!msheet.IsVertical) { SupportRegistry.SetOrientationForPdfCreator(OrientationType.Landscape); Debug.WriteLine("Принудительно установлена Landscape ориентация"); } } for (int i = 0; i < msheet.titleBlocks.Count; i++) { string tempFilename = ""; if (msheet.titleBlocks.Count > 1) { Debug.WriteLine("На листе более 1 основной надписи! Печать части №" + i.ToString()); tempFilename = fileName.Replace(".pdf", "_" + i.ToString() + ".pdf"); } else { Debug.WriteLine("На листе 1 основная надпись Id " + msheet.titleBlocks.First().Id.IntegerValue.ToString()); tempFilename = fileName; } string fullFilename = System.IO.Path.Combine(outputFolder, tempFilename); Debug.WriteLine("Полное имя файла: " + fullFilename); if (fullFilename.Length > 256) { throw new Exception("Слишком длинное имя файла " + fullFilename); } //смещаю область для печати многолистовых спецификаций double offsetX = -i * msheet.widthMm / 25.4; //смещение задается в дюймах! Debug.WriteLine("Смещение печати по X: " + offsetX.ToString("F3")); PrintSetting ps = PrintSupport.CreatePrintSetting(openedDoc, pManager, msheet, printSettings, offsetX, 0); pManager.PrintSetup.CurrentPrintSetting = ps; Debug.WriteLine("Настройки печати применены, " + ps.Name); PrintSupport.PrintView(msheet.sheet, pManager, ps, tempFilename); Debug.WriteLine("Лист успешно отправлен на принтер"); msheet.PdfFileName = fullFilename; printedSheets.Add(new MySheet(msheet)); } if (printerName == "PDFCreator" && printSettings.useOrientation) { System.Threading.Thread.Sleep(5000); } t.RollBack(); } //если включен dwg - то ещё экспортирую этот лист if (printSettings.exportToDwg) { List <ElementId> sheetsIds = new List <ElementId> { msheet.sheet.Id }; string sheetname = msheet.NameByConstructor(printSettings.dwgNameConstructor); openedDoc.Export(outputFolder, sheetname, sheetsIds, dwgOptions); } } if (rlt != null) { openedDoc.Close(false); #if R2017 RevitLinkLoadResult LoadResult = rlt.Reload(); #else LinkLoadResult loadResult = rlt.Reload(); #endif Debug.WriteLine("Ссылочный документ закрыт"); } } int printedSheetsCount = printedSheets.Count; printedSheets.Sort(); //если требуется постобработка файлов - ждем, пока они напечатаются if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs) { Debug.WriteLine("Включена постобработка файлов; ожидание окончания печати. Требуемое число файлов " + printedSheetsCount.ToString()); int watchTimer = 0; while (printToFile) { int filescount = System.IO.Directory.GetFiles(outputFolder, "*.pdf").Length; Debug.WriteLine("Итерация №" + watchTimer + ", файлов напечатано " + filescount); if (filescount >= printedSheetsCount) { break; } System.Threading.Thread.Sleep(500); watchTimer++; if (watchTimer > 100) { BalloonTip.Show("Обнаружены неполадки", "Печать PDF заняла продолжительное время или произошел сбой. Дождитесь окончания печати."); Debug.WriteLine("Не удалось дождаться окончания печати"); return(Result.Failed); } } } List <string> pdfFileNames = printedSheets.Select(i => i.PdfFileName).ToList(); Debug.WriteLine("PDF файлы которые должны быть напечатаны:"); foreach (string pdfname in pdfFileNames) { Debug.WriteLine(" " + pdfname); } Debug.WriteLine("PDF файлы напечатанные по факту:"); foreach (string pdfnameOut in System.IO.Directory.GetFiles(outputFolder, "*.pdf")) { Debug.WriteLine(" " + pdfnameOut); } //преобразую файл в черно-белый при необходимости if (printSettings.colorsType == ColorType.MonochromeWithExcludes) { Debug.WriteLine("Преобразование PDF файла в черно-белый"); foreach (MySheet msheet in printedSheets) { if (msheet.ForceColored) { Debug.WriteLine("Лист не преобразовывается в черно-белый: " + msheet.sheet.Name); continue; } string file = msheet.PdfFileName; string outFile = file.Replace(".pdf", "_OUT.pdf"); Debug.WriteLine("Файл будет преобразован из " + file + " в " + outFile); pdf.PdfWorker.SetExcludeColors(printSettings.excludeColors); pdf.PdfWorker.ConvertToGrayScale(file, outFile); //GrayscaleConvertTools.ConvertPdf(file, outFile, ColorType.Grayscale, new List<ExcludeRectangle> { rect, rect2 }); System.IO.File.Delete(file); System.IO.File.Move(outFile, file); Debug.WriteLine("Лист успешно преобразован"); } } //объединяю файлы при необходимости if (printSettings.mergePdfs) { Debug.WriteLine(" "); Debug.WriteLine("\nОбъединение PDF файлов"); System.Threading.Thread.Sleep(500); string combinedFile = System.IO.Path.Combine(outputFolder, mainDoc.Title + ".pdf"); BatchPrintYay.pdf.PdfWorker.CombineMultiplyPDFs(pdfFileNames, combinedFile); foreach (string file in pdfFileNames) { System.IO.File.Delete(file); Debug.WriteLine("Удален файл " + file); } Debug.WriteLine("Объединено успешно"); } if (printToFile) { System.Diagnostics.Process.Start(outputFolder); Debug.WriteLine("Открыта папка " + outputFolder); } //восстанавливаю настройки PDFCreator //if(printerName == "PDFCreator") //{ // SupportRegistry.RestoreSettingsForPDFCreator(); //} string msg = "Напечатано листов: " + printedSheetsCount; BalloonTip.Show("Печать завершена!", msg); Debug.WriteLine("Печать успешно завершена, напечатано листов " + printedSheetsCount); return(Result.Succeeded); }
void batchPrint() { Transaction trans = new Transaction(commandData.Application.ActiveUIDocument.Document, "WW_PDF"); trans.Start(); string printSetting = "A1 TO A1"; var doc = commandData.Application.ActiveUIDocument.Document; var printM = commandData.Application.ActiveUIDocument.Document.PrintManager; printM.SelectNewPrintDriver("Bluebeam PDF"); var ps = new FilteredElementCollector(doc); List <Element> myPrintSettings = ps.OfClass(typeof(PrintSetting)).ToList(); foreach (var setting in myPrintSettings) { if (setting.Name == printSetting) { printM.PrintSetup.CurrentPrintSetting = setting as PrintSetting; } } printM.PrintToFile = true; string dest = ""; if (CopyToFolder) { FolderBrowserDialog folderDlg = new FolderBrowserDialog(); folderDlg.ShowNewFolderButton = true; DialogResult result = folderDlg.ShowDialog(); if (result == DialogResult.OK) { dest = folderDlg.SelectedPath; } } string output = "Sheets printed: " + Environment.NewLine; List <string> printedFileNames = new List <string>(); foreach (var sheet in SheetInfo) { if (sheet.ToPrint) { output += sheet.Number + " " + sheet.Name + Environment.NewLine; var fp = sheet.FilePath; printM.PrintToFileName = fp; printedFileNames.Add(fp); printM.SubmitPrint(sheet.Sheet); string dwgFilepath = Path.GetDirectoryName(fp); string dwgfileName = Path.GetFileNameWithoutExtension(fp) + @".dwg"; var dwgxopt = new DWGExportOptions(); dwgxopt.MergedViews = true; doc.Export(dwgFilepath, dwgfileName, new List <ElementId> { sheet.ElementID }, dwgxopt); } } if (CopyToFolder) { foreach (var fileName in printedFileNames) { int waitCycles = 0; CannotFindFileVM vm = new CannotFindFileVM(); while (!File.Exists(fileName)) { Thread.Sleep(1000); waitCycles++; if (waitCycles > 15) { var skipFile = new Window(); var userControl = new ContinueLooking(vm); var window = new Window() { Content = userControl }; window.ShowDialog(); } if (vm.SkipAll == true || vm.SkipOne == true) { break; } } if (vm.SkipOne == false && vm.SkipAll == false) { string file = Path.GetFileName(fileName); File.Copy(fileName, dest + @"\" + file, true); } else { if (vm.SkipAll == true) { break; } } } } trans.Commit(); }