API for dimension annotations.

API for dimension annotations.

ss13953642009
Advocate Advocate
377 Views
8 Replies
Message 1 of 9

API for dimension annotations.

ss13953642009
Advocate
Advocate

Hello everyone, in Inventor 2021, after obtaining all the dimension annotations on the current drawing sheet, I then iterate through these dimension annotations. In the breakpoint debugging state, the dimension annotation contains the first geometric intent, IntentOne.

83448a3fa8af21630d6a3529c5dcfd90.png

But when calling, it shows that the method does not exist.

1751267102562_228BE6EC-5720-49ae-A31E-A805BC7A8082.png

What method can be used to obtain the first geometric intent of the current dimension?

0 Likes
Accepted solutions (2)
378 Views
8 Replies
Replies (8)
Message 2 of 9

punam_bansode
Contributor
Contributor

Hi @ss13953642009,

 

Please share the code from the screen shot not able to understand. Apart from this if you want to annotate dimensions automatically on drawing view. you can use the Function "Dimension" which I have pasted below. you can use this method by passing all parameters like the view name, placement of annotation with relative to that view as, Top, Left, Right and Bottom. then third parameter as drawing text position center 0, right- (+Ve numeric), left- (-Ve numeric).  fourth and fifth parameter will be the work points name which you created in 3D model to show dimension between two points. 

 

Sub Main()
 AddDimension()
End sub 


Sub AddDimension()
	Trace.TraceInformation("Start Sub AddDimension")	
	
	Dim oSheet As Sheet = ThisDoc.Document.ActiveSheet
	Dim oGeneralNotes As GeneralNotes = oSheet.DrawingNotes.GeneralNotes
	Dim oTG As TransientGeometry = ThisServer.TransientGeometry
	Dim oGenDim As GeneralDimensions = oSheet.DrawingDimensions.GeneralDimensions
	Trace.TraceInformation("Sub AddDimension - Views")	
	Dim oView1 As DrawingView = ActiveSheet.View("1").View '	|-----------------------------------|	
	Dim oView2 As DrawingView = ActiveSheet.View("VIEW2").View '
Dimension(oView1, 3, "Right", 0, "Work Point37", "Work Point57", 0, 0, "")
	Dimension(oView1, 3, "Right", 0, "Work Point37", "Work Point36", 0, 0, "")
	Dimension(oView1, 3, "Right", 0, "Work Point35", "Work Point57", 0, 0, "") '-----------Like this you can call this method

End Sub

Function Dimension(oView As DrawingView, oView_Offset As Decimal, ViewEdgeName As String, _
			  oWP_Offset As Decimal, oWP_Name1 As String, oWP_Name2 As String, _
			  UpperTol As Decimal, LowerTol As Decimal, FormattedText As String)
		 
	Try
		Dim oSheet As Sheet = ThisDoc.Document.ActiveSheet
		Dim oDoc As Document = oView.ReferencedDocumentDescriptor.ReferencedDocument		
		Dim oWP1 As Inventor.WorkPoint = oDoc.ComponentDefinition.WorkPoints.Item(oWP_Name1)	
		Dim oWP2 As Inventor.WorkPoint = oDoc.ComponentDefinition.WorkPoints.Item(oWP_Name2)
		
		Dim Xpos, Ypos, PPAPdist As Decimal
		
		oView.SetIncludeStatus(oWP1, True)	
		oView.SetIncludeStatus(oWP2, True)
		

		Dim DimCenterText As Boolean = False
		If oWP_Offset = 0 Then DimCenterText = True


For Each oCenterMark In oSheet.Centermarks
			If oCenterMark.Attached Then
				If oCenterMark.AttachedEntity Is oWP1 Then oCenterMark_1 = oCenterMark
				If oCenterMark.AttachedEntity Is oWP2 Then oCenterMark_2 = oCenterMark
					
			End If
		Next
'----------------------------------------------------------------------------------------		
'For all WorkPoints in assy that ends on a number, adds a CenterMark.
		oCenterMark_1.Visible = False
		Select Split(oWP_Name1, "_")(Split(oWP_Name1, "_").Count-1)
		Case "H1", "H2", "H3", "H4", "H5", "H6","H7", "H8", "H9"
			oCenterMark_1.Visible = True
		End Select
		
		oCenterMark_2.Visible = False
		
		Select Split(oWP_Name2, "_")(Split(oWP_Name2, "_").Count-1)
		Case "H1", "H2", "H3", "H4", "H5", "H6","H7", "H8", "H9"
			oCenterMark_2.Visible = True
		End Select	
