public static void ExportView(Document doc, View view,
                                      string view_export_loc, string ext)
        {
            try
            {
                //var sb = new StringBuilder();
                //sb.AppendLine();
                //sb.AppendLine(view_export_loc +
                //    " cbMIN " + view.CropBox.Min.ToString() +
                //" cbMax " + view.CropBox.Min.ToString() +
                //" bbxMIN " + view.get_BoundingBox(view).Min.ToString() +
                //    " bbxMAX " + view.get_BoundingBox(view).Max.ToString());

                //File.AppendAllText("C:\\data\\misc.txt", sb.ToString() + "\n");

                IList <ElementId> ImageExportList = new List <ElementId>();
                ImageExportList.Clear();
                ImageExportList.Add(view.Id);
                var BilledeExportOptions_3D_PNG = new ImageExportOptions
                {
                    ZoomType              = ZoomFitType.FitToPage,
                    PixelSize             = 4098,
                    FilePath              = view_export_loc,
                    FitDirection          = FitDirectionType.Horizontal,
                    HLRandWFViewsFileType = ImageFileType.PNG,
                    ImageResolution       = ImageResolution.DPI_600,
                    ExportRange           = ExportRange.SetOfViews,
                };

                BilledeExportOptions_3D_PNG.SetViewsAndSheets(ImageExportList);
                doc.ExportImage(BilledeExportOptions_3D_PNG);
            }
            catch (Exception)  {  }
        }
Exemple #2
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            var    view     = (View)((Value.Container)args[0]).Item;
            string pathName = ((Value.String)args[1]).Item;

            //string name = view.ViewName;
            //string pathName = path; +"\\" + name;

            var options = new ImageExportOptions
            {
                ExportRange           = ExportRange.SetOfViews,
                FilePath              = pathName,
                HLRandWFViewsFileType = ImageFileType.PNG,
                ImageResolution       = ImageResolution.DPI_72,
                ZoomType              = ZoomFitType.Zoom,
                ShadowViewsFileType   = ImageFileType.PNG
            };

            options.SetViewsAndSheets(new List <ElementId> {
                view.Id
            });

            dynRevitSettings.Doc.Document.ExportImage(options);//revit only has a method to save image to disk.
            //hack - make sure to change the read image below if other file types are supported
            Image image = Image.FromFile(pathName + ".png");

            return(Value.NewContainer(image));
        }
Exemple #3
0
        private List <string> ExportDraftingView(Document recipientDoc, List <ElementId> viewIds)
        {
            List <string> fileNames = new List <string>();

            try
            {
                string tempFileName  = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), "png");
                string tempImageFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), tempFileName);

                ImageExportOptions option = new ImageExportOptions();
                option.FilePath = tempImageFile;
                option.HLRandWFViewsFileType = ImageFileType.PNG;
                option.ImageResolution       = ImageResolution.DPI_300;
                option.ShouldCreateWebSite   = false;
                option.SetViewsAndSheets(viewIds);
                option.ExportRange = ExportRange.SetOfViews;

                if (ImageExportOptions.IsValidFileName(tempImageFile))
                {
                    recipientDoc.ExportImage(option);
                }

                fileNames = Directory.GetFiles(System.IO.Path.GetTempPath(), string.Format("{0}*.*", System.IO.Path.GetFileNameWithoutExtension(tempFileName))).ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to export draftingView to image.\n" + ex.Message, "ExportDraftingView", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(fileNames);
        }
        //
        public string GetImageFromView(UIDocument uidoc, Autodesk.Revit.DB.View view, bool isReload)
        {
            if (!isReload)
            {
                Selection choices = uidoc.Selection;
                try
                {
                    Reference hasPickOne = choices.PickObject(ObjectType.Element);
                    Import.selElement = uidoc.Document.GetElement(hasPickOne.ElementId);
                }
                catch (Exception)
                {
                    MessageBox.Show("Необходимо выбрать графический вид!!!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return "";
                }

            }
            IList<ElementId> ImageExportList = new List<ElementId>();
            ImageExportList.Add(view.Id);
            var BilledeExportOptions = new ImageExportOptions
            {
                PixelSize = 512,
                ExportRange = ExportRange.SetOfViews,
                HLRandWFViewsFileType = ImageFileType.PNG,
                ImageResolution = ImageResolution.DPI_300,
                ZoomType = ZoomFitType.Zoom,
                ShadowViewsFileType = ImageFileType.PNG

            };

            BilledeExportOptions.ViewName = "";

            BilledeExportOptions.FilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Temp\" + view.Id.IntegerValue.ToString() + ".png";
            BilledeExportOptions.SetViewsAndSheets(ImageExportList);
            try
            {
                uidoc.Document.ExportImage(BilledeExportOptions);
            }
            catch { return ""; }
            DirectoryInfo imagesDir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Temp\");
            string nameFile = "";

            nameFile = RenameFile(view, imagesDir, nameFile);
            //Image im = Image.FromFile(nameFile);
            //im = resizeImage(im, new Size(256, 256));
            //string newName = Path.GetFileNameWithoutExtension(nameFile);
            //newName += "f.png";
            //im.Save(newName);
            //using (var image = Image.FromFile(nameFile))
            //using (var newImage = ScaleImage(image, 300, 400))
            //{
            //    newImage.Save(@"c:\test.png", ImageFormat.Png);
            //}

            return nameFile;
        }
Exemple #5
0
        public static byte[] ThumbnailFromView(Autodesk.Revit.DB.Document doc, string viewName)
        {
            string   guid = Guid.NewGuid().ToString();
            FileInfo info = new FileInfo(Environment.CurrentDirectory + "\\" + guid + ".png");

            if (doc != null)
            {
                byte[] returnbytes             = null;
                FilteredElementCollector views = new FilteredElementCollector(doc).OfClass(typeof(View));
                foreach (View view in views)
                {
                    if (view.IsTemplate)
                    {
                        continue;
                    }
                    IList <ElementId> ImageExportList = new List <ElementId>();
                    if (view.Name == viewName)
                    {
                        ImageExportList.Clear();
                        ImageExportList.Add(view.Id);

                        var BilledeExportOptions_3D_PNG = new ImageExportOptions
                        {
                            ZoomType              = ZoomFitType.FitToPage,
                            PixelSize             = 1024,
                            FilePath              = info.FullName,
                            FitDirection          = FitDirectionType.Horizontal,
                            HLRandWFViewsFileType = ImageFileType.JPEGLossless,
                            ShadowViewsFileType   = ImageFileType.JPEGLossless,
                            ImageResolution       = ImageResolution.DPI_600,
                            ExportRange           = ExportRange.SetOfViews
                        };
                        BilledeExportOptions_3D_PNG.SetViewsAndSheets(ImageExportList);
                        doc.ExportImage(BilledeExportOptions_3D_PNG);

                        DirectoryInfo dinfo = new DirectoryInfo(info.DirectoryName);
                        foreach (FileInfo file in dinfo.GetFiles())
                        {
                            if (file.Name.Contains(guid))
                            {
                                returnbytes = FileToByteArray(file.FullName);
                                File.Delete(file.FullName);
                                break;
                            }
                        }
                        break;
                    }
                }
                return(returnbytes);
            }
            return
                (new byte[0]);
        }
Exemple #6
0
        private void buttonRefresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //export image
                ImageExportOptions option = new ImageExportOptions();
                option.HLRandWFViewsFileType = ImageFileType.PNG;
                option.ImageResolution       = ImageResolution.DPI_300;
                option.ShouldCreateWebSite   = false;
                option.ExportRange           = ExportRange.SetOfViews;

                List <ElementId> viewIds = new List <ElementId>();
                int        index         = pageNum - 1;
                PreviewMap preview       = previewMapList[index];
                if (null != preview.RecipientViewProperties)
                {
                    if (preview.RecipientViewProperties.ViewId > 0)
                    {
                        string tempFileName  = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), "png");
                        string tempImageFile = System.IO.Path.Combine(tempFolder, tempFileName);

                        viewIds.Add(new ElementId(preview.RecipientViewProperties.ViewId));
                        option.FilePath = tempImageFile;
                        option.SetViewsAndSheets(viewIds);
                        if (ImageExportOptions.IsValidFileName(tempImageFile))
                        {
                            string imageFileName = ExportDraftingView(preview.RecipientModelInfo.Doc, option);
                            if (!string.IsNullOrEmpty(preview.ViewLinkInfo.DestImagePath1))
                            {
                                if (File.Exists(preview.ViewLinkInfo.DestImagePath1))
                                {
                                    File.Delete(preview.ViewLinkInfo.DestImagePath1);
                                }
                            }
                            if (!string.IsNullOrEmpty(preview.ViewLinkInfo.DestImagePath2))
                            {
                                preview.ViewLinkInfo.DestImagePath1 = preview.ViewLinkInfo.DestImagePath2;
                            }
                            preview.ViewLinkInfo.DestImagePath2 = imageFileName;
                            imageRecipient.Source = new BitmapImage(new Uri(preview.ViewLinkInfo.DestImagePath2));
                        }
                    }
                    previewMapList.RemoveAt(index);
                    previewMapList.Insert(index, preview);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to refresh the preview image.\n" + ex.Message, "Refresh Preview Image", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        private void generateThumbnails()
        {
            var doc = commandData.Application.ActiveUIDocument.Document;
            var ieo = new ImageExportOptions();

            foreach (var sheet in SheetInfo)
            {
                ieo.ExportRange = ExportRange.SetOfViews;
                ieo.SetViewsAndSheets(new List <ElementId> {
                    sheet.ElementID
                });
                ieo.HLRandWFViewsFileType = ImageFileType.PNG;
                string tempFilePath = Path.GetTempFileName();
                ieo.FilePath = tempFilePath;
                doc.ExportImage(ieo);
                var    files     = Directory.GetFiles(Path.GetTempPath(), string.Format("{0}*.*", Path.GetFileNameWithoutExtension(tempFilePath)));
                string imagePath = files[0] ?? "";
                sheet.ImagePath = imagePath;
            }
        }
