Help: Code For "Export face as". Have tried everything i know

Help: Code For "Export face as". Have tried everything i know

xenocatalyst
Advocate Advocate
5,289 Views
27 Replies
Message 1 of 28

Help: Code For "Export face as". Have tried everything i know

xenocatalyst
Advocate
Advocate

Hello,

 

I have been trying to write an iLogic rule to automate the process of exporting a selected face to a dxf file.

The file name and location is set using information from iproperties and project values.

I have searched this forum and the web in general but cant seem to find an answer to my problem.

My background in coding is from autocad lisp (enough to get me by), maybe this is confusing my understanding of iLogic.

Maybe the code i have found is for VB and not iLogic.

With all the examples i have referenced I have been unable to see any link between the select face function and the export function.

How does "GeomToDXFCommand" know what face you have selected?

 

With the code I have everything seems to work except the actual export function.

 

 

When i run the rule from the iLogic Browser (right click, run), i get prompted to select a face.

I select the face i want to export and then nothing.

 

If I then right click and select "Export Face As" a dxf file with the correct filename is created in the project folder in a folder called "DXF".

This happens without and dialog box or prompts, as I would expect if the ilogic rule ran correctly.

 

Any help with coding or my understanding of the code would be greatly appreciated.

 

Here is my code, it is a work in progress so it may be a bit untidy.

I have also attached the ilogic file.

 

 

'check that this active document is a part file    

'[ ;Part Check
Imports System.Windows.Forms
If ThisApplication.ActiveDocument.DocumentType <> kPartDocumentObject Then
MessageBox.Show ("Please open a part document", "iLogic")
End If
']

'[ ;Set Variables
oPath = ThisDoc.Path

''Set a reference to the active document (the document to be published).
Dim oDocument As Document = ThisApplication.ActiveDocument
	
'' Create a DataMedium object
Dim oDataMedium As DataMedium = ThisApplication.TransientObjects.CreateDataMedium
	oQty = iProperties.Value(docFName, "Project", "Stock Number")
	oMat = iProperties.Value(docFName, "Summary", "Comments")
	oFolder = oPath & "\DXF\"
	oFileName = ThisDoc.FileName(False) & " - "& oMat & " - " & oQty & " Required.dxf" 'without extension

''Check for the DXF folder and create it if it does not exist
	If Not System.IO.Directory.Exists(oFolder) Then
    	System.IO.Directory.CreateDirectory(oFolder)
	End If

''Set the dxf target file name
oDataMedium.FileName = oFolder & oFilename 
DefaultChoice = True
'MessageBox.Show(oDataMedium.FileName)
''copies filename to clipboard for paste (ctrl + v)
'Clipboard.SetText(oFileName)
']


'[;Selection Code
Dim testFace As Face 
                
                 Try
                 testFace = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kPartFaceFilter, "Select a face") 
                 Catch  ex As Exception
                 End Try
            
                    If (testFace Is Nothing) Then
                        Return
                    End If
']

'[;Export code 1

'Get CommandManager object
'Dim Cm As CommandManager
'Cm = ThisApplication.CommandManager
Dim Cm As CommandManager = ThisApplication.CommandManager
Cm.PostPrivateEvent(PrivateEventTypeEnum.kFileNameEvent, oDataMedium.FileName)


'Get control definition for the line command. 
'Dim oCDef As ControlDefinition = Cm.ControlDefinitions.Item( "GeomToDXFCommand")
'oCDef.Execute()