'----------------------------------------------------------------------------------------	
 		iLogicVb.UpdateWhenDone = True

 		WorkPoint_1 = oSheet.CreateGeometryIntent(oCenterMark_1, kPoint2dIntent)
		WorkPoint_2 = oSheet.CreateGeometryIntent(oCenterMark_2, kPoint2dIntent)
		
		
	'In the case of PPAP and not symmetrical tolerance, the measurement distance needs to be increased due to. Inspection Dim Symbol:
		If Not UpperTol = 0 And Not LowerTol = 0 And Not UpperTol = LowerTol Then _
			PPAPdist = 1.05 Else PPAPdist = 1
		'Break()
		Select LCase(Left(ViewEdgeName, 3)) 
			Case "top"
				PosInX = WorkPoint_2.PointOnSheet.X + oWP_Offset
				PosInY = oView.Top + (oView_Offset * PPAPdist) + 0.2
				DimensionType = DimensionTypeEnum.kHorizontalDimensionType
			Case "bot"
				PosInX = WorkPoint_2.PointOnSheet.X + oWP_Offset
				PosInY = oView.Top - oView.Height - (oView_Offset * PPAPdist) - 0.2
				DimensionType = DimensionTypeEnum.kHorizontalDimensionType
			Case "lef"	
				PosInX = oView.Left - (oView_Offset * PPAPdist) - 0.2
				PosInY = WorkPoint_2.PointOnSheet.Y + oWP_Offset 
				DimensionType = DimensionTypeEnum.kVerticalDimensionType					
			Case "rig"
				PosInX = oView.Left + oView.Width + (oView_Offset * PPAPdist) + 0.2
				PosInY = WorkPoint_1.PointOnSheet.Y + oWP_Offset
				DimensionType = DimensionTypeEnum.kVerticalDimensionType	
			Case "par" 'RIGHT SIDE ALIGNED DIMENSION
				PosInX = oView.Left + oView.Width + (oView_Offset * PPAPdist) + 0.2
				PosInY = WorkPoint_1.PointOnSheet.Y + oWP_Offset
				DimensionType = DimensionTypeEnum.kAlignedDimensionType
			Case "ang" 'LEFT SIDE ANGLE DIMENSION
				PosInX1 = oView.Left - (oView_Offset * PPAPdist) - 0.2
				PosInY1 = WorkPoint_2.PointOnSheet.Y + oWP_Offset 
				DimensionType = DimensionTypeEnum.kAngularDimensionType
				
		End Select		
			
		Dim oPointDim As Inventor.Point2d = ThisServer.TransientGeometry.CreatePoint2d(PosInX, PosInY) 	
		
		Dim CreateDimension As GeneralDimension = _
			oSheet.DrawingDimensions.GeneralDimensions.AddLinear(oPointDim, WorkPoint_1, WorkPoint_2, DimensionType,,)
		
		If Not UpperTol = 0 OrElse Not LowerTol = 0 Then  			
			If UpperTol = LowerTol Then  
				CreateDimension.Tolerance.SetToSymmetric(UpperTol * 0.1)
			Else 
				CreateDimension.Tolerance.SetToDeviation(UpperTol * 0.1,- LowerTol * 0.1)
			End If
		End If 
				
		Select Left(FormattedText, 5) 
			Case "Diam:" 'Adds diameter characters before and extra text after dimension.
				CreateDimension.Text.FormattedText = Chr(216) & "<DimensionValue/>" & Replace(FormattedText, "Diam:", "")
			Case "Equal" 'Adds diameter characters before and extra text after dimension.
				CreateDimension.Text.FormattedText = "= " & "<DimensionValue/>" & " = "
			Case "Idler" 'Adds diameter characters before and extra text after dimension.
				CreateDimension.Text.FormattedText = "= " & "<DimensionValue/>" & " IDLER CC ="
			Case "DP" 'Adds diameter characters before and extra text after dimension.
				CreateDimension.Text.FormattedText = "= " & "<DimensionValue/>" & " DECK PL ="
			Case "CRS" 'Adds diameter characters before and extra text after dimension.
				CreateDimension.Text.FormattedText = "= " & "<DimensionValue/>" & " IDLER FIXING CRS ="
			Case "ISMC" 'Adds diameter characters before and extra text after dimension.
				CreateDimension.Text.FormattedText = "ISMC " & "<DimensionValue/>"
			Case "THK." 'Adds diameter characters before and extra text after dimension.
				CreateDimension.Precision = 2
				CreateDimension.Text.FormattedText =  "<DimensionValue/>" & " THK."
			Case ""
				Exit Select
			Case Else 'Add extra text after dimension.
				CreateDimension.Text.FormattedText = "<DimensionValue/>" & FormattedText
		End Select
		
		Select oWP_Offset
			Case 0
				CreateDimension.CenterText
			Case >0
				CreateDimension.Text.HorizontalJustification = kAlignTextRight
			Case <0
				CreateDimension.Text.HorizontalJustification = kAlignTextRight
			End Select
				
		oSheet.Update
		
		Return "-"
	Catch ex As Exception
	
	End Try