Exemple #8
0
        private void OK_Click(object sender, EventArgs e)
        {
            m_exportOptions.FilePath = saveAs.Text;
            if (m_exportOptions.ZoomType == ZoomFitType.FitToPage)
            {
                m_exportOptions.PixelSize = int.Parse(pixelValue.Text);
            }
            else if (m_exportOptions.ZoomType == ZoomFitType.Zoom)
            {
                m_exportOptions.Zoom            = (int)zoomSize.Value;
                m_exportOptions.ImageResolution = (ImageResolution)RIQCom.SelectedIndex;
            }

            m_exportOptions.ShadowViewsFileType   = (ImageFileType)shadedCom.SelectedIndex;
            m_exportOptions.HLRandWFViewsFileType = (ImageFileType)noShadedCom.SelectedIndex;


            if (m_exportOptions.ExportRange == ExportRange.SetOfViews)
            {
                ViewSet          views   = m_exportData.SelectViewsData.SelectedViews;
                List <ElementId> viewIds = new List <ElementId>();
                foreach (Autodesk.Revit.DB.View view in views)
                {
                    viewIds.Add(view.Id);
                }
                m_exportOptions.SetViewsAndSheets(viewIds);
            }

            try
            {
                m_exportData.ActiveDocument.ExportImage(m_exportOptions);
            }
            catch (Exception ex)
            {
                String errorMessage = "Failed to export img" + ex.ToString();
                TaskDialog.Show("Error", errorMessage, TaskDialogCommonButtons.Ok);
            }
            this.Close();
        }
Exemple #9
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            var view = (View)((Value.Container)args[0]).Item;

            var fullPath = ((Value.String)args[1]).Item;

            string pathName = fullPath;
            string extension = null;

            var fileType = ImageFileType.PNG;
            if (Path.HasExtension(fullPath))
            {
                extension = Path.GetExtension(fullPath).ToLower();
                switch (extension)
                {
                    case ".jpg":
                        fileType = ImageFileType.JPEGLossless;
                        break;
                    case ".png":
                        fileType = ImageFileType.PNG;
                        break;
                    case ".bmp":
                        fileType = ImageFileType.BMP;
                        break;
                    case ".tga":
                        fileType = ImageFileType.TARGA;
                        break;
                    case ".tif":
                        fileType = ImageFileType.TIFF;
                        break;
                }
                pathName = Path.Combine(
                    Path.GetDirectoryName(fullPath),
                    Path.GetFileNameWithoutExtension(fullPath));
            }

            var options = new ImageExportOptions
            {
                ExportRange = ExportRange.SetOfViews,
                FilePath = pathName,
                HLRandWFViewsFileType = fileType,
                ImageResolution = ImageResolution.DPI_72,
                ZoomType = ZoomFitType.Zoom,
                ShadowViewsFileType = fileType
            };

            options.SetViewsAndSheets(new List<ElementId> { view.Id });

            dynRevitSettings.Doc.Document.ExportImage(options);
                //revit only has a method to save image to disk.

            //hack - rename saved file to match specified file name
            //File.Move(string.Format("{0} - {1} - {2}.png", pathName, view.ViewType, view.ViewName), pathName + ".png");

            //hack - make sure to change the read image below if other file types are supported
            //Image image = Image.FromFile(pathName + (extension ?? ".png"));

            return Value.NewDummy("wrote image file"); //NewContainer(image);
        }
