How to print images using event handler from winforms? Catch is i have to stay locked in to floorplans because my current program does not work on 3dview

How to print images using event handler from winforms? Catch is i have to stay locked in to floorplans because my current program does not work on 3dview

allazaruszcheong_21
Enthusiast Enthusiast
1,057 Views
11 Replies
Message 1 of 12

How to print images using event handler from winforms? Catch is i have to stay locked in to floorplans because my current program does not work on 3dview

allazaruszcheong_21
Enthusiast
Enthusiast

Alot of guides i have followed were not successful

``` printing views 1

private void button33_Click(object sender, EventArgs e) // It doesnt work

        {

            // Get the current Revit document and active view

            UIDocument uidoc = uiapp2.ActiveUIDocument;

            Autodesk.Revit.DB.Document doc = uidoc.Document;

            Autodesk.Revit.DB.View activeView = uidoc.ActiveView;

 

            // Create a new viewport for each angle

            List<Viewport> newViewports = new List<Viewport>();

            FilteredElementCollector collector = new FilteredElementCollector(doc, activeView.Id);

            ICollection<ElementId> viewportIds = collector.OfCategory(BuiltInCategory.OST_Viewports).ToElementIds();

 

            foreach (ElementId viewportId in viewportIds)

            {

                Viewport viewport = doc.GetElement(viewportId) as Viewport;

                if (viewport != null)

                {

```

```

                    for (int i = 0; i < 360; i += 10)

                    {

                        Viewport newViewport = Viewport.Create(doc, activeView.Id, viewport.ViewId, viewport.GetBoxCenter());

                        XYZ direction = new XYZ(Math.Sin(i * Math.PI / 180), 0, Math.Cos(i * Math.PI / 180));

                        newViewport.SetBoxCenter(viewport.GetBoxCenter() + direction * 10); // Adjust the distance as needed

                        newViewports.Add(newViewport);

                    }

                }

            }

 

            // Extract an image from each new viewport

            List<Image> images = new List<Image>();

            foreach (Viewport newViewport in newViewports)

            {

                using (Transaction tx = new Transaction(doc, "Capture Image"))

                {

                    tx.Start();

 

                    // Set the active view to the new viewport

                    uidoc.ActiveView = doc.GetElement(newViewport.ViewId) as Autodesk.Revit.DB.View;

 

                    // Export the image

                    ImageExportOptions options = new ImageExportOptions();

                    options.ZoomType = ZoomFitType.FitToPage;

                    options.PixelSize = 300; // Adjust the pixel size as needed

                    options.FilePath = "C:\\Users\\Public\\Downloads\\RevitImages\\image"; // Specify the file path without extension

                    options.HLRandWFViewsFileType = ImageFileType.PNG;

 

                    doc.ExportImage(options);

 

                    tx.Commit();

                }

            }

 

            // Close the new viewports

            foreach (Viewport newViewport in newViewports)

            {

                doc.Delete(newViewport.Id);

            }

 

            MessageBox.Show("Images extracted successfully!");

        }  

```

 

 

 

this produces no images help

0 Likes
Accepted solutions (4)
1,058 Views
11 Replies
Replies (11)
Message 2 of 12

Mohamed_Arshad
Advisor
Advisor

HI @allazaruszcheong_21 

    

     From your question I can understand that you need to print each viewport from the sheet as a Image. If I'm correct then I can see few errors in your code.

 

1. If your trying to export multiple images but with the same name is not possible, Kindly add index like image_1 and make unique for every images.

 

options.FilePath = $"C:\\Users\\Public\\Downloads\\RevitImages\\image_{i}"; // Specify the file path without extension

 

 

2. Why you're creating existing new view ports again and deleting in outside transaction.

  // Close the new viewports

            foreach (Viewport newViewport in newViewports)

            {

                doc.Delete(newViewport.Id);

            }

 

I need a elaborate definition from you side about the error so can explain your question in briefly with an example. So that I will easily 🙂

 


Mohamed Arshad K
Software Developer (CAD & BIM)

0 Likes
Message 3 of 12

allazaruszcheong_21
Enthusiast
Enthusiast

I thought the viewports remain after creating them in revit so i wanted to delete them as i thought they are physical items in revit that might lag my PC.

 

Also, i have to run the program in active 2Dview/floorplan, is that an issue? Also know that i am relatively new to C# and RevitAPI, most of the code above is just bits and pieces from the internet i combined...

0 Likes
Message 4 of 12

Mohamed_Arshad
Advisor
Advisor

HI @allazaruszcheong_21 
   

    Still I didn't Understand your requirement clearly. You need to export image of view port from the sheets ?


Mohamed Arshad K
Software Developer (CAD & BIM)

0 Likes
Message 5 of 12

allazaruszcheong_21
Enthusiast
Enthusiast

allazaruszcheong_21_0-1700566739403.png


here is my revit model in 3D.
i want to get pictures of the orientations of the walls, so in this case N S E W, NE NW SE SW 

allazaruszcheong_21_1-1700566783610.pngallazaruszcheong_21_2-1700566792971.pngallazaruszcheong_21_3-1700566804855.pngallazaruszcheong_21_4-1700566807980.png

Currently my code can only run on the "Floor plan" 