'---------------------
End Function

 

0 Likes
Message 3 of 9

ss13953642009
Advocate
Advocate

//Hello, this is part of my code. 

Inventor.Application application = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "dwg|*.dwg";
openFileDialog.Title = "Select a DWG file";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFirstSheetNum.ReadOnly = true;
string filePath = openFileDialog.FileName;
firstDrawingPath = filePath;
DrawingDocument oDrawingDoc = (DrawingDocument)application.Documents.Open(filePath);
Sheets sheets = oDrawingDoc.Sheets;
Sheet sheet = sheets[int.Parse(firstSheetNum)];
sheet.Activate();
DrawingDimensions drawingDimensions = sheet.DrawingDimensions;
foreach (DrawingDimension dimension in drawingDimensions)
{
/**I want to use the code at this location to get the view name of the view where the collection intent is located, based on the first geometric intent of the dimension:
*string drawingViewName = dimension.IntentOne.Geometry.Parent.Name;
*When I was debugging the code in Visual Studio, I found that there is an IntentOne method under dimension, but when I try to call the IntentOne method, it prompts that dimension does not define IntentOne.
*What I need to do now is: reverse-engineer from the dimension on the drawing to determine which view the dimension was annotated in.
**/ string drawingDimensionEntityText = dimension.Text.Text;
double dimensionLineOriginPointX = dimension.Text.Origin.X;
double dimensionLineOriginPointY = dimension.Text.Origin.Y;
}
}

0 Likes
Message 4 of 9

punam_bansode
Contributor
Contributor
Accepted solution

Hi @ss13953642009  You can check this code as per your requirement. 