'''at this point i can right click on face and select 'Export as face' and it will be saved properly
'''without any further input.
'''Its Almost as if the selected face isn't being parsed to the GeomToDXFCommand.
']

'[;Clear Variables
oPath = Nothing
oDocument = Nothing
oDataMedium = Nothing
oQty = Nothing
oMat = Nothing
oFolder = Nothing
oFileName = Nothing
testFace = Nothing

']

 

 

Accepted solutions (2)
5,290 Views
27 Replies
Replies (27)
Message 21 of 28

FESP-meloman
Explorer
Explorer

I try to export face as DWG in my IAM for each IPT with or without specific esquiss.

Based on the answer I modified my code to integrate "SelectSet" object.

 

But I can't make it working.

Sub ExploreComponents(components As ComponentOccurrences, SaveFolder As String)

    Dim oComp As ComponentOccurrence
    Dim oPartDoc As PartDocument
    
    For Each oComp In components
        On Error Resume Next ' Ignorer les erreurs et passer au composant suivant en cas de problème
        
        ' Vérifie si le composant est un document de pièce
        If Not oComp Is Nothing Then
        
            ' Vérifie si le composant est un document de pièce
            If TypeOf oComp.Definition.Document Is PartDocument Then
                Set oPartDoc = oComp.Definition.Document
                
                ' Affiche le nom de la pièce dans la console
                Debug.Print "Nom de la pièce : " & oPartDoc.DisplayName
                
                ' Affiche la valeur de la propriété BOMStructure dans la console
                Debug.Print "BOMStructure : " & oPartDoc.ComponentDefinition.BOMStructure
        
                ' Si la pièce est une tôle...
                If oPartDoc.ComponentDefinition.BOMStructure = 51970 Then
                    Debug.Print "Pièce en tôle détectée : " & oPartDoc.DisplayName
                    
                    ' Enregistre la pièce au format STEP
                    oPartDoc.SaveAs SaveFolder & oPartDoc.DisplayName & ".stp", True
                    
                    ' Enregistre la mise à plat (DWG)...
                    Dim oFlatPattern As FlatPattern
                    Set oFlatPattern = oPartDoc.ComponentDefinition.FlatPattern
                    
                    If Not oFlatPattern Is Nothing Then
                        ' Exporte l'esquisse de la mise à plat si elle existe
                        If oFlatPattern.Sketches.Count > 0 Then
                            Debug.Print "Esquisse de mise à plat trouvée pour la pièce : " & oPartDoc.DisplayName
                            ' Sélectionne directement le sketch de la mise à plat
                            ThisApplication.ActiveDocument.SelectSet.Clear
                            ThisApplication.ActiveDocument.SelectSet.Select (oFlatPattern.Sketches.Item(1))
                            ' Exporte la face comme DWG
                            ThisApplication.CommandManager.ControlDefinitions.Item("AppExportFaceAs").Execute
                            Debug.Print "DWG enregistré avec succès pour la pièce : " & oPartDoc.DisplayName
                        Else
                            Debug.Print "Aucune esquisse de mise à plat trouvée pour la pièce : " & oPartDoc.DisplayName
                        End If
                    Else
                        Debug.Print "Mise à plat non trouvée pour la pièce : " & oPartDoc.DisplayName
                    End If
        
                End If
                
            ElseIf TypeOf oComp.Definition.Document Is AssemblyDocument Then
                ' Si le composant est un assemblage, appelle récursivement la fonction pour explorer ses composants
                ExploreComponents oComp.SubOccurrences, SaveFolder
            End If
            
        End If
        On Error GoTo 0 ' Réactiver la gestion des erreurs normale
    Next oComp

End Sub

 

Could someone help me ?
My VBA is rusted.

 

Regards

0 Likes
Message 22 of 28

WCrihfield
Mentor
Mentor

Hi @FESP-meloman.  Is this VBA macro something that you are planning on running from a button in your Inventor ribbon?  If so, it can not have any 'input' parameters, like your example has.  However, this VBA routine could be called to run by another VBA macro, and if that other one is a Sub (not a Function) and does not have any input parameters, then it may be used as a button.  Beyond that concern, down within your large loop of components, where you it looks like you are attempting to select a sketch from within the FlatPattern of a sheet metal part, then export that as a DWG...you are using the 'ThisApplication.ActiveDocument' phrase there for the selection.  I believe that will be impossible, because they will be referring to the assembly that you are running this code on, not that part being referenced by that component.  You already have the 'oPartDoc' variable available at that point, so why not use that?  Also, I am not sure you can select something in some other referenced document like that, without that document being visibly showing on your screen at the time...and since that sketch is within the FlatPattern, you may even need to be in Edit Mode of that FlatPattern before you can select it, because it would not be available from the folded part mode.

Plus, I do not recognize the "AppExportFaceAs" ControlDefinition you are trying to execute there.  Where did you come up with that from?

Edit (5/2/2024):

The command that the others have been using in this discussion is "GeomToDXFCommand".  And I believe the same command would also be used for exporting to DWG, even though it has DXF right in its name.  You would just have to specify ".dwg" as the extension of the file that you want it exported to.  But since this code is just executing a command, and not using API for the export, that will usually just launch the dialog, allowing you to manually specify which document type, access to the Options button, and where to save it.

 

There is another way to export a planar part face as either DXF or DWG, but it requires a lot more code, instead of executing a command.  It involved creating a sketch on that face, capturing all its edges as sketch geometry, making sure the geometry is not construction status, then using the Sketch.DataIO.WriteDataToFile() method.  But in order to keep it 'clean', we have to use an Inventor.Transaction to wrap the sketch creation actions into a single item in the UNDO list, then after the export, abort that Transaction, which gets rid of the sketch, but not the exported DXF/DWG file.  And I do not believe we can use the same settings that we can use for exporting sheet metal FlatPattern directly to DXF with that method when just exporting a sketch with it.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 23 of 28

FESP-meloman
Explorer
Explorer

Thanks,

I'll check this.

 

Indeed, this function is called by another function, the whole thing should be executed by a button later.

 

The aim of all this is to automate the export (because this work is time-consuming by hand) of all the flattened versions for laser cutting and the folded versions for the folding machine. DXF part of the script is working great.

 

DWG one is not working but no error. In fact, what I want to do (automatically with marco for all IPT that are sheet only) is equivalent of "right button click" > "export face as..." > which is opening "save copy as" window but with some specific options.

 

itDPXP8_1-1714973233915.png

 

0 Likes
Message 24 of 28

WCrihfield
Mentor
Mentor
Accepted solution

Hi @FESP-meloman.  When looking at your code again, you are actually attempting to select a PlanarSketch type object, instead of a Face type object.  Not sure if that command (with "Face" right in its name) will work for a PlanarSketch.  You may be able to use the PlanarSketch.DataIO.WriteDataToFile() method instead of trying to select that sketch, then execute a command on it.  Some commands often do not work really well when used in a loop, because the code does not know to wait for it to finish processing, before it continues trying to process the next line of code.

PlanarSketch 

PlanarSketch.DataIO 

DataIO 

DataIO.WriteDataToFile 

When I used the DataIO.GetOutputFormats method (from a PlanarSketch object), I get both DXF & DWG as the file formats, and 'kFileStorage' for both storage types.  That means this can be used to export the PlanarSketch object out as either of those two file types.  You should likely try that instead of the selection and command execution process.  You would not have the dialog popping up, asking you where to put them, or what to name them though, so you would have to prepare a full file path & name (single String including full path, file name, and file extension) ahead of time to specify within that method (as its 'FileName').  Then, as the 'Format' String, just specify either "DXF" or "DWG".

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 25 of 28

i_dubail
Enthusiast
Enthusiast

Thank you very much, it works perfectly!!!

Message 26 of 28

FESP-meloman
Explorer
Explorer

Thanks for your help @WCrihfield 

Message 27 of 28

i_dubail
Enthusiast
Enthusiast
Imports System.Windows.Forms
Imports Inventor
 
Sub Main()
    ' Vérifier que le document actif est une pièce
    If ThisApplication.ActiveDocument.DocumentType <> kPartDocumentObject Then
        MessageBox.Show("Veuillez ouvrir un document pièce.", "iLogic")
        Return
    End If
 
    ' Définir les variables
    Dim oDoc As PartDocument = ThisApplication.ActiveDocument
    Dim oFolder As String = "V:\Découpe\"
    Dim oFileName As String = ThisDoc.FileName(False) & ".dwg" ' Changez l'extension ici si nécessaire
    Dim oExportPath As String = oFolder & oFileName
 
    ' Créer le dossier si nécessaire
    If Not System.IO.Directory.Exists(oFolder) Then
        System.IO.Directory.CreateDirectory(oFolder)
    End If
 
    Try
        ' Sélectionner une face
        Dim oFace As Face
        oFace = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kPartFaceFilter, "Sélectionner une face pour créer une esquisse")
        If oFace Is Nothing Then
            MessageBox.Show("Aucune face sélectionnée. Abandon.", "iLogic")
            Return
        End If
 
        ' Créer une esquisse sur la face sélectionnée
        Dim oCompDef As ComponentDefinition = oDoc.ComponentDefinition
        Dim oSketch As PlanarSketch = oCompDef.Sketches.Add(oFace)
 
        ' Projeter toutes les arêtes de la face dans l'esquisse
        For Each oEdge As Edge In oFace.Edges
            oSketch.AddByProjectingEntity(oEdge)
        Next
 
        ' Exporter l'esquisse en DWG via DataIO
        oSketch.DataIO.WriteDataToFile("DWG", oExportPath)
 
        ' Supprimer l'esquisse après l'export
        oSketch.Delete()
 
' Effacer la sélection après l'export
oDoc.SelectSet.Clear()
 
        ' Confirmation
       ' MessageBox.Show("Exportation réussie vers : " & oExportPath, "Export OK")
 
' Confirmation
Dim Reponse As DialogResult
Reponse = MessageBox.Show("Face exportée avec succès : " & vbCrLf & oExportPath _
& vbCrLf & vbCrLf & _
"Voulez-vous ouvrir le dossier Découpe ?", "Export OK - Open Folder", _
MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
 
    ' Si l'utilisateur clique sur "Non" (DialogResult.No), quitter la règle
    If Reponse = DialogResult.No Then
        Return
    End If
 
Catch ex As Exception
    MessageBox.Show("Erreur durant l'export : " & ex.Message, "iLogic")
End Try
 
End Sub

 

0 Likes
Message 28 of 28

i_dubail
Enthusiast
Enthusiast

To export the selected face as DWG : 

Imports System.Windows.Forms
Imports Inventor
 
Sub Main()
    ' Vérifier que le document actif est une pièce
    If ThisApplication.ActiveDocument.DocumentType <> kPartDocumentObject Then
        MessageBox.Show("Veuillez ouvrir un document pièce.", "iLogic")
        Return
    End If
 
    ' Définir les variables
    Dim oDoc As PartDocument = ThisApplication.ActiveDocument
    Dim oFolder As String = "V:\Découpe\"
    Dim oFileName As String = ThisDoc.FileName(False) & ".dwg" ' Changez l'extension ici si nécessaire
    Dim oExportPath As String = oFolder & oFileName
 
    ' Créer le dossier si nécessaire
    If Not System.IO.Directory.Exists(oFolder) Then
        System.IO.Directory.CreateDirectory(oFolder)
    End If
 
    Try
        ' Sélectionner une face
        Dim oFace As Face
        oFace = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kPartFaceFilter, "Sélectionner une face pour créer une esquisse")
        If oFace Is Nothing Then
            MessageBox.Show("Aucune face sélectionnée. Abandon.", "iLogic")
            Return
        End If
 
        ' Créer une esquisse sur la face sélectionnée
        Dim oCompDef As ComponentDefinition = oDoc.ComponentDefinition
        Dim oSketch As PlanarSketch = oCompDef.Sketches.Add(oFace)
 
        ' Projeter toutes les arêtes de la face dans l'esquisse
        For Each oEdge As Edge In oFace.Edges
            oSketch.AddByProjectingEntity(oEdge)
        Next
 
        ' Exporter l'esquisse en DWG via DataIO
        oSketch.DataIO.WriteDataToFile("DWG", oExportPath)
 
        ' Supprimer l'esquisse après l'export
        oSketch.Delete()
 
' Effacer la sélection après l'export
oDoc.SelectSet.Clear()
 
        ' Confirmation
       ' MessageBox.Show("Exportation réussie vers : " & oExportPath, "Export OK")
 
' Confirmation
Dim Reponse As DialogResult
Reponse = MessageBox.Show("Face exportée avec succès : " & vbCrLf & oExportPath _
& vbCrLf & vbCrLf & _
"Voulez-vous ouvrir le dossier Découpe ?", "Export OK - Open Folder", _
MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
 
    ' Si l'utilisateur clique sur "Non" (DialogResult.No), quitter la règle
    If Reponse = DialogResult.No Then
        Return
    End If
 
Catch ex As Exception
    MessageBox.Show("Erreur durant l'export : " & ex.Message, "iLogic")
End Try
 
'Si on est arrivé au bout de la règle - on n'a pas cliqué sur non => Ouvrir le dossier
iLogicVb.RunExternalRule("Open_DECOUPE_Folder.iLogicVb")
 
End Sub