allazaruszcheong_21_5-1700566839772.png

if i try to run it in 3dview it will not work.



Currently the button that starts the image export is this:

allazaruszcheong_21_0-1700567204849.png

allazaruszcheong_21_1-1700567215422.png

 

 

0 Likes
Message 6 of 12

ctm_mka
Collaborator
Collaborator

As Mohamed stated, change the end of your export file path, something like, dont forget to set the file type! (unless i missed that in your code already)

 

"//image_"+ ViewName + ".png;

 

 As for the extra views, set your active view to your floor plan you set as Active View in the beginning, before closing/deleting views. Something like this is think:

 

doc.ActiveView = activeView;

 

0 Likes
Message 7 of 12

allazaruszcheong_21
Enthusiast
Enthusiast

Program runs, however the images dont get saved, directory is correct, i rightclick and press copy addressn then subsequently added yall's requests..

 

0 Likes
Message 8 of 12

Mohamed_Arshad
Advisor
Advisor
Accepted solution

HI @allazaruszcheong_21 

    Above code is different from your requirement. Kindly follow the below steps and refer the below code to achieve your requirement.

 

Steps to be Followed

1. Filter the Elevation ex. East, West.

2. Make Elevation as Active View.

3. Export Image.

 

Note:

Make sure the Crop Region is Fitted to the Image, Unless the Image is will not export in correct position.

 

Reference Code

UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;

            //Root Path
            string rootPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\Export_Images";

            //Filter Elevation
            List<View> viewList = new FilteredElementCollector(doc)
                .OfClass(typeof(View))
                .Cast<View>()
                .Where(x => x.ViewType.Equals(ViewType.Elevation))
                .Where(x=> ! x.IsTemplate)
                .ToList();


            //Itterate Each View and Export as Image
            foreach(View view in viewList)
            {

                //Make Active View
                uidoc.ActiveView = view;

                //Refresh Active View
                uidoc.RefreshActiveView();

                //Export Image
                PrintImage(doc, rootPath, view.Name);

            }

 

  public static void PrintImage(Document doc,string rootPath,string viewName)
        {
            // Export the image
            ImageExportOptions options = new ImageExportOptions();
            options.ZoomType = ZoomFitType.FitToPage;
            options.PixelSize = 1080;
            options.ImageResolution = ImageResolution.DPI_300;
            options.HLRandWFViewsFileType = ImageFileType.PNG;
            options.FilePath = $@"{rootPath}\{viewName}";
            doc.ExportImage(options);
        }

 

Demo Video

Demo Output.gif

 

I Hope this will Helps 🙂


Mohamed Arshad K
Software Developer (CAD & BIM)

0 Likes
Message 9 of 12

allazaruszcheong_21
Enthusiast
Enthusiast
Accepted solution

Your code works wonderfully, but i also found a solution here:


private void button33_Click(object sender, EventArgs e) // It doesnt work
{
// Get the desktop path
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

// Specify the folder and file name
string folderName = "Orientations_Folder";
string fileName = "PlaceHolder.txt";

// Combine the desktop path, folder name, and file name
string filePath = Path.Combine(desktopPath, folderName, fileName);

// Create the folder if it doesn't exist
Directory.CreateDirectory(Path.Combine(desktopPath, folderName));

var uidoc = uiapp2.ActiveUIDocument;
var doc = uidoc.Document;
var ieo = new ImageExportOptions
{
ZoomType = ZoomFitType.Zoom,
PixelSize = 512,
FilePath = filePath,
FitDirection = FitDirectionType.Horizontal,
HLRandWFViewsFileType = ImageFileType.PNG,
ImageResolution = ImageResolution.DPI_72,
ExportRange = ExportRange.SetOfViews,
};

ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Views);
FilteredElementCollector views = new FilteredElementCollector(doc);
views.WherePasses(filter).WhereElementIsNotElementType().ToElements();
IList<ElementId> ImageExportList = null;

foreach (Autodesk.Revit.DB.View view in views)
{
if (view.ViewType == ViewType.Elevation)
{
try
{
ImageExportList = new List<ElementId>();
ImageExportList.Add(view.Id);
ieo.SetViewsAndSheets(ImageExportList);
doc.ExportImage(ieo);
}
catch (Exception ex)
{
System.IO.File.WriteAllText(filePath, view.Name + " " + ex.Message);
}
}
}
}

0 Likes
Message 10 of 12

Mohamed_Arshad
Advisor
Advisor
Accepted solution

HI @allazaruszcheong_21 

 Kindly mark as solution which suit for you. So that others can easily find the answer


Mohamed Arshad K
Software Developer (CAD & BIM)

0 Likes
Message 11 of 12

allazaruszcheong_21
Enthusiast
Enthusiast

I assume if i want other views like North East North West, South East, South West, i need to create and add the elevations myself?

0 Likes
Message 12 of 12

Mohamed_Arshad
Advisor
Advisor
Accepted solution

HI @allazaruszcheong_21 

     Yes you need to add Elevation for North East North West, South East, South West. Kindly get the sample code from below link.

 

URL :https://maciejglowka.com/blog/creating-elevation-views-with-api/#:~:text=ElevationMarker%20marker%20... 


Mohamed Arshad K
Software Developer (CAD & BIM)

0 Likes