using Inventor;
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class DimensionViewExtractor
{
    private Inventor.Application _invApp;

    public void Run()
    {
        try
        {
            // Connect to Inventor
            _invApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");

            // Open DWG File
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Drawing Files (*.dwg)|*.dwg";
            openFileDialog.Title = "Select a DWG file";

            if (openFileDialog.ShowDialog() != DialogResult.OK)
                return;

            string filePath = openFileDialog.FileName;

            DrawingDocument oDrawingDoc = (DrawingDocument)_invApp.Documents.Open(filePath);
            Sheets sheets = oDrawingDoc.Sheets;

            // Use first sheet or select your own
            Sheet sheet = sheets[1];
            sheet.Activate();

            DrawingDimensions drawingDimensions = sheet.DrawingDimensions;

            foreach (DrawingDimension dimension in drawingDimensions)
            {
                if (dimension is GeneralDimension genDim)
                {
                    string dimText = genDim.Text.Text;
                    Point2d origin = genDim.Text.Origin;

                    string viewName = GetViewNameFromDimension(sheet, genDim, origin);

                    Console.WriteLine("View: " + viewName);
                    Console.WriteLine("Dimension: " + dimText);
                    Console.WriteLine("Origin: X=" + origin.X + ", Y=" + origin.Y);
                    Console.WriteLine("----------------------------------");
                }
            }

            MessageBox.Show("Finished extracting dimensions.");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
    }

    private string GetViewNameFromDimension(Sheet sheet, GeneralDimension dimension, Point2d origin)
    {
        try
        {
            // 1. Try to find by Annotations (most reliable)
            foreach (DrawingView view in sheet.DrawingViews)
            {
                foreach (object ann in view.Annotations)
                {
                    if (ann == (object)dimension)
                    {
                        return CleanViewName(view.Name);
                    }
                }
            }

            // 2. Fallback: check if origin point lies in view boundary
            foreach (DrawingView view in sheet.DrawingViews)
            {
                double left = view.Left;
                double top = view.Top;
                double right = left + view.Width;
                double bottom = top - view.Height;

                if (origin.X > left && origin.X < right &&
                    origin.Y < top && origin.Y > bottom)
                {
                    return CleanViewName(view.Name);
                }
            }
        }
        catch
        {
            return "Unknown";
        }

        return "Unknown";
    }

    private string CleanViewName(string fullViewName)
    {
        // Extract only "VIEW1" from "VIEW1:Assembly.iam"
        if (fullViewName.Contains(":"))
        {
            return fullViewName.Split(':')[0];
        }
        return fullViewName;
    }
}
0 Likes
Message 5 of 9

ss13953642009
Advocate
Advocate

Hello, thank you for your response. I encountered an issue while running the code: may I ask which version of the Inventor API you are using? I am using Inventor 2021, and when I try to run the code, I find that Annotations is not defined in DrawingView.

// 1. Try to find by Annotations (most reliable)
foreach (DrawingView view in sheet.DrawingViews)
{
foreach (object ann in view.Annotations)
{
if (ann == (object)dimension)
{
return CleanViewName(view.Name);
}
}
}

0 Likes
Message 6 of 9

punam_bansode
Contributor
Contributor

Hi @ss13953642009 ,

I am using 2024 version. maybe the error because of C# language.  I did some changes in annotation approach please check once again.

 

0 Likes
Message 7 of 9

punam_bansode
Contributor
Contributor
Accepted solution

This code is perfectly working on my system.

using System;
using System.Runtime.InteropServices;
using Inventor;
using System.Windows.Forms;


namespace InventorDimensionExtractor
{
    internal class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            DimensionViewExtractor extractor = new DimensionViewExtractor();
            extractor.Run();
        }




        public class DimensionViewExtractor
        {
            private Inventor.Application _invApp;

            public void Run()
            {
                try
                {
                    // Connect to running Inventor
                    _invApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");

                    // Open DWG File
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "Drawing Files (*.dwg)|*.dwg";
                    openFileDialog.Title = "Select a DWG file";

                    if (openFileDialog.ShowDialog() != DialogResult.OK)
                        return;

                    string filePath = openFileDialog.FileName;

                    DrawingDocument oDrawingDoc = (DrawingDocument)_invApp.Documents.Open(filePath);
                    Sheets sheets = oDrawingDoc.Sheets;

                    // Activate first sheet
                    Sheet sheet = sheets[1];
                    sheet.Activate();

                    DrawingDimensions drawingDimensions = sheet.DrawingDimensions;

                    foreach (DrawingDimension dimension in drawingDimensions)
                    {
                        // Only process GeneralDimension types
                        if (dimension is GeneralDimension genDim)
                        {
                            string dimText = genDim.Text.Text;
                            Point2d origin = genDim.Text.Origin;

                            string viewName = GetViewNameFromDimension(sheet, genDim);

                            Console.WriteLine("View: " + viewName);
                            Console.WriteLine("Dimension: " + dimText);
                            Console.WriteLine("Origin: X=" + origin.X.ToString("F2") + ", Y=" + origin.Y.ToString("F2"));
                            Console.WriteLine("----------------------------------");
                        }
                    }

                    MessageBox.Show("Finished extracting dimensions.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }

            private string GetViewNameFromDimension(Sheet sheet, GeneralDimension dimension)
            {
                try
                {
                    Point2d dimPos = dimension.Text.Origin;

                    Console.WriteLine($"--> Checking dimension at X: {dimPos.X:F2}, Y: {dimPos.Y:F2}");

                    foreach (DrawingView view in sheet.DrawingViews)
                    {
                        double left = view.Left;
                        double right = view.Left + view.Width;
                        double top = view.Top;
                        double bottom = view.Top - view.Height;

                        // Print view bounds for debugging
                        Console.WriteLine($"   View: {view.Name}");
                        Console.WriteLine($"     Left: {left:F2}, Right: {right:F2}, Top: {top:F2}, Bottom: {bottom:F2}");

                        double margin = 2.0; // Increased margin to tolerate small differences

                        bool xInRange = dimPos.X >= (left - margin) && dimPos.X <= (right + margin);
                        bool yInRange = dimPos.Y <= (top + margin) && dimPos.Y >= (bottom - margin);

                        if (xInRange && yInRange)
                        {
                            Console.WriteLine($"     --> MATCHED View: {view.Name}");
                            return CleanViewName(view.Name);
                        }
                    }

                    Console.WriteLine("     --> No matching view found.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("     [Error in view matching] " + ex.Message);
                }

                return "Unknown";
            }


            private string CleanViewName(string fullViewName)
            {
                if (fullViewName.Contains(":"))
                    return fullViewName.Split(':')[0];
                return fullViewName;
            }
        }
    }

}
0 Likes
Message 8 of 9

ss13953642009
Advocate
Advocate

Hello, I have a question. Currently, the code can only find dimensions within the view. However, if a dimension is placed in the view but the text is moved outside the dimension, the current code cannot locate the dimension in the view. I tried converting the GeneralDimension to LinearGeneralDimension or DiameterGeneralDimension for judgment and then obtaining the IntentOne.PointOnSheet or IntentTwo.PointOnSheet of the LinearGeneralDimension, but this introduces a new issue. The diameter dimension is not converted to a DiameterGeneralDimension. Another problem is that when I mark a part of the model as a reference, I cannot retrieve the reference line when fetching the dimension.

0 Likes
Message 9 of 9

punam_bansode
Contributor
Contributor

Hi @ss13953642009

some APIs for 2021 are not available which are updated one. let's try this code once if it's working then works with 2021 otherwise, I would suggest using 2024 version.

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Inventor;

namespace InventorDimensionExtractor
{
    internal class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            DimensionViewExtractor extractor = new DimensionViewExtractor();
            extractor.Run();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        public class DimensionViewExtractor
        {
            private Inventor.Application _invApp;

            public void Run()
            {
                try
                {
                    _invApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");

                    OpenFileDialog openFileDialog = new OpenFileDialog
                    {
                        Filter = "Drawing Files (*.dwg)|*.dwg",
                        Title = "Select a DWG file"
                    };

                    if (openFileDialog.ShowDialog() != DialogResult.OK)
                        return;

                    string filePath = openFileDialog.FileName;

                    DrawingDocument oDrawingDoc = (DrawingDocument)_invApp.Documents.Open(filePath);
                    Sheet sheet = oDrawingDoc.Sheets[1];
                    sheet.Activate();

                    DrawingDimensions drawingDimensions = sheet.DrawingDimensions;

                    foreach (DrawingDimension dimension in drawingDimensions)
                    {
                        if (dimension is GeneralDimension genDim)
                        {
                            string dimText = genDim.Text.Text;
                            Point2d textOrigin = genDim.Text.Origin;

                            // --- Debug output of all available properties for exploration ---
                            Console.WriteLine($"--- PROPERTIES FOR DIMENSION: {dimText} ---");
                            foreach (var prop in genDim.GetType().GetProperties())
                            {
                                Console.WriteLine($"Property: {prop.Name}");
                            }
                            Console.WriteLine("----------------------------------");

                            string viewName = GetViewNameFromIntentOrText(sheet, genDim);

                            Console.WriteLine("View: " + viewName);
                            Console.WriteLine("Dimension: " + dimText);
                            Console.WriteLine("Text Origin: X=" + textOrigin.X.ToString("F2") + ", Y=" + textOrigin.Y.ToString("F2"));
                            Console.WriteLine("----------------------------------");
                        }
                    }

                    MessageBox.Show("Finished extracting dimensions.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }

            private string GetViewNameFromIntentOrText(Sheet sheet, GeneralDimension dimension)
            {
                Point2d pt = null;

                // Try using intent point first
                try
                {
                    object intentObj = dimension.GetType().GetProperty("IntentOne")?.GetValue(dimension);
                    if (intentObj != null)
                    {
                        pt = intentObj.GetType().GetProperty("PointOnSheet")?.GetValue(intentObj) as Point2d;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("IntentOne lookup failed: " + ex.Message);
                }

                // Fallback to text origin if intent is unavailable
                if (pt == null)
                {
                    pt = dimension.Text.Origin;
                }

                // Match point to view bounds
                foreach (DrawingView view in sheet.DrawingViews)
                {
                    double margin = 5.0;
                    double left = view.Left - margin;
                    double right = view.Left + view.Width + margin;
                    double top = view.Top + margin;
                    double bottom = view.Top - view.Height - margin;

                    if (pt.X > left && pt.X < right && pt.Y < top && pt.Y > bottom)
                    {
                        return CleanViewName(view.Name);
                    }
                }

                return "Unknown";
            }

            private string CleanViewName(string fullViewName)
            {
                if (fullViewName.Contains(":"))
                    return fullViewName.Split(':')[0];
                return fullViewName;
            }
        }
    }
}
0 Likes