Exemple #10
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            var view = (View)((Value.Container)args[0]).Item;

            var fullPath = ((Value.String)args[1]).Item;

            string pathName  = fullPath;
            string extension = null;

            var fileType = ImageFileType.PNG;

            if (Path.HasExtension(fullPath))
            {
                extension = Path.GetExtension(fullPath).ToLower();
                switch (extension)
                {
                case ".jpg":
                    fileType = ImageFileType.JPEGLossless;
                    break;

                case ".png":
                    fileType = ImageFileType.PNG;
                    break;

                case ".bmp":
                    fileType = ImageFileType.BMP;
                    break;

                case ".tga":
                    fileType = ImageFileType.TARGA;
                    break;

                case ".tif":
                    fileType = ImageFileType.TIFF;
                    break;
                }
                pathName = Path.Combine(
                    Path.GetDirectoryName(fullPath),
                    Path.GetFileNameWithoutExtension(fullPath));
            }

            var options = new ImageExportOptions
            {
                ExportRange           = ExportRange.SetOfViews,
                FilePath              = pathName,
                HLRandWFViewsFileType = fileType,
                ImageResolution       = ImageResolution.DPI_72,
                ZoomType              = ZoomFitType.Zoom,
                ShadowViewsFileType   = fileType
            };

            options.SetViewsAndSheets(new List <ElementId> {
                view.Id
            });

            dynRevitSettings.Doc.Document.ExportImage(options);
            //revit only has a method to save image to disk.

            //hack - rename saved file to match specified file name
            //File.Move(string.Format("{0} - {1} - {2}.png", pathName, view.ViewType, view.ViewName), pathName + ".png");

            //hack - make sure to change the read image below if other file types are supported
            //Image image = Image.FromFile(pathName + (extension ?? ".png"));

            return(Value.NewDummy("wrote image file")); //NewContainer(image);
        }
Exemple #11
0
        private OrthogonalCamera GetOrthogonalCamera(Dictionary <int, ElementProperties> elementDictionary, string imagePath)
        {
            OrthogonalCamera orthoCamera = new OrthogonalCamera();

            try
            {
                BoundingBoxXYZ boundingBox = new BoundingBoxXYZ();
                boundingBox.Enabled = true;
                for (int i = 0; i < 3; i++)
                {
                    boundingBox.set_MinEnabled(i, true);
                    boundingBox.set_MaxEnabled(i, true);
                    boundingBox.set_BoundEnabled(0, i, true);
                    boundingBox.set_BoundEnabled(1, i, true);
                }

                BoundingBoxXYZ tempBoundingBox = elementDictionary.First().Value.RevitElement.get_BoundingBox(null);
                tempBoundingBox.Enabled = true;

                double maxX = tempBoundingBox.Max.X;
                double maxY = tempBoundingBox.Max.Y;
                double maxZ = tempBoundingBox.Max.Z;
                double minX = tempBoundingBox.Min.X;
                double minY = tempBoundingBox.Min.Y;
                double minZ = tempBoundingBox.Min.Z;

                List <ElementId>           elementIds = new List <ElementId>();
                Dictionary <int, Category> categories = new Dictionary <int, Category>();
                foreach (ElementProperties ep in elementDictionary.Values)
                {
                    Element element = ep.RevitElement;
                    if (null != element)
                    {
                        try
                        {
                            if (!categories.ContainsKey(element.Category.Id.IntegerValue))
                            {
                                categories.Add(element.Category.Id.IntegerValue, element.Category);
                            }
                            BoundingBoxXYZ bbBox = element.get_BoundingBox(null);
                            bbBox.Enabled = true;
                            elementIds.Add(element.Id);
                            if (null != boundingBox)
                            {
                                if (bbBox.Max.X > maxX)
                                {
                                    maxX = bbBox.Max.X;
                                }
                                if (bbBox.Max.Y > maxY)
                                {
                                    maxY = bbBox.Max.Y;
                                }
                                if (bbBox.Max.Z > maxZ)
                                {
                                    maxZ = bbBox.Max.Z;
                                }
                                if (bbBox.Min.X < minX)
                                {
                                    minX = bbBox.Min.X;
                                }
                                if (bbBox.Min.Y < minY)
                                {
                                    minY = bbBox.Min.Y;
                                }
                                if (bbBox.Min.Z < minZ)
                                {
                                    minZ = bbBox.Min.Z;
                                }
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }

                XYZ xyzMax = new XYZ(maxX, maxY, maxZ);
                XYZ xyzMin = new XYZ(minX, minY, minZ);

                boundingBox.set_Bounds(0, xyzMin);
                boundingBox.set_Bounds(1, xyzMax);


                ViewFamilyType           view3dFamilyType = null;
                FilteredElementCollector collector        = new FilteredElementCollector(m_doc);
                List <Element>           elements         = collector.OfClass(typeof(ViewFamilyType)).ToElements().ToList();
                foreach (Element element in elements)
                {
                    ViewFamilyType viewfamilytype = element as ViewFamilyType;
                    if (viewfamilytype.ViewFamily == ViewFamily.ThreeDimensional)
                    {
                        view3dFamilyType = viewfamilytype; break;
                    }
                }

                if (null != view3dFamilyType)
                {
                    using (TransactionGroup transGroup = new TransactionGroup(m_doc))
                    {
                        transGroup.Start("Start Creating View 3D");
                        using (Transaction trans = new Transaction(m_doc))
                        {
                            trans.Start("Create View");

                            View3D view3d = View3D.CreateIsometric(m_doc, view3dFamilyType.Id);
                            view3d.SetSectionBox(boundingBox);
                            view3d.GetSectionBox().Enabled = true;
                            view3d.DetailLevel = ViewDetailLevel.Fine;

                            foreach (Category category in categories.Values)
                            {
                                if (category.get_AllowsVisibilityControl(view3d))
                                {
#if RELEASE2017 || RELEASE2018
                                    view3d.SetCategoryHidden(category.Id, false);
#else
                                    view3d.SetVisibility(category, true);
#endif
                                }
                            }

                            view3d.get_Parameter(BuiltInParameter.MODEL_GRAPHICS_STYLE).Set(4);

                            //m_app.ActiveUIDocument.ActiveView = view3d;
                            //m_app.ActiveUIDocument.RefreshActiveView();

                            XYZ   eyePostion = view3d.GetOrientation().EyePosition;
                            Point viewPoint  = new Point();
                            viewPoint.X = eyePostion.X; viewPoint.Y = eyePostion.Y; viewPoint.Z = eyePostion.Z;
                            orthoCamera.CameraViewPoint = viewPoint;

                            XYZ       forwardDirection = view3d.GetOrientation().ForwardDirection;
                            Direction fDirection       = new Direction();
                            fDirection.X = forwardDirection.X; fDirection.Y = forwardDirection.Y; fDirection.Z = forwardDirection.Z;
                            orthoCamera.CameraDirection = fDirection;

                            XYZ       upDirection = view3d.GetOrientation().UpDirection;
                            Direction uDirection  = new Direction();
                            uDirection.X = upDirection.X; uDirection.Y = upDirection.Y; uDirection.Z = upDirection.Z;
                            orthoCamera.CameraUpVector = uDirection;

                            orthoCamera.ViewToWorldScale = view3d.Scale;
                            m_app.ActiveUIDocument.RefreshActiveView();
                            trans.Commit();

                            trans.Start("Export Image");
                            //create snapshot.png
                            ImageExportOptions option = new ImageExportOptions();
                            option.HLRandWFViewsFileType = ImageFileType.PNG;
                            option.ImageResolution       = ImageResolution.DPI_300;
                            option.ShouldCreateWebSite   = false;
                            option.ExportRange           = ExportRange.SetOfViews;
                            option.FilePath = imagePath;
                            List <ElementId> viewIds = new List <ElementId>();
                            viewIds.Add(view3d.Id);
                            option.SetViewsAndSheets(viewIds);

                            if (ImageExportOptions.IsValidFileName(option.FilePath))
                            {
                                m_doc.ExportImage(option);
                            }
                            trans.Commit();
                        }
                        transGroup.RollBack();
                    }

                    if (File.Exists(imagePath))
                    {
                        File.Delete(imagePath);
                    }
                    string[] fileNames = Directory.GetFiles(Path.GetDirectoryName(imagePath), "snapshot*");
                    foreach (string fName in fileNames)
                    {
                        if (Path.GetExtension(fName) == ".png" || Path.GetExtension(fName) == ".jpg")
                        {
                            File.Move(fName, imagePath);
                            if (File.Exists(fName))
                            {
                                File.Delete(fName);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get the orthogonal camera.\n" + ex.Message, "Get Orthogonal Camera", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(orthoCamera);
        }
Exemple #12
0
        public string[] ExportToImage(Element e)
        {
            Document doc = e.Document;

            // Hide all other elements in views to export

            foreach (View v in _views_to_export)
            {
                List <ElementId> hideable_element_ids
                    = new FilteredElementCollector(doc, v.Id)
                      .Where <Element>(a => a.CanBeHidden(v))
                      .Select <Element, ElementId>(b => b.Id)
                      .ToList <ElementId>();

                v.HideElements(hideable_element_ids);

                List <ElementId> ids = new List <ElementId>(1)
                {
                    e.Id
                };

                v.UnhideElements(ids);
            }

            doc.Regenerate();

            string dir      = "C:/tmp";
            string fn       = e.Id.IntegerValue.ToString();
            string filepath = $"{dir}/{fn}.png";

            var ieo = new ImageExportOptions
            {
                FilePath              = filepath,
                FitDirection          = FitDirectionType.Horizontal,
                HLRandWFViewsFileType = ImageFileType.PNG,
                ImageResolution       = ImageResolution.DPI_150,
                ShouldCreateWebSite   = false
            };

            int n = _views_to_export.Count;

            if (0 < n)
            {
                List <ElementId> ids = new List <ElementId>(
                    _views_to_export.Select <View, ElementId>(
                        v => v.Id));

                ieo.SetViewsAndSheets(ids);
                ieo.ExportRange = ExportRange.SetOfViews;
            }
            else
            {
                ieo.ExportRange = ExportRange
                                  .VisibleRegionOfCurrentView;
            }

            ieo.ZoomType = ZoomFitType.FitToPage;
            ieo.ViewName = "tmp";

            try
            {
                doc.ExportImage(ieo);
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }

            // File name has format like
            // "tempFileName - view type - view name", e.g.
            // "12345678 - 3D View - {3D}.png".
            // Get the first image (we only listed one view
            // in views).

            var files = Directory.GetFiles(
                dir, $"{fn}*.*");

            return(files);
        }
Exemple #13
0
        public static bool ToPdf(this Document document, IEnumerable <ElementId> viewElementIds, string path, PdfSharp.PageSize pageSize = PdfSharp.PageSize.A4, ImageResolution imageResolution = ImageResolution.DPI_600)
        {
            if (document == null || viewElementIds == null || string.IsNullOrWhiteSpace(path))
            {
                return(false);
            }

            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path)))
            {
                return(false);
            }

            //Creating directory for temporary images
            string directory = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.Guid.NewGuid().ToString());

            System.IO.Directory.CreateDirectory(directory);

            string name = string.IsNullOrEmpty(document.Title) ? "???" : document.Title;

            //Adjusting image pixel size
            int pixelSize = 512;

            switch (pageSize)
            {
            case PdfSharp.PageSize.A0:
                pixelSize = 14043;
                break;

            case PdfSharp.PageSize.A1:
                pixelSize = 9933;
                break;

            case PdfSharp.PageSize.A2:
                pixelSize = 7016;
                break;

            case PdfSharp.PageSize.A3:
                pixelSize = 4961;
                break;

            case PdfSharp.PageSize.A4:
                pixelSize = 3508;
                break;

            case PdfSharp.PageSize.A5:
                pixelSize = 2480;
                break;
            }

            //Adjusting image resolution
            switch (imageResolution)
            {
            case ImageResolution.DPI_600:
                pixelSize = pixelSize * 2;
                break;

            case ImageResolution.DPI_300:
                pixelSize = pixelSize * 1;
                break;

            case ImageResolution.DPI_150:
                pixelSize = System.Convert.ToInt32(pixelSize * 0.5);
                break;

            case ImageResolution.DPI_72:
                pixelSize = System.Convert.ToInt32(pixelSize * 0.25);
                break;
            }


            //Creating Revit Export Options for View Image
            ImageExportOptions imageExportOptions = new ImageExportOptions()
            {
                FilePath              = System.IO.Path.Combine(directory, name),
                FitDirection          = FitDirectionType.Horizontal,
                ZoomType              = ZoomFitType.FitToPage,
                ImageResolution       = imageResolution,
                HLRandWFViewsFileType = ImageFileType.PNG,
                ShadowViewsFileType   = ImageFileType.PNG,
                PixelSize             = pixelSize,
                ExportRange           = ExportRange.SetOfViews
            };


            //Exporting temporary images from Views. Necessary to do it one by one to keep view order
            List <string> imagePaths = new List <string>();

            foreach (ElementId elementId in viewElementIds)
            {
                if (elementId == null)
                {
                    continue;
                }

                View view = document.GetElement(elementId) as View;
                if (view == null)
                {
                    continue;
                }

                imageExportOptions.SetViewsAndSheets(new List <ElementId>()
                {
                    elementId
                });

                document.ExportImage(imageExportOptions);

                foreach (string imagePath in System.IO.Directory.GetFiles(directory))
                {
                    if (!imagePaths.Contains(imagePath))
                    {
                        imagePaths.Add(imagePath);
                        break;
                    }
                }
            }

            //Creating pdf Document from view images
            using (PdfDocument pdfDocument = new PdfDocument())
            {
                foreach (string imagePath in imagePaths)
                {
                    PdfPage pdfPage = pdfDocument.AddPage();
                    pdfPage.Size = pageSize;

                    byte[] bytes = System.IO.File.ReadAllBytes(imagePath);
                    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes, false))
                    {
                        double widthFactor  = 1;
                        double heightFactor = 1;

                        XImage xImage = XImage.FromStream(memoryStream);
                        if (xImage.PointHeight > xImage.PointWidth)
                        {
                            pdfPage.Orientation = PdfSharp.PageOrientation.Portrait;
                            widthFactor         = xImage.PointWidth / pdfPage.Width.Point;
                        }
                        else
                        {
                            pdfPage.Orientation = PdfSharp.PageOrientation.Landscape;
                            heightFactor        = xImage.PointHeight / pdfPage.Height.Point;
                        }

                        XGraphics xGraphics = XGraphics.FromPdfPage(pdfPage);
                        xGraphics.DrawImage(xImage, 0, 0, pdfPage.Width.Point * widthFactor, pdfPage.Height.Point * heightFactor);
                    }
                }

                pdfDocument.Save(path);
            }

            //Removing temporary image files -> Not necessary
            foreach (string imagePath in imagePaths)
            {
                if (System.IO.File.Exists(imagePath))
                {
                    System.IO.File.Delete(imagePath);
                }
            }

            //Recursive removing whole temporary directory where view images were saved
            System.IO.Directory.Delete(directory, true);

            return(System.IO.File.Exists(path));
        }
Exemple #14
0
        /// <summary>
        /// Export the view as an image to the given path - defaults to png, but you can override 
        /// the file type but supplying a path with the appropriate extension
        /// </summary>
        /// <param name="fullPath">A valid path for the image</param>
        /// <returns>The image</returns>
        public System.Drawing.Image ExportAsImage(string fullPath)
        {
            string pathName = fullPath;
            string extension = null;

            var fileType = ImageFileType.PNG;
            if (Path.HasExtension(fullPath))
            {
                extension = Path.GetExtension(fullPath).ToLower();
                switch (extension)
                {
                    case ".jpg":
                        fileType = ImageFileType.JPEGLossless;
                        break;
                    case ".png":
                        fileType = ImageFileType.PNG;
                        break;
                    case ".bmp":
                        fileType = ImageFileType.BMP;
                        break;
                    case ".tga":
                        fileType = ImageFileType.TARGA;
                        break;
                    case ".tif":
                        fileType = ImageFileType.TIFF;
                        break;
                }
                pathName = Path.Combine(
                    Path.GetDirectoryName(fullPath),
                    Path.GetFileNameWithoutExtension(fullPath));
            }

            extension = (extension ?? ".png");

            var options = new ImageExportOptions
            {
                ExportRange = ExportRange.SetOfViews,
                FilePath = pathName,
                HLRandWFViewsFileType = fileType,
                ImageResolution = ImageResolution.DPI_72,
                ZoomType = ZoomFitType.Zoom,
                ShadowViewsFileType = fileType
            };

            options.SetViewsAndSheets(new List<ElementId> { InternalView.Id });

            Document.ExportImage(options);

            // Revit outputs file with a bunch of crap in the file name, let's construct that
            var actualFn = string.Format("{0} - {1} - {2}{3}", pathName, ViewTypeString(InternalView.ViewType),
                InternalView.ViewName, extension);

            // and the intended destination
            var destFn = pathName + extension;

            // rename the file
            if (File.Exists(destFn)) File.Delete(destFn);
            File.Move(actualFn, destFn);

            return Image.FromFile(destFn);
        }
Exemple #15
0
        static string ExportToImage(Document doc)
        {
            var tempFileName = Path.ChangeExtension(
                Path.GetRandomFileName(), "png");

            string tempImageFile;

            try
            {
                tempImageFile = Path.Combine(
                    Path.GetTempPath(), tempFileName);
            }
            catch (IOException)
            {
                return(null);
            }

            IList <ElementId> views = new List <ElementId>();

            try
            {
#if !VERSION2014
                var direction = new XYZ(-1, 1, -1);
                var view3D    = doc.IsFamilyDocument
      ? doc.FamilyCreate.NewView3D(direction)
      : doc.Create.NewView3D(direction);
#else
                var collector = new FilteredElementCollector(
                    doc);

                var viewFamilyType = collector
                                     .OfClass(typeof(ViewFamilyType))
                                     .OfType <ViewFamilyType>()
                                     .FirstOrDefault(x =>
                                                     x.ViewFamily == ViewFamily.ThreeDimensional);

                var view3D = (viewFamilyType != null)
        ? View3D.CreateIsometric(doc, viewFamilyType.Id)
        : null;
#endif // VERSION2014

                if (view3D != null)
                {
                    // Ensure white background.

                    Color white = new Color(255, 255, 255);

                    view3D.SetBackground(
                        ViewDisplayBackground.CreateGradient(
                            white, white, white));

                    views.Add(view3D.Id);

                    var graphicDisplayOptions
                        = view3D.get_Parameter(
                              BuiltInParameter.MODEL_GRAPHICS_STYLE);

                    // Settings for best quality

                    graphicDisplayOptions.Set(6);
                }
            }
            catch (Autodesk.Revit.Exceptions
                   .InvalidOperationException)
            {
            }

            var ieo = new ImageExportOptions
            {
                FilePath              = tempImageFile,
                FitDirection          = FitDirectionType.Horizontal,
                HLRandWFViewsFileType = ImageFileType.PNG,
                ImageResolution       = ImageResolution.DPI_150,
                ShouldCreateWebSite   = false
            };

            if (views.Count > 0)
            {
                ieo.SetViewsAndSheets(views);
                ieo.ExportRange = ExportRange.SetOfViews;
            }
            else
            {
                ieo.ExportRange = ExportRange
                                  .VisibleRegionOfCurrentView;
            }

            ieo.ZoomType = ZoomFitType.FitToPage;
            ieo.ViewName = "tmp";

            if (ImageExportOptions.IsValidFileName(
                    tempImageFile))
            {
                // If ExportRange = ExportRange.SetOfViews
                // and document is not active, then image
                // exports successfully, but throws
                // Autodesk.Revit.Exceptions.InternalException

                try
                {
                    doc.ExportImage(ieo);
                }
                catch
                {
                    return(string.Empty);
                }
            }
            else
            {
                return(string.Empty);
            }

            // File name has format like
            // "tempFileName - view type - view name", e.g.
            // "luccwjkz - 3D View - {3D}.png".
            // Get the first image (we only listed one view
            // in views).

            var files = Directory.GetFiles(
                Path.GetTempPath(),
                string.Format("{0}*.*", Path
                              .GetFileNameWithoutExtension(
                                  tempFileName)));

            return(files.Length > 0
        ? files[0]
        : string.Empty);
        }
Exemple #16
0
        /// <summary>
        ///     Export the view as an image to the given path - defaults to png, but you can override
        ///     the file type but supplying a path with the appropriate extension
        /// </summary>
        /// <param name="path">A valid path for the image</param>
        /// <returns>The image</returns>
        public Bitmap ExportAsImage(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException(Properties.Resources.View_ExportAsImage_Path_Invalid, "path");
            }

            var    fileType  = ImageFileType.PNG;
            string extension = ".png";

            if (Path.HasExtension(path))
            {
                extension = Path.GetExtension(path);
                switch (extension.ToLower())
                {
                case ".jpg":
                    fileType = ImageFileType.JPEGLossless;
                    break;

                case ".png":
                    fileType = ImageFileType.PNG;
                    break;

                case ".bmp":
                    fileType = ImageFileType.BMP;
                    break;

                case ".tga":
                    fileType = ImageFileType.TARGA;
                    break;

                case ".tif":
                    fileType = ImageFileType.TIFF;
                    break;
                }
            }

            var options = new ImageExportOptions
            {
                ExportRange           = ExportRange.SetOfViews,
                FilePath              = path,
                FitDirection          = FitDirectionType.Horizontal,
                HLRandWFViewsFileType = fileType,
                ImageResolution       = ImageResolution.DPI_150,
                ShadowViewsFileType   = fileType,
                ShouldCreateWebSite   = false,
                ViewName              = Guid.NewGuid().ToString(),
                Zoom     = 100,
                ZoomType = ZoomFitType.Zoom
            };

            options.SetViewsAndSheets(new List <ElementId> {
                InternalView.Id
            });

            Document.ExportImage(options);

            var pathName = Path.Combine(
                Path.GetDirectoryName(path),
                Path.GetFileNameWithoutExtension(path));

            // Revit outputs file with a bunch of crap in the file name, let's construct that
            var actualFn = string.Format("{0} - {1} - {2}{3}", pathName, ViewTypeString(InternalView.ViewType),
                                         InternalView.ViewName, extension);

            // and the intended destination
            var destFn = pathName + extension;

            // rename the file
            if (File.Exists(destFn))
            {
                File.Delete(destFn);
            }
            File.Move(actualFn, destFn);

            Bitmap bmp;

            try
            {
                using (var fs = new FileStream(destFn, FileMode.Open))
                {
                    bmp = new Bitmap(Image.FromStream(fs));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Resources.ViewExportImageError, ex);
            }

            return(bmp);
        }
Exemple #17
0
        /// <summary>
        /// Export the view as an image to the given path - defaults to png, but you can override
        /// the file type but supplying a path with the appropriate extension.
        /// </summary>
        /// <param name="path">A valid path for the image.</param>
        /// <returns>A Bitmap Image.</returns>
        public Bitmap ExportAsImage(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException(Properties.Resources.View_ExportAsImage_Path_Invalid, nameof(path));
            }

            var fileType  = ImageFileType.PNG;
            var extension = ".png";

            if (Path.HasExtension(path))
            {
                extension = Path.GetExtension(path);
                switch (extension.ToLower())
                {
                case ".jpg":
                    fileType = ImageFileType.JPEGLossless;
                    break;

                case ".png":
                    fileType = ImageFileType.PNG;
                    break;

                case ".bmp":
                    fileType = ImageFileType.BMP;
                    break;

                case ".tga":
                    fileType = ImageFileType.TARGA;
                    break;

                case ".tif":
                    fileType = ImageFileType.TIFF;
                    break;
                }
            }

            var options = new ImageExportOptions
            {
                ExportRange           = ExportRange.SetOfViews,
                FilePath              = path,
                FitDirection          = FitDirectionType.Horizontal,
                HLRandWFViewsFileType = fileType,
                ImageResolution       = ImageResolution.DPI_150,
                ShadowViewsFileType   = fileType,
                ShouldCreateWebSite   = false,
                ViewName              = Guid.NewGuid().ToString(),
                Zoom     = 100,
                ZoomType = ZoomFitType.Zoom
            };

            options.SetViewsAndSheets(new List <ElementId> {
                InternalView.Id
            });

            Document.ExportImage(options);

            var doc                 = DocumentManager.Instance.CurrentDBDocument;
            var revitName           = Autodesk.Revit.DB.ImageExportOptions.GetFileName(doc, InternalView.Id);
            var directoryName       = Path.GetDirectoryName(path);
            var actualFileName      = string.Empty;
            var destinationFileName = string.Empty;

            if (directoryName != null)
            {
                actualFileName = Path.Combine(
                    directoryName,
                    Path.GetFileNameWithoutExtension(path) + revitName + extension);

                destinationFileName = Path.Combine(
                    directoryName,
                    Path.GetFileNameWithoutExtension(path) + extension);
            }

            if (string.IsNullOrEmpty(actualFileName) || string.IsNullOrEmpty(destinationFileName))
            {
                throw new ArgumentException(Properties.Resources.View_ExportAsImage_Path_Invalid, nameof(path));
            }

            // rename the file
            if (File.Exists(actualFileName))
            {
                try
                {
                    File.Delete(destinationFileName);
                    File.Move(actualFileName, destinationFileName);
                }
                catch (Exception ex)
                {
                    throw new Exception(Properties.Resources.ViewExportImageLockedError, ex);
                }
            }

            Bitmap bmp;

            try
            {
                using (var fs = new FileStream(destinationFileName, FileMode.Open))
                {
                    bmp = new Bitmap(Image.FromStream(fs));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Resources.ViewExportImageError, ex);
            }

            return(bmp);
        }
        public static void GetImagesFromDocument(Document familyDoc, string targetDirectory)
        {
            //IL_000f: Unknown result type (might be due to invalid IL or missing references)
            //IL_0014: Unknown result type (might be due to invalid IL or missing references)
            //IL_0015: Unknown result type (might be due to invalid IL or missing references)
            //IL_001c: Unknown result type (might be due to invalid IL or missing references)
            //IL_0023: Unknown result type (might be due to invalid IL or missing references)
            //IL_002a: Unknown result type (might be due to invalid IL or missing references)
            //IL_0031: Unknown result type (might be due to invalid IL or missing references)
            //IL_0038: Unknown result type (might be due to invalid IL or missing references)
            //IL_003f: Unknown result type (might be due to invalid IL or missing references)
            //IL_004a: Unknown result type (might be due to invalid IL or missing references)
            //IL_0051: Unknown result type (might be due to invalid IL or missing references)
            //IL_0052: Unknown result type (might be due to invalid IL or missing references)
            //IL_0057: Unknown result type (might be due to invalid IL or missing references)
            //IL_0058: Unknown result type (might be due to invalid IL or missing references)
            //IL_0063: Unknown result type (might be due to invalid IL or missing references)
            //IL_0080: Unknown result type (might be due to invalid IL or missing references)
            //IL_0085: Unknown result type (might be due to invalid IL or missing references)
            //IL_0087: Unknown result type (might be due to invalid IL or missing references)
            //IL_0089: Expected O, but got Unknown
            //IL_008e: Unknown result type (might be due to invalid IL or missing references)
            //IL_0090: Unknown result type (might be due to invalid IL or missing references)
            //IL_0094: Unknown result type (might be due to invalid IL or missing references)
            //IL_009d: Unknown result type (might be due to invalid IL or missing references)
            //IL_00a7: Unknown result type (might be due to invalid IL or missing references)
            //IL_00a9: Unknown result type (might be due to invalid IL or missing references)
            //IL_00ca: Unknown result type (might be due to invalid IL or missing references)
            //IL_0118: Unknown result type (might be due to invalid IL or missing references)
            //IL_0119: Unknown result type (might be due to invalid IL or missing references)
            if (!Directory.Exists(targetDirectory))
            {
                Util_Helper.CreateDirectory(targetDirectory);
            }
            ImageExportOptions val = new ImageExportOptions();

            val.set_ExportRange(2);
            val.set_FilePath(targetDirectory);
            val.set_HLRandWFViewsFileType(2);
            val.set_ImageResolution(0);
            val.set_ShadowViewsFileType(2);
            val.set_ZoomType(0);
            val.set_PixelSize(512);
            val.set_FitDirection(0);
            FilteredElementCollector val2  = new FilteredElementCollector(familyDoc);
            IList <Element>          list  = val2.OfClass(typeof(View)).ToElements();
            IList <ElementId>        list2 = new List <ElementId>();

            foreach (Element item in list)
            {
                View val3 = item as View;
                if ((int)val3 != 0 && !val3.get_IsTemplate() && val3.get_CanBePrinted())
                {
                    list2.Add(val3.get_Id());
                }
            }
            val.SetViewsAndSheets(list2);
            if (Directory.Exists(targetDirectory))
            {
                string[] files = Directory.GetFiles(targetDirectory, "*.jpg");
                foreach (string path in files)
                {
                    File.Delete(path);
                }
            }
            if (ImageExportOptions.IsValidFileName(targetDirectory) && list2.Count > 0)
            {
                try
                {
                    familyDoc.ExportImage(val);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// Export the view as an image to the given path - defaults to png, but you can override
        /// the file type but supplying a path with the appropriate extension
        /// </summary>
        /// <param name="fullPath">A valid path for the image</param>
        /// <returns>The image</returns>
        public System.Drawing.Image ExportAsImage(string fullPath)
        {
            string pathName  = fullPath;
            string extension = null;

            var fileType = ImageFileType.PNG;

            if (Path.HasExtension(fullPath))
            {
                extension = Path.GetExtension(fullPath).ToLower();
                switch (extension)
                {
                case ".jpg":
                    fileType = ImageFileType.JPEGLossless;
                    break;

                case ".png":
                    fileType = ImageFileType.PNG;
                    break;

                case ".bmp":
                    fileType = ImageFileType.BMP;
                    break;

                case ".tga":
                    fileType = ImageFileType.TARGA;
                    break;

                case ".tif":
                    fileType = ImageFileType.TIFF;
                    break;
                }
                pathName = Path.Combine(
                    Path.GetDirectoryName(fullPath),
                    Path.GetFileNameWithoutExtension(fullPath));
            }

            extension = (extension ?? ".png");

            var options = new ImageExportOptions
            {
                ExportRange           = ExportRange.SetOfViews,
                FilePath              = pathName,
                HLRandWFViewsFileType = fileType,
                ImageResolution       = ImageResolution.DPI_72,
                ZoomType              = ZoomFitType.Zoom,
                ShadowViewsFileType   = fileType
            };

            options.SetViewsAndSheets(new List <ElementId> {
                InternalView.Id
            });

            Document.ExportImage(options);

            // Revit outputs file with a bunch of crap in the file name, let's construct that
            var actualFn = string.Format("{0} - {1} - {2}{3}", pathName, ViewTypeString(InternalView.ViewType),
                                         InternalView.ViewName, extension);

            // and the intended destination
            var destFn = pathName + extension;

            // rename the file
            if (File.Exists(destFn))
            {
                File.Delete(destFn);
            }
            File.Move(actualFn, destFn);

            return(Image.FromFile(destFn));
        }
    static string ExportToImage( Document doc )
    {
      var tempFileName = Path.ChangeExtension(
        Path.GetRandomFileName(), "png" );

      string tempImageFile;

      try
      {
        tempImageFile = Path.Combine(
          Path.GetTempPath(), tempFileName );
      }
      catch( IOException )
      {
        return null;
      }

      IList<ElementId> views = new List<ElementId>();

      try
      {

#if !VERSION2014
    var direction = new XYZ(-1, 1, -1);
    var view3D = doc.IsFamilyDocument
      ? doc.FamilyCreate.NewView3D(direction)
      : doc.Create.NewView3D(direction);
#else
        var collector = new FilteredElementCollector(
          doc );

        var viewFamilyType = collector
          .OfClass( typeof( ViewFamilyType ) )
          .OfType<ViewFamilyType>()
          .FirstOrDefault( x =>
            x.ViewFamily == ViewFamily.ThreeDimensional );

        var view3D = ( viewFamilyType != null )
        ? View3D.CreateIsometric( doc, viewFamilyType.Id )
        : null;

#endif // VERSION2014

        if( view3D != null )
        {
          // Ensure white background.

          Color white = new Color( 255, 255, 255 );

          view3D.SetBackground(
            ViewDisplayBackground.CreateGradient(
              white, white, white ) );

          views.Add( view3D.Id );

          var graphicDisplayOptions
            = view3D.get_Parameter(
              BuiltInParameter.MODEL_GRAPHICS_STYLE );

          // Settings for best quality

          graphicDisplayOptions.Set( 6 );
        }
      }
      catch( Autodesk.Revit.Exceptions
        .InvalidOperationException )
      {
      }

      var ieo = new ImageExportOptions
      {
        FilePath = tempImageFile,
        FitDirection = FitDirectionType.Horizontal,
        HLRandWFViewsFileType = ImageFileType.PNG,
        ImageResolution = ImageResolution.DPI_150,
        ShouldCreateWebSite = false
      };

      if( views.Count > 0 )
      {
        ieo.SetViewsAndSheets( views );
        ieo.ExportRange = ExportRange.SetOfViews;
      }
      else
      {
        ieo.ExportRange = ExportRange
          .VisibleRegionOfCurrentView;
      }

      ieo.ZoomType = ZoomFitType.FitToPage;
      ieo.ViewName = "tmp";

      if( ImageExportOptions.IsValidFileName(
        tempImageFile ) )
      {
        // If ExportRange = ExportRange.SetOfViews 
        // and document is not active, then image 
        // exports successfully, but throws
        // Autodesk.Revit.Exceptions.InternalException

        try
        {
          doc.ExportImage( ieo );
        }
        catch
        {
          return string.Empty;
        }
      }
      else
      {
        return string.Empty;
      }

      // File name has format like 
      // "tempFileName - view type - view name", e.g.
      // "luccwjkz - 3D View - {3D}.png".
      // Get the first image (we only listed one view
      // in views).

      var files = Directory.GetFiles(
        Path.GetTempPath(),
        string.Format( "{0}*.*", Path
          .GetFileNameWithoutExtension(
            tempFileName ) ) );

      return files.Length > 0
        ? files[0]
        : string.Empty;
    }
Exemple #21
0
        private bool UpdateViews()
        {
            bool result = false;

            try
            {
                progressBar.Visibility = System.Windows.Visibility.Visible;
                statusLable.Visibility = System.Windows.Visibility.Visible;
                statusLable.Text       = "Duplicating Views . . .";

                progressBar.Minimum = 0;
                progressBar.Maximum = previewMapList.Count;
                progressBar.Value   = 0;

                double value = 0;

                UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);
                DuplicateUtils.errorMessage = new StringBuilder();
                List <PreviewMap> updatedList = new List <PreviewMap>();
                for (int i = 0; i < previewMapList.Count; i++)
                {
                    value += 1;
                    if (previewMapList[i].IsEnabled)
                    {
                        PreviewMap previewMap = DuplicateUtils.DuplicateView(previewMapList[i], createSheet);
                        updatedList.Add(previewMap);
                    }
                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });
                }

                if (DuplicateUtils.errorMessage.Length > 0)
                {
                    MessageBox.Show("Following drafting views contains problems.\n\n" + DuplicateUtils.errorMessage.ToString(), "Errors in Duplicating Views", MessageBoxButton.OK, MessageBoxImage.Information);
                }

                previewMapList = new List <PreviewMap>();
                previewMapList = updatedList;
                //exportView one by one
                ImageExportOptions option = new ImageExportOptions();
                option.HLRandWFViewsFileType = ImageFileType.PNG;
                option.ImageResolution       = ImageResolution.DPI_300;
                option.ShouldCreateWebSite   = false;
                option.ExportRange           = ExportRange.SetOfViews;

                List <ElementId> viewIds = new List <ElementId>();
                foreach (PreviewMap preview in previewMapList)
                {
                    viewIds.Clear();
                    if (null != preview.RecipientViewProperties)
                    {
                        if (preview.RecipientViewProperties.ViewId > 0)
                        {
                            string tempFileName  = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), "png");
                            string tempImageFile = System.IO.Path.Combine(tempFolder, tempFileName);

                            viewIds.Add(new ElementId(preview.RecipientViewProperties.ViewId));
                            option.FilePath = tempImageFile;
                            option.SetViewsAndSheets(viewIds);
                            if (ImageExportOptions.IsValidFileName(tempImageFile))
                            {
                                string imageFileName = ExportDraftingView(preview.RecipientModelInfo.Doc, option);

                                if (!string.IsNullOrEmpty(preview.ViewLinkInfo.DestImagePath1))
                                {
                                    if (File.Exists(preview.ViewLinkInfo.DestImagePath1))
                                    {
                                        File.Delete(preview.ViewLinkInfo.DestImagePath1);
                                    }
                                }
                                if (!string.IsNullOrEmpty(preview.ViewLinkInfo.DestImagePath2))
                                {
                                    preview.ViewLinkInfo.DestImagePath1 = preview.ViewLinkInfo.DestImagePath2;
                                }
                                preview.ViewLinkInfo.DestImagePath2 = imageFileName;
                            }
                        }
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to update drafting views.\n" + ex.Message, "Update Views", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(result);
        }