batch flat pattern

batch flat pattern

design5LD8F
Explorer Explorer
264 Views
3 Replies
Message 1 of 4

batch flat pattern

design5LD8F
Explorer
Explorer

Hi

 

I used google AI to write a ilogic code that creates dxf files for all open sheet metal parts.

what i want it to do is use my flat pattern dxf export options, add my job number to the end of the file name, and decide which side to use as the front ( which ever side has the most IV_BEND or bend lines (front) lines).

 

code below, any help appreciated

 

' 1. DEFINE YOUR INI PATH
Dim sIniFile As String = "C:\Users\design.BRISELEC\Documents\Drawing Standards and Parameters\FlatPatternConfiguration.ini"

If Not System.IO.File.Exists(sIniFile) Then
MessageBox.Show("Configuration file not found at:" & vbLf & sIniFile, "Error")
Return
End If

' 2. PROMPT FOR JOB NUMBER ONCE
Dim oJobNum As String = InputBox("Enter Job Number for ALL open parts:", "Batch Export", "")
If String.IsNullOrEmpty(oJobNum) Then Return

' 3. CAPTURE OPEN DOCUMENTS
Dim oDocsToProcess As New List(Of Document)
For Each oDoc As Document In ThisApplication.Documents.VisibleDocuments
oDocsToProcess.Add(oDoc)
Next

' 4. PROCESS LOOP
For Each oDoc As Document In oDocsToProcess
If oDoc.DocumentType = DocumentTypeEnum.kPartDocumentObject Then
oDoc.Activate() ' Prevents export errors in 2024
Dim oPartDoc As PartDocument = oDoc

If oPartDoc.ComponentDefinition.Type = ObjectTypeEnum.kSheetMetalComponentDefinitionObject Then
Dim oCompDef As SheetMetalComponentDefinition = oPartDoc.ComponentDefinition

' A. REFRESH FLAT PATTERN
If oCompDef.HasFlatPattern Then
Try : oCompDef.FlatPattern.Delete() : Catch : End Try
End If
Try : oCompDef.Unfold() : Catch : Continue For : End Try

' B. OPTIMIZE BEND DIRECTION (Favor Front/Up Bends)
Dim oFlatPattern As FlatPattern = oCompDef.FlatPattern
Dim upCount As Integer = 0
Dim downCount As Integer = 0
For Each oResult As FlatBendResult In oFlatPattern.FlatBendResults
If oResult.IsDirectionUp Then upCount += 1 Else downCount += 1
Next
If downCount > upCount Then
oFlatPattern.FlatPatternOrientations.ActiveFlatPatternOrientation.FlipBaseFace = Not oFlatPattern.FlatPatternOrientations.ActiveFlatPatternOrientation.FlipBaseFace
End If

' C. DEFINE FILENAME
Dim oFileName As String = System.IO.Path.GetFileNameWithoutExtension(oPartDoc.FullFileName)
Dim oFilePath As String = System.IO.Path.GetDirectoryName(oPartDoc.FullFileName)
Dim sFullDXFName As String = oFilePath & "\" & oFileName & " - " & oJobNum & ".dxf"

' D. ROBUST EXPORT STRING (Forces valid version and loads INI)
' Using AcadVersion=2018 is standard for 2024. Use R12 if your CNC is very old.
Dim sOut As String = "FLAT PATTERN DXF?AcadVersion=2018&ConfigFile=" & sIniFile

Try
' This method is the most direct way to bypass "not valid" errors
oCompDef.DataIO.WriteDataToFile(sOut, sFullDXFName)
oPartDoc.Save()
oPartDoc.Close(True)
Catch ex As Exception
' Skips read-only or locked files
End Try
End If
End If
Next

MessageBox.Show("Batch processing complete.", "Success")

0 Likes
265 Views
3 Replies
Replies (3)
Message 2 of 4

WCrihfield
Mentor
Mentor

Hi @design5LD8F.  Unfortunately, when using the DataIO.WriteDataToFile method, we can not use the 'INI' file.  Instead, we must include all specifications / settings / options (see help documentation at the Link provided) directly within the 'Format' input (the 'sOut' variable's value, in your case).  Depending on the extent of custom settings you use, that can require a TON of additional lines in your rule, to fit all of those specifications into that one String value.  In newer versions of Inventor (starting with 2025), we can use the TranslatorAddIn.SaveCopyAs method, supply the FlatPattern object itself directly as the 'SourceObject' input, instead of the Document object.  Then when using that SaveCopyAs method, the one 'Option' we have is to specify the full file name of the 'INI' file, so that it can use the settings in that file...similar to the manual process.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 3 of 4

design5LD8F
Explorer
Explorer

Hi Wesley 

 

Yes this morning i worked this out today, using 2024, might pay to update soon, but i did get it to work today with adding in centre punch marks on fold lines.

i also tried to create all the sheet metal dxf's straight out of the assembly ranther than opening all parts and running the code. no luck yet. 

 

' 1. Setup - Manual DXF Option String
Dim sOut As String = "FLAT PATTERN DXF?AcadVersion=2004" _
    & "&OuterProfileLayer=IV_OUTER_PROFILE&OuterProfileLayerColor=0;0;0" _
    & "&InteriorProfilesLayer=IV_INTERIOR_PROFILES&InteriorProfilesLayerColor=0;0;0" _
    & "&BendUpLayer=IV_BEND&BendUpLayerColor=255;0;0" _
    & "&BendDownLayer=IV_BEND_DOWN&BendDownLayerColor=0;255;255" _
    & "&FeatureProfilesUpLayer=IV_FEATURE_PROFILES&FeatureProfilesUpLayerColor=255;128;0" _
    & "&FeatureProfilesDownLayer=IV_FEATURE_PROFILES_DOWN&FeatureProfilesDownLayerColor=0;255;0" _
    & "&AltRepFrontLayer=IV_ALTREP_FRONT&AltRepFrontLayerColor=0;0;0" _
    & "&AltRepBackLayer=IV_ALTREP_BACK&AltRepBackLayerColor=0;0;0" _
    & "&RollTangentLayer=IV_ROLL_TANGENT&RollTangentLayerColor=0;0;0" _
    & "&RollLayer=IV_ROLL&RollLayerColor=0;0;0" _
    & "&UnconsumedSketchesLayer=IV_UNCONSUMED_SKETCHES" _
    & "&SimplifySplines=True&SplineSimplificationMethod=Linear&ChordTolerance=0.01" _
    & "&InvisibleLayers=IV_TANGENT;IV_TOOL_CENTER;IV_TOOL_CENTER_DOWN;IV_ARC_CENTERS"

' 2. Prompt for Job Number
Dim oJobNum As String = InputBox("Enter Job Number for ALL open parts:", "Batch Export", "")
If String.IsNullOrEmpty(oJobNum) Then Return

' 3. Process open documents
Dim oDocsToProcess As New List(Of Document)
For Each oDoc As Document In ThisApplication.Documents.VisibleDocuments
    ' Only add parts that are actually saved to disk (have a file path)
    If oDoc.DocumentType = DocumentTypeEnum.kPartDocumentObject AndAlso Not String.IsNullOrEmpty(oDoc.FullFileName) Then
        oDocsToProcess.Add(oDoc)
    End If
Next

For Each oDoc As Document In oDocsToProcess
    Dim oPartDoc As PartDocument = oDoc
    oPartDoc.Activate()
    
    If oPartDoc.ComponentDefinition.Type = ObjectTypeEnum.kSheetMetalComponentDefinitionObject Then
        Dim oCompDef As SheetMetalComponentDefinition = oPartDoc.ComponentDefinition
        
        ' A. Ensure Flat Pattern exists
        Try
            If Not oCompDef.HasFlatPattern Then
                oCompDef.Unfold()
            End If
        Catch ex As Exception
            oPartDoc.Close(True) ' Close even if unfold fails
            Continue For
        End Try
        
        Dim oFlatPattern As FlatPattern = oCompDef.FlatPattern
        oFlatPattern.Edit()

        ' --- CENTER MARKING LOGIC ---
        Dim oSketch As PlanarSketch
        Try : oSketch = oFlatPattern.Sketches.Item("CTR_MARKS") : oSketch.Delete() : Catch : End Try
        oSketch = oFlatPattern.Sketches.Add(oFlatPattern.TopFace, False)
        oSketch.Name = "CTR_MARKS"

        Dim c1_rad As Double = 0.05 ' 0.5mm
        Dim c2_rad As Double = 0.025 ' 0.25mm
        Dim oTG As TransientGeometry = ThisApplication.TransientGeometry
        
        For Each oResult As FlatBendResult In oFlatPattern.FlatBendResults
            Dim oSketchLine As SketchLine = oSketch.AddByProjectingEntity(oResult.Edge)
            Dim pStart As Point2d = oSketchLine.StartSketchPoint.Geometry
            Dim pEnd As Point2d = oSketchLine.EndSketchPoint.Geometry
            Dim unitDir As Vector2d = oTG.CreateVector2d(pEnd.X - pStart.X, pEnd.Y - pStart.Y)
            unitDir.Normalize()

            If oResult.IsDirectionUp Then
                oSketch.SketchCircles.AddByCenterRadius(oTG.CreatePoint2d(pStart.X + unitDir.X * 0.5, pStart.Y + unitDir.Y * 0.5), c1_rad)
                oSketch.SketchCircles.AddByCenterRadius(oTG.CreatePoint2d(pEnd.X - unitDir.X * 0.5, pEnd.Y - unitDir.Y * 0.5), c1_rad)
            Else
                Dim offsets() As Double = {0.5, 0.75, 1.0}
                Dim radii() As Double = {c1_rad, c2_rad, c1_rad}
                For i As Integer = 0 To 2
                    oSketch.SketchCircles.AddByCenterRadius(oTG.CreatePoint2d(pStart.X + unitDir.X * offsets(i), pStart.Y + unitDir.Y * offsets(i)), radii(i))
                    oSketch.SketchCircles.AddByCenterRadius(oTG.CreatePoint2d(pEnd.X - unitDir.X * offsets(i), pEnd.Y - unitDir.Y * offsets(i)), radii(i))
                Next
            End If
            oSketchLine.Delete()
        Next
        oFlatPattern.ExitEdit()

        ' B. Flip Logic
        Dim upBends As New List(Of Double)
        Dim downBends As New List(Of Double)
        For Each oResult As FlatBendResult In oFlatPattern.FlatBendResults
            Dim oLine As LineSegment = oResult.Edge.Geometry
            Dim pos As Double = If(Math.Abs(oLine.Direction.X) > 0.9, oLine.MidPoint.Y, oLine.MidPoint.X)
            Dim targetList As List(Of Double) = If(oResult.IsDirectionUp, upBends, downBends)
            Dim isFound As Boolean = False
            For Each existingPos In targetList
                If Math.Abs(existingPos - pos) < 0.001 Then : isFound = True : Exit For : End If
            Next
            If Not isFound Then targetList.Add(pos)
        Next

        If downBends.Count > upBends.Count Then
            oFlatPattern.FlatPatternOrientations.ActiveFlatPatternOrientation.FlipBaseFace = Not oFlatPattern.FlatPatternOrientations.ActiveFlatPatternOrientation.FlipBaseFace
        End If

        ' D. Export, Save, and Close
        Dim oFileName As String = System.IO.Path.GetFileNameWithoutExtension(oPartDoc.FullFileName)
        Dim oFilePath As String = System.IO.Path.GetDirectoryName(oPartDoc.FullFileName)
        Dim sFullDXFName As String = System.IO.Path.Combine(oFilePath, oFileName & " - " & oJobNum & ".dxf")

        Try
            oCompDef.DataIO.WriteDataToFile(sOut, sFullDXFName)
        Catch ex As Exception
            ' If export fails (e.g. file locked), we still want to save/close part
        End Try
        
        oPartDoc.Save()
        oPartDoc.Close(True)
    Else
        ' If not sheet metal, just close it? (Optional)
        ' oPartDoc.Close(True)
    End If
Next

MessageBox.Show("Batch processing complete", "Success")

 

 

 

@design5LD8F - this post has been edited due to Community Rules & Etiquette violation

 

0 Likes
Message 4 of 4

WCrihfield
Mentor
Mentor

Hi @design5LD8F.  I noticed that you are using the SheetMetalComponentDefinition.DataIO Property to access its WriteDataToFile Method, then ensuring that the FlatPattern is in 'Edit Mode' before the export.  Have you tried using the FlatPattern.DataIO Property to access the WriteDataToFile Method, then not having the FlatPattern in 'Edit Mode' while doing the export step.  Seems like it would be less complicated, and have less problems doing it from the assembly that way, because that part document would not need to be 'activated'.  You would just want to make sure the document was updated after any previous changes, before doing the export step, but that should not require document activation.  Just an idea.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes