Help with saving copy as iges or step of part within assembly

Help with saving copy as iges or step of part within assembly

dschulteHR4D5
Advocate Advocate
3,018 Views
47 Replies
Message 1 of 48

Help with saving copy as iges or step of part within assembly

dschulteHR4D5
Advocate
Advocate

Hello all, I am looking for some assistance with iLogic coding... Let me try to explain what i am looking for here, bear with me.

 

For my workflow, i am designing one-off tooling that trims plastic blow molded parts. We have an in house tool room where we design and build most of the tooling we use. With that being said, we build some of the parts, some times some of them get sent out to other companies to build then we assemble depending on the job. 

 

So i will design an entire project for say a trim station, and the parts we build i will save as an igs for our cnc department to use. Then some of the companies need the files as a stp and the drawings as a dxf. 

 

What i am trying to do essentially is take the entire assembly, and hide the parts i do not want to convert to say an iges. But when i use this code it saves everything in the assembly, and i believe it saves assemblies within the assembly as an iges as well, whereas i want each individual part saved as an iges, not the whole assembly. So it seems i need to add something to recognize only visible items, and to only select parts, not assemblies within the assembly. Is this possible? This is the current code i am using right now. 

 

'Define the open document
Dim openDoc As Document
openDoc = ThisDoc.Document


'path from current file
oFolder = ThisDoc.WorkspacePath() & "\CNC FILES"

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

'Look at all of the files referenced in the open document
Dim docFile As Document
For Each docFile In openDoc.AllReferencedDocuments                
'format  file name                   
Dim FNamePos As Long
'postion of last back slash
FNamePos = InStrRev(docFile.FullFileName, "\", -1)                        
Dim docFName As String 
'file name with extension
docFName = Right(docFile.FullFileName, Len(docFile.FullFileName) - FNamePos) 
'file name without extension
shortname = Left(docFName, Len(docFName) -4) 

	' Get the IGES translator Add-In.
	Dim oIGESTranslator As TranslatorAddIn
	oIGESTranslator = ThisApplication.ApplicationAddIns.ItemById _ 
	("{90AF7F44-0C01-11D5-8E83-0010B541CD80}")
	Dim oContext As TranslationContext
	oContext = ThisApplication.TransientObjects.CreateTranslationContext
	Dim oOptions As NameValueMap
	oOptions = ThisApplication.TransientObjects.CreateNameValueMap
	If oIGESTranslator.HasSaveCopyAsOptions(docFile, oContext, oOptions) Then
	   ' Set geometry type for wireframe.
	   ' 0 = Surfaces, 1 = Solids, 2 = Wireframe
	   'oOptions.Value("GeometryType") = 1
	   ' To set other translator values:
	   ' oOptions.Value("SolidFaceType") = n
	   ' 0 = NURBS, 1 = Analytic
	   ' oOptions.Value("SurfaceType") = n
	   ' 0 = 143(Bounded), 1 = 144(Trimmed)
	oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
	Dim oData As DataMedium
	oData = ThisApplication.TransientObjects.CreateDataMedium
	'set file path for IGS file
	oData.FileName =  oFolder & "\" & shortname & ".igs"
	oIGESTranslator.SaveCopyAs(docFile, oContext, oOptions, oData)
	End If
Next

 This code also checks and makes a folder for CNC FILES if there isnt one there, as mentioned, i use this for our CNC department so it works, but it seems like it saves subassemblies as one igs file, and not the individual parts within a subassembly. 

 

Also i would like to map out how to reference if i translate to an step file, to find a reference drawing of that part and also save the drawing as a dxf if this would be possible. 

 

Thanks for any help!! Ill take anything i can get for knowledge of this, i am pretty new to ilogic but have made this code from cross referencing a number of posts and different codes and eventually got it to work. 

0 Likes
Accepted solutions (4)
3,019 Views
47 Replies
Replies (47)
Message 2 of 48

Ralf_Krieg
Advisor
Advisor
Accepted solution

Hello

 

There is nothing in a part where an existing drawing is stored. You can find an existing drawing if, for instance the drawing file is in the same (or another known) folder and the filename is the same as part or something rule based.

If the drawing is in the same folder and file name is the same, then you can try this one:

(It's untested, so there can be some bugs.)

Sub main
	
'Define the open document
Dim openDoc As Document
openDoc = ThisDoc.Document


'path from current file
oFolder = ThisDoc.WorkspacePath() & "\CNC FILES"

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

'Look at all of the files referenced in the open document
Dim docFile As Document
For Each docFile In openDoc.AllReferencedDocuments                
	If docFile.DocumentType=DocumentTypeEnum.kPartDocumentObject Then
		'file name without extension
		shortname = System.IO.Path.GetFileNameWithoutExtension(docFile)
		
		ExportIGES(docFile, oFolder, shortname)
		
		ExportSTEP(docFile, oFolder, shortname)
		
		ExportDrawingDXF(docFile, oFolder, shortname)
	End If
Next

End Sub

Private Sub ExportIGES(ByVal oDoc As PartDocument, ByVal sFileName As String, sFolder As String)
	' Get the IGES translator Add-In.
		Dim oIGESTranslator As TranslatorAddIn
		oIGESTranslator = ThisApplication.ApplicationAddIns.ItemById _ 
		("{90AF7F44-0C01-11D5-8E83-0010B541CD80}")
		Dim oContext As TranslationContext
		oContext = ThisApplication.TransientObjects.CreateTranslationContext
		Dim oOptions As NameValueMap
		oOptions = ThisApplication.TransientObjects.CreateNameValueMap
		If oIGESTranslator.HasSaveCopyAsOptions(docFile, oContext, oOptions) Then
		   ' Set geometry type for wireframe.
		   ' 0 = Surfaces, 1 = Solids, 2 = Wireframe
		   'oOptions.Value("GeometryType") = 1
		   ' To set other translator values:
		   ' oOptions.Value("SolidFaceType") = n
		   ' 0 = NURBS, 1 = Analytic
		   ' oOptions.Value("SurfaceType") = n
		   ' 0 = 143(Bounded), 1 = 144(Trimmed)
		oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
		Dim oData As DataMedium
		oData = ThisApplication.TransientObjects.CreateDataMedium
		oData.FileName =  sFolder & "\" & sFileName & ".igs"
		oIGESTranslator.SaveCopyAs(docFile, oContext, oOptions, oData)
		End If
End Sub

Sub ExportSTEP(ByVal oDoc As PartDocument, ByVal sFileName As String, sFolder As String)
	
	Dim oSTEPTranslator As TranslatorAddIn
	oSTEPTranslator = ThisApplication.ApplicationAddIns.ItemById( _
	"{90AF7F40-0C01-11D5-8E83-0010B541CD80}")
	Dim oContext As TranslationContext
	oContext = ThisApplication.TransientObjects.CreateTranslationContext
	Dim oOptions As NameValueMap
	oOptions = ThisApplication.TransientObjects.CreateNameValueMap
	If oSTEPTranslator.HasSaveCopyAsOptions(ThisApplication.ActiveDocument, oContext, oOptions) Then
		' Set application protocol.
		' 2 = AP 203 - Configuration Controlled Design
		' 3 = AP 214 - Automotive Design
		oOptions.Value("ApplicationProtocolType") = 3
		' Other options...
		'oOptions.Value("Author") = ""
		'oOptions.Value("Authorization") = ""
		'oOptions.Value("Description") = ""
		'oOptions.Value("Organization") = ""
		oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
		oDataMedium = ThisApplication.TransientObjects.CreateDataMedium

		oDataMedium.FileName =  sFolder & "\" & sFileName & ".stp"
		oSTEPTranslator.SaveCopyAs(docFile, oContext, oOptions, oData)
	End If
End Sub

Sub ExportDrawingDXF(ByVal oDoc As PartDocument,ByVal sFilename As String, ByVal sFolder As String)
	
	Dim sDrawName As String = sFolder & "\" & sFilename 
	Dim oDrawDoc As DrawingDocument
	If System.IO.File.Exists(sDrawName & ".idw") Then
		oDrawDoc = ThisApplication.Documents.Open(sDrawName & ".idw")
	ElseIf System.IO.File.Exists(sDrawName & ".dwg") Then
		oDrawDoc = ThisApplication.Documents.Open(sDrawName & ".dwg")
	Else
		'no drawing found
		Exit Sub
	End If
	
    Dim oDXFTranslator As TranslatorAddIn
    oDXFTranslator = ThisApplication.ApplicationAddIns.ItemById( _
	"{C24E3AC4-122E-11D5-8E91-0010B541CD80}")

    Dim oContext As TranslationContext
    oContext = ThisApplication.TransientObjects.CreateTranslationContext
    oContext.Type = kFileBrowseIOMechanism
    Dim oOptions As NameValueMap
    oOptions = ThisApplication.TransientObjects.CreateNameValueMap
    Dim oDataMedium As DataMedium
    oDataMedium = ThisApplication.TransientObjects.CreateDataMedium
    If oDXFTranslator.HasSaveCopyAsOptions(oDocument, oContext, oOptions) Then
        Dim strIniFile As String
        strIniFile = "C:\tempDXFOut.ini"
        oOptions.Value("Export_Acad_IniFile") = strIniFile
    End If
    oDataMedium.FileName = sFolder & "\" & sFilename & ".dxf"

    Call oDXFTranslator.SaveCopyAs(oDocument, oContext, oOptions, oDataMedium)
	
End Sub





 


R. Krieg
RKW Solutions
www.rkw-solutions.com
0 Likes
Message 3 of 48

dschulteHR4D5
Advocate
Advocate

Sorry for the late reply, will try this tonight when i get back at work. But yes I normally make the drawings off the part first, print, then save, and then depending on our workflow some go out and some we do in house. So im trying to sort of automate it to where, if i need a STP of the part, i also need a DXF of the print, so if i could do both at once that would be a win. Same thing with the assembly, ill have the whole finished assembly, say 50 different parts, we might make 10 of them, other 10 are purchased, 30 go out to another shop to get finished. So if i could hide everything except those 30, and then just run the rule and be done with it, it would save a tremendous amount of time clicking 5,000 times opening different parts, prints, save as, save as etc etc

0 Likes
Message 4 of 48

WCrihfield
Mentor
Mentor

So...you never need to export all three formats from the same model file, right?  And you only want this routine to work on a select set of components (or referenced documents), right?  Do you want to use component 'Visibility' and 'DesignViewRepresentations', or do you want to use component Suppression (Link1, Link2, Link3) and LevelOfDetailRepresentations (pre-2022) or ModelStates (2022)?  If you will be using component Visible or Suppressd as the main means of identifying which ones to work with, then the code needs to know which formats you want those components that remain visible or un-suppressed to be exported as, if not all 3.  Maybe a single question that prompts the user each time the main code starts, asking you which format's to export the visible/un-suppressed components as?  If we do something like that, we would then have to change up our loop to looking at components, instead of referenced documents.    Or maybe you would want to use an iProperty to identify/differentiate which ones to export one way, or the other?  If you do it that way, then we could continue to loop the referenced documents, which would likely be faster, easier, and more efficient.  Whichever way you plan on identifying which ones to export in which ways, the main loop in the code would have to change so that if the component (or document) is identified as 'in-house', then it should only get exported as an IGES file, while those that are identified as 'purchased' or 'outsourced' should be exported as STEP file and its drawing as DXF, right?  You will likely have to inform us of these details before we can properly fix the code to suit your exact needs. 

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 5 of 48

dschulteHR4D5
Advocate
Advocate

That is correct, typically i dont need all 3, normally it would be something like, i have all the part models within the assembly, drawings for each part unless its a purchased component. Then normally the iges ones we use in house and the step files are the ones i need to make the drawing also a dxf.

 

My idea was to look at the master assembly and turn the visibility off to the components i need. I'm still newer to finding my workflow on how i do things, but as of now thats how i have done it is to have the master assembly, hide the things i dont need, then open each one at a time, drawings are already made at this point, and then click, save as, open drawing, save as, close, close, open the next, repeat. 

 

I do it that way i guess so as i go through the parts i need i can see which ones i need to do yet, so after i transfer to step/dxf i just hide it and go to the next. 

 

I have thought about adding something to the description but havent put too much thought into it yet. I like the idea of a prompt tho, but i could also have two separate rules, the current one i have for IGS specifically to save as IGS, only issue right now is i would like to get the rule to only tag visible components in the assembly and sub assemblies. I think if i could get the IGS rule to do this, then could transfer that to the STP rule, which would be the same thing, only tag visible components, but also find the reference drawing and also save a copy of that to a DXF. I guess initially, i like playing around with the code myself even though alot of the time i am guessing to get it to work, but if for now i could get the original rule to only tag visible parts i would have a good start. Also to be able to identify parts within a sub assembly, like i mentioned i was having issues with it saving a whole subassembly of say 3 parts constrained together as an iges, whereas i needed all 3 of those individually as an iges not the whole thing in one file.

0 Likes
Message 6 of 48

WCrihfield
Mentor
Mentor

OK.  Well here is an example of an iLogic rule that will loop through all components in every level of the assembly, check if the component is Visible, check if it is a Part, and export those that past those tests to IGES file format.  When looping through the components to export, you have to keep track of which source documents you have already processed, so you don't attempt to export the same one multiple times, when there may be multiple components representing that same document throughout the assembly's structure, so I've incorporated a List(Of PartDocument) object variable to help with that part of the task.  I have not tested this, because I generally don't have any need to export IGES files, and usually export files to the same location as the original files.

 

Sub Main
	If ThisDoc.Document.DocumentType <> DocumentTypeEnum.kAssemblyDocumentObject Then
		MsgBox("An Assembly Document must be active for this rule to work. Exiting.", vbCritical, "")
		Exit Sub
	End If
	Dim oADoc As AssemblyDocument = ThisDoc.Document
	oOccs = oADoc.ComponentDefinition.Occurrences
	IterateComponentsRecursively(oOccs)
	MsgBox("All Exports Complete.", vbInformation, "")
End Sub

Dim oProcessedDocs As List(Of PartDocument)

Sub IterateComponentsRecursively(oComps As ComponentOccurrences)
	If IsNothing(oComps) Then Exit Sub
	For Each oComp As ComponentOccurrence In oComps
		If oComp.Visible = False Then Continue For
		If oComp.DefinitionDocumentType = DocumentTypeEnum.kAssemblyDocumentObject Then
			'it is a sub-assembly, so run it back through this same Sub again (recursive processing)
			IterateComponentsRecursively(oComp.Definition.Occurrences)
		End If
		If oComp.DefinitionDocumentType <> DocumentTypeEnum.kPartDocumentObject Then Continue For
		If Not TypeOf oComp.Definition Is PartComponentDefinition Then Continue For
		Dim oPDoc As PartDocument = oComp.ReferencedDocumentDescriptor.ReferencedDocument
		If IsNothing(oProcessedDocs) Then oProcessedDocs = New List(Of PartDocument)
		If oProcessedDocs.Contains(oPDoc) Then Continue For
		oFolder = ThisApplication.DesignProjectManager.ActiveDesignProject.WorkspacePath
		oFolder = oFolder & "\CNC FILES"
		If Not System.IO.Directory.Exists(oFolder) Then
			System.IO.Directory.CreateDirectory(oFolder)
		End If
		oFileName = System.IO.Path.GetFileNameWithoutExtension(oPDoc.FullFileName)
		oIGESFullFileName = oFolder & "\" & oFileName & ".igs"
		'run other custom Sub routine here that does main work of rule
		ExportToIGES(oPDoc, oIGESFullFileName)
		'check if it represents an assembly (sub-assembly)
	Next
End Sub

Sub ExportToIGES(oPartDoc As PartDocument, oNewFullFileName As String)
	If IsNothing(oPartDoc) Or oNewFullFileName = "" Then Exit Sub
	Dim oIGES As TranslatorAddIn = ThisApplication.ApplicationAddIns.ItemById( _
	"{90AF7F44-0C01-11D5-8E83-0010B541CD80}")
	If IsNothing(oIGES) Then Exit Sub
	Dim oTO As TransientObjects = ThisApplication.TransientObjects
	oContext = oTO.CreateTranslationContext
	oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
	oOptions = oTO.CreateNameValueMap
	oDataMedium = oTO.CreateDataMedium
	'check to see if the exported file already exists, to avoid overwriting it
	If System.IO.File.Exists(oNewFullFileName) Then
		oAns = MsgBox("An IGES file with this name already exists." & vbCrLf &
		"Do you want to overwrite it with this new one?",vbYesNo + vbQuestion + vbDefaultButton2, "IGES FILE EXISTS")
		If oAnswer = vbNo Then Exit Sub
	End If
	oDataMedium.FileName = oNewFullFileName
	If oIGES.HasSaveCopyAsOptions(oPartDoc, oContext, oOptions) Then
		'oOptions.Value("GeometryType") = 1 '0=Surfaces, 1=Solids, 2=WireFrame
		'oOptions.Value("SolidFaceType") = '0=Nurbs, 1=Analytic
		'oOptions.Value("SurfaceType") =  '0=143(Bounded), 1=144(Trimmed)
		Try
			oIGES.SaveCopyAs(oPartDoc, oContext, oOptions, oDataMedium)
			If IsNothing(oProcessedDocs) Then oProcessedDocs = New List(Of PartDocument)
			oProcessedDocs.Add(oPartDoc)
		Catch oEx As Exception
			MsgBox(oEx.Message & vbCrLf & oEx.StackTrace, vbExclamation, "")
			'Logger.Error(oEx.Message & vbCrLf & oEx.StackTrace)
		End Try
	End If
End Sub

 

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 7 of 48

dschulteHR4D5
Advocate
Advocate

Hello there again, sorry for the long delay. Have been waiting on my workflow to bring this back to surface, until i needed to use the code... Have been busy with other things as of late. But, i did try this last code you posted and so far so good, the only thing i dont have yet nailed down is the design view representations, i am starting to understand this more as i work with it but basically what i found, the main assembly file i use this code on, the design view has to match each sub assembly within the assembly. So if i hide the things i dont want on the main final assembly, they will export to iges, so each individual sub assembly model tree has to be hidden in order for this to work. And this is completely fine, i usually thumb through the assemblies anyways and verify components for the build list i make for the project. 

 

I am still to try out anything to translate to STP and pull a reference drawing and export that as well. Soon i will try that out and comb through that. But so far so good, thank you very much for your help so far. Much appreciated, your code is also really nice and well put together btw.

0 Likes
Message 8 of 48

dschulteHR4D5
Advocate
Advocate

Ideally, with this last code you posted, could you make a version of this code but instead of CNC FILES folder, would it be possible to have the one code, to translate to step in the same manner as the iges code to a specified folder, and pull reference drawing of each, translate that print to dxf and put it in a seperate specified folder? They could go in one folder but if possible i would like to keep them seperated when i send them out. Looking back n forth between the first couple codes this last one looks a little different so not sure if theres much change to add these steps to the current code or not. I cant tell if the first code you posted would do this.

0 Likes
Message 9 of 48

dschulteHR4D5
Advocate
Advocate
Okay so i did try the first code and came up with this error.

Error in rule: export, in document: 29242 RIVNUT ASM.iam

Unable to cast COM object of type 'System.__ComObject' to class type 'System.String'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

This is the first code you posted with iges stp and dxf in it. The last one you posted with just the iges works perfectly.
0 Likes
Message 10 of 48

WCrihfield
Mentor
Mentor
Accepted solution

Hi @dschulteHR4D5.  I may still not be 100% clear on all the folder location requirements, but I made an attempt to create a similar code to the last one I posted, but this one being for exporting the referenced Part document behind every 'Visible' component out as a STEP file, then attempt to get its Drawing and export that to DXF.  I'm not sure if you prefer the TranslatorAddIn route for exporting the DXF's or if you prefer using the DataIO.WriteDataToFile() method, but my example is using the TranslatorAddIn route.  The only option you can specify when exporting using the TranslatorAddIn route is the .ini file for it to use, so you may need to change that file location within the code before you try to use it.  It is currently pointing to somewhat of a default location for that .ini file.  Also, the way it is currently set-up, it is looking for the drawing documents in the same location and same file name as the model file, but with the .idw file extension, so if that is not how you have your drawings set-up, that will not work.

Here is what I have so far (untested):

Sub Main
	If ThisDoc.Document.DocumentType <> DocumentTypeEnum.kAssemblyDocumentObject Then
		MsgBox("An Assembly Document must be active for this rule to work. Exiting.", vbCritical, "")
		Exit Sub
	End If
	Dim oADoc As AssemblyDocument = ThisDoc.Document
	
	Dim oWSPath As String = ThisApplication.DesignProjectManager.ActiveDesignProject.WorkspacePath
	oSTEPFilesFolder = oWSPath & "\STEP FILES"
	If Not System.IO.Directory.Exists(oSTEPFilesFolder) Then
		System.IO.Directory.CreateDirectory(oSTEPFilesFolder)
	End If
	oDXFFilesFolder = oWSPath & "\DXF FILES"
	If Not System.IO.Directory.Exists(oDXFFilesFolder) Then
		System.IO.Directory.CreateDirectory(oDXFFilesFolder)
	End If
	
	oOccs = oADoc.ComponentDefinition.Occurrences
	IterateComponentsRecursively(oOccs)
	MsgBox("All Exports Complete.", vbInformation, "")
End Sub

Dim oSTEPFilesFolder As String
Dim oDXFFilesFolder As String
Dim oProcessedDocs As List(Of PartDocument)

Sub IterateComponentsRecursively(oComps As ComponentOccurrences)
	If IsNothing(oComps) OrElse oComps.Count = 0 Then Exit Sub
	For Each oComp As ComponentOccurrence In oComps
		'only process Visible components
		If oComp.Visible = False Then Continue For
		'if it is Visible, and an Assembly, recursively process its components
		If oComp.DefinitionDocumentType = DocumentTypeEnum.kAssemblyDocumentObject Then
			IterateComponentsRecursively(oComp.Definition.Occurrences)
		End If
		'make sure it is a Part
		If oComp.DefinitionDocumentType <> DocumentTypeEnum.kPartDocumentObject Then Continue For
		If Not TypeOf oComp.Definition Is PartComponentDefinition Then Continue For
		Dim oPDoc As PartDocument = oComp.ReferencedDocumentDescriptor.ReferencedDocument
		If IsNothing(oProcessedDocs) Then oProcessedDocs = New List(Of PartDocument)
		'if we have already processed this referenced document, skip to next component
		If oProcessedDocs.Contains(oPDoc) Then Continue For
		Dim oFileName As String = System.IO.Path.GetFileNameWithoutExtension(oPDoc.FullFileName)
		Dim oSTEPFullFileName As String = oSTEPFilesFolder & "\" & oFileName & ".stp"
		'run other custom Sub routine here that does main work of rule
		ExportToSTEP(oPDoc, oSTEPFullFileName)
		Dim oDrawDoc As DrawingDocument = GetDrawing(oPDoc)
		If Not IsNothing(oDrawDoc) Then
			Dim oDXFFullFileName As String = oDXFFilesFolder & "\" & oFileName & ".dxf"
			ExportIDWtoDXF(oDrawDoc, oDXFFullFileName)
		End If
	Next
End Sub

Sub ExportToSTEP(oDoc As Document, oNewFileName As String)
	Dim oSTEP As TranslatorAddIn = ThisApplication.ApplicationAddIns.ItemById( _
	"{90AF7F40-0C01-11D5-8E83-0010B541CD80}")
	If IsNothing(oSTEP) Then
		MsgBox("STEP Translator Add-in not found.  Exiting.", vbCritical, "")
		'Logger.Debug("STEP Translator Add-in not found.")
		Exit Sub
	End If

	'create needed variables for translator
	oTO = ThisApplication.TransientObjects
	oContext = oTO.CreateTranslationContext
	oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
	oOptions = oTO.CreateNameValueMap
	oDataMedium = oTO.CreateDataMedium

	If System.IO.File.Exists(oNewFileName) Then
		oAns = MsgBox("A STEP file with this name already exists." & vbCrLf &
		"Do you want to overwrite it with this new one?",vbYesNo + vbQuestion + vbDefaultButton2, "STEP FILE EXISTS")
		If oAns = vbNo Then Exit Sub
	End If
	oDataMedium.FileName = oNewFileName

	If oSTEP.HasSaveCopyAsOptions(oDoc, oContext, oOptions) Then
		' Set application protocol.
		 ' 2 = AP 203 - Configuration Controlled Design
		 ' 3 = AP 214 - Automotive Design
		 'oOptions.Value("ApplicationProtocolType") = 3
		 'oOptions.Value("IncludeSketches") = True
		 'oOptions.Value("export_fit_tolerance") = .000393701  'minimum
		 'oOptions.Value("Author") = ThisApplication.GeneralOptions.UserName
		 'oOptions.Value("Authorization") = ""
		 'oOptions.Value("Description") = iProperties.Value("Summary", "Title")
		 'oOptions.Value("Organization") = iProperties.Value("Summary", "Company")
		Try
			 oSTEP.SaveCopyAs(oDoc, oContext, oOptions, oDataMedium)
		Catch
			MsgBox("Your attempt to export this document as a STEP file FAILED!", vbExclamation, "Export to STEP Error")
			'Logger.Error("Export to STEP failed.")
		End Try
	End If
End Sub

Function GetDrawing(oModelDoc As Document) As DrawingDocument
	'only works when drawing is in same place and has same file name as model.
	Dim oDrawingFile As String = System.IO.Path.ChangeExtension(oModelDoc.FullFileName, ".idw")
	If System.IO.File.Exists(oDrawingFile) Then
		Dim oDrawingDoc As DrawingDocument = ThisApplication.Documents.Open(oDrawingFile, False)
		Return oDrawingDoc
	End If
	Return Nothing
End Function

Sub ExportIDWtoDXF(oDrawing As DrawingDocument, oNewFullFileName As String)
	Dim oDXF As TranslatorAddIn = ThisApplication.ApplicationAddIns.ItemById( _
	"{C24E3AC4-122E-11D5-8E91-0010B541CD80}")
	If IsNothing(oDXF) Then
		MsgBox("DXF Translator Add-in not found.  Exiting.", vbCritical, "")
		'Logger.Debug("DXF Translator Add-in not found.")
		Exit Sub
	End If
	
	'create needed variables for translator
	oTO = ThisApplication.TransientObjects
	oContext = oTO.CreateTranslationContext
	oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
	oOptions = oTO.CreateNameValueMap
	oDataMedium = oTO.CreateDataMedium
	
	If System.IO.File.Exists(oNewFileName) Then
		oAns = MsgBox("A DXF file with this name already exists." & vbCrLf &
		"Do you want to overwrite it with this new one?", vbYesNo + vbQuestion + vbDefaultButton2, "DXF FILE EXISTS")
		If oAns = vbNo Then Exit Sub
	End If
	oDataMedium.FileName = oNewFileName
	'<<<< CHANGE THIS IF NEEDED >>>>
	Dim oINI_File As String = "C:\Users\Public\Documents\Autodesk\Inventor 2022\Design Data\DWG-DXF\exportdxf.ini"
	If Not System.IO.File.Exists(oINI_File) Then
		MsgBox("Couldn't find this INI file:  " & oINI_File & ".  Exiting.", vbExclamation, "")
		Exit Sub
	End If
	If oDXF.HasSaveCopyAsOptions(oDrawing, oContext, oOptions) Then
		oOptions.Value("Export_Acad_IniFile") = oINI_File
	End If
	Try
		oDXF.SaveCopyAs(oDrawing, oContext, oOptions, oDataMedium)
	Catch oEx As Exception
		MsgBox("SaveCopyAs DXF failed." & vbCrLf & _
		oEx.Message & vbCrLf & oEx.StackTrace, vbExclamation, "")
		'Logger.Error(oEx.Message & vbCrLf & oEx.StackTrace)
	End Try
End Sub

 

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 11 of 48

WCrihfield
Mentor
Mentor

Looks like I forgot a couple lines of code that might help with clean up after the task is finished.  Since this code has to open a bunch of DrawingDocuments, in order to export them to DXF, it is leaving all those open in the background unnecessarily.  There are a few things we can do to fix that situation, that I forgot to incorporate into the code.  At the end of the ExportIDWtoDXF Sub, we could add a line like the following:

oDrawing.Close(True) 'True = SkipSave

or

oDrawing.ReleaseReference

Then, if you use the ReleaseReference route, you can also use the following line of code at the end of the Sub Main code, as part of the clean up.

ThisApplication.Documents.CloseAll(True)

True here means only close all of the 'unreferenced' documents.  When you open documents using the Visible = False setting, then they can be dismissed using the ReleaseReference method, and cleared from memory using the CloseAll(True) method.  But if opened visibly, then using the regular Close method is best.

 

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 12 of 48

dschulteHR4D5
Advocate
Advocate

Okay so back at it now, finally have a job we are sending out to try this with properly.. So using this code you posted, i added the couple lines like you mentioned (i think in the right spots) and i get this error

Autodesk Inventor Professional 2021 5_24_2022 4_05_47 AM.png

Currently my files are in different folders, Components(where the ipt and iam files are), and Drawings(all drawings made go in this folder) are separated for a few reasons, for one to somewhat cleanup the files in the folder, and to also be able to manage subfolders within the drawings, might have a separate folder in there for a specific customer, or saved as a different type for a customer that needs it saved as something else. 

 

As far as the documents, it is saving as a STP properly, whatever is hidden isn't saving, so thats good. Just gotta try and get the next part, idw to dxf and i think i would be set. 

 

I did take a couple idw files and save them in the same folder as the IPT but didn't seem to translate over to saving as a dxf.

 

Thanks again for you help, this code i can see easily saving hours of work over time. Truly appreciate your help with this

 

0 Likes
Message 13 of 48

dschulteHR4D5
Advocate
Advocate
this is the rule, also i noticed, it seems to be cycling over the parts and saying there is a part already with the same name asking if i want to save new, which there wasn't before, so im wondering if its saving as a stp then somewhere in the code cycling back through that part?

Sub Main
If ThisDoc.Document.DocumentType <> DocumentTypeEnum.kAssemblyDocumentObject Then
MsgBox("An Assembly Document must be active for this rule to work. Exiting.", vbCritical, "")
Exit Sub
End If
Dim oADoc As AssemblyDocument = ThisDoc.Document

Dim oWSPath As String = ThisApplication.DesignProjectManager.ActiveDesignProject.WorkspacePath
oSTEPFilesFolder = oWSPath & "\STEP FILES"
If Not System.IO.Directory.Exists(oSTEPFilesFolder) Then
System.IO.Directory.CreateDirectory(oSTEPFilesFolder)
End If
oDXFFilesFolder = oWSPath & "\DXF FILES"
If Not System.IO.Directory.Exists(oDXFFilesFolder) Then
System.IO.Directory.CreateDirectory(oDXFFilesFolder)
End If

oOccs = oADoc.ComponentDefinition.Occurrences
IterateComponentsRecursively(oOccs)
MsgBox("All Exports Complete.", vbInformation, "")
ThisApplication.Documents.CloseAll(True)
End Sub

Dim oSTEPFilesFolder As String
Dim oDXFFilesFolder As String
Dim oProcessedDocs As List(Of PartDocument)

Sub IterateComponentsRecursively(oComps As ComponentOccurrences)
If IsNothing(oComps) OrElse oComps.Count = 0 Then Exit Sub
For Each oComp As ComponentOccurrence In oComps
'only process Visible components
If oComp.Visible = False Then Continue For
'if it is Visible, and an Assembly, recursively process its components
If oComp.DefinitionDocumentType = DocumentTypeEnum.kAssemblyDocumentObject Then
IterateComponentsRecursively(oComp.Definition.Occurrences)
End If
'make sure it is a Part
If oComp.DefinitionDocumentType <> DocumentTypeEnum.kPartDocumentObject Then Continue For
If Not TypeOf oComp.Definition Is PartComponentDefinition Then Continue For
Dim oPDoc As PartDocument = oComp.ReferencedDocumentDescriptor.ReferencedDocument
If IsNothing(oProcessedDocs) Then oProcessedDocs = New List(Of PartDocument)
'if we have already processed this referenced document, skip to next component
If oProcessedDocs.Contains(oPDoc) Then Continue For
Dim oFileName As String = System.IO.Path.GetFileNameWithoutExtension(oPDoc.FullFileName)
Dim oSTEPFullFileName As String = oSTEPFilesFolder & "\" & oFileName & ".stp"
'run other custom Sub routine here that does main work of rule
ExportToSTEP(oPDoc, oSTEPFullFileName)
Dim oDrawDoc As DrawingDocument = GetDrawing(oPDoc)
If Not IsNothing(oDrawDoc) Then
Dim oDXFFullFileName As String = oDXFFilesFolder & "\" & oFileName & ".dxf"
ExportIDWtoDXF(oDrawDoc, oDXFFullFileName)
End If
Next
End Sub

Sub ExportToSTEP(oDoc As Document, oNewFileName As String)
Dim oSTEP As TranslatorAddIn = ThisApplication.ApplicationAddIns.ItemById( _
"{90AF7F40-0C01-11D5-8E83-0010B541CD80}")
If IsNothing(oSTEP) Then
MsgBox("STEP Translator Add-in not found. Exiting.", vbCritical, "")
'Logger.Debug("STEP Translator Add-in not found.")
Exit Sub
End If

'create needed variables for translator
oTO = ThisApplication.TransientObjects
oContext = oTO.CreateTranslationContext
oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
oOptions = oTO.CreateNameValueMap
oDataMedium = oTO.CreateDataMedium

If System.IO.File.Exists(oNewFileName) Then
oAns = MsgBox("A STEP file with this name already exists." & vbCrLf &
"Do you want to overwrite it with this new one?",vbYesNo + vbQuestion + vbDefaultButton2, "STEP FILE EXISTS")
If oAns = vbNo Then Exit Sub
End If
oDataMedium.FileName = oNewFileName

If oSTEP.HasSaveCopyAsOptions(oDoc, oContext, oOptions) Then
' Set application protocol.
' 2 = AP 203 - Configuration Controlled Design
' 3 = AP 214 - Automotive Design
'oOptions.Value("ApplicationProtocolType") = 3
'oOptions.Value("IncludeSketches") = True
'oOptions.Value("export_fit_tolerance") = .000393701 'minimum
'oOptions.Value("Author") = ThisApplication.GeneralOptions.UserName
'oOptions.Value("Authorization") = ""
'oOptions.Value("Description") = iProperties.Value("Summary", "Title")
'oOptions.Value("Organization") = iProperties.Value("Summary", "Company")
Try
oSTEP.SaveCopyAs(oDoc, oContext, oOptions, oDataMedium)
Catch
MsgBox("Your attempt to export this document as a STEP file FAILED!", vbExclamation, "Export to STEP Error")
'Logger.Error("Export to STEP failed.")
End Try
End If
End Sub

Function GetDrawing(oModelDoc As Document) As DrawingDocument
'only works when drawing is in same place and has same file name as model.
Dim oDrawingFile As String = System.IO.Path.ChangeExtension(oModelDoc.FullFileName, ".idw")
If System.IO.File.Exists(oDrawingFile) Then
Dim oDrawingDoc As DrawingDocument = ThisApplication.Documents.Open(oDrawingFile, False)
Return oDrawingDoc
End If
Return Nothing
End Function

Sub ExportIDWtoDXF(oDrawing As DrawingDocument, oNewFullFileName As String)
Dim oDXF As TranslatorAddIn = ThisApplication.ApplicationAddIns.ItemById( _
"{C24E3AC4-122E-11D5-8E91-0010B541CD80}")
If IsNothing(oDXF) Then
MsgBox("DXF Translator Add-in not found. Exiting.", vbCritical, "")
'Logger.Debug("DXF Translator Add-in not found.")
Exit Sub
End If

'create needed variables for translator
oTO = ThisApplication.TransientObjects
oContext = oTO.CreateTranslationContext
oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
oOptions = oTO.CreateNameValueMap
oDataMedium = oTO.CreateDataMedium

If System.IO.File.Exists(oNewFileName) Then
oAns = MsgBox("A DXF file with this name already exists." & vbCrLf &
"Do you want to overwrite it with this new one?", vbYesNo + vbQuestion + vbDefaultButton2, "DXF FILE EXISTS")
If oAns = vbNo Then Exit Sub
End If
oDataMedium.FileName = oNewFileName
'<<<< CHANGE THIS IF NEEDED >>>>
Dim oINI_File As String = "C:\Users\Public\Documents\Autodesk\Inventor 2021\Design Data\DWG-DXF\exportdxf.ini"
If Not System.IO.File.Exists(oINI_File) Then
MsgBox("Couldn't find this INI file: " & oINI_File & ". Exiting.", vbExclamation, "")
Exit Sub
End If
If oDXF.HasSaveCopyAsOptions(oDrawing, oContext, oOptions) Then
oOptions.Value("Export_Acad_IniFile") = oINI_File
End If
Try
oDXF.SaveCopyAs(oDrawing, oContext, oOptions, oDataMedium)
Catch oEx As Exception
MsgBox("SaveCopyAs DXF failed." & vbCrLf & _
oEx.Message & vbCrLf & oEx.StackTrace, vbExclamation, "")
'Logger.Error(oEx.Message & vbCrLf & oEx.StackTrace)
oDrawing.ReleaseReference
End Try
End Sub
0 Likes
Message 14 of 48

WCrihfield
Mentor
Mentor

Hi @dschulteHR4D5.  If you normally store your drawing files in a different folder than your model files, then you will need to change the 'GetDrawing' function to reflect that.  Currently it is only looking for the drawing in the same folder as the part file, and with the same exact full file name, except for the file extension.  You could have it look in both places too, if you wanted.  When you change it, you could either just 'hard code' a folder location into it, or you could have it use a shared variable (sort of like how we did with the 'oSTEPFilesFolder ' variable), or you could add another 'input variable' to the Function's definition line for a String that will represent the folder where it should start searching for the drawing file.

 

As for the 'ExportIDWtoDXF' Sub routine failing...It seems to be failing right at the end for some reason.  Do you have the INI file set-up the way you want it, and is it pointing to the correct file?  Are you only encountering that 'save as' error message when trying to save over an existing file with the same name, or is there any other noticeable similarities about the instances that fail that way?  Maybe we need to include the full file name it was trying to save as, within the error message, to help us better understand where the error is happening, and on which specific files.

 

You may be seeing that message about encountering the same document again, because we are looping through components in an assembly, instead of referenced documents.  Because it is possible for multiple components within the structure of an assembly to be referencing the same source model document, that's why I'm using the List(Of PartDocument), to keep track of which documents we have already encountered / worked on.  If we were looping through all the referenced documents within the main assembly, we wouldn't need the List or that check in there, but then we couldn't check component visibility/suppression.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 15 of 48

dschulteHR4D5
Advocate
Advocate

Yeah i am trying to look and see where to set the folder, its always in the root workspace folder where the IPJ is, under DRAWINGS, so im going to try and play with that part, not sure what to put in for code to tell it to look in that folder.

 

And i have had some time to experiment, it asks to save over when there is more than 1 visible with the same name, and only then will it ask to save over. 

 

As far as the idw to dxf, i have all of the drawings in the same folder as the the part is in, and still get the error. And yeah i copied the link to the ini file i have unless mine is looking somewhere else for it, so for some reason somewhere its not saving as a dxf.. not sure if its the code or file location.

0 Likes
Message 16 of 48

WCrihfield
Mentor
Mentor

Hi @dschulteHR4D5.  I'm not sure if this is similar to what you were looking for as the modified version of the 'GetDrawing' function, but this is what I had in mind, based on what you said in your last post.

Function GetDrawing(oModelDoc As Document) As DrawingDocument
	oWSPath = ThisApplication.DesignProjectManager.ActiveDesignProject.WorkspacePath
	Dim oDrawingsFolder As String = oWSPath & "\DRAWINGS"
	oFileName = System.IO.Path.GetFileNameWithoutExtension(oModelDoc.FullFileName)
	Dim oDrawingFile As String = oDrawingsFolder & "\" & oFileName & ".idw"
	If System.IO.File.Exists(oDrawingFile) Then
		Dim oDrawingDoc As DrawingDocument = ThisApplication.Documents.Open(oDrawingFile, False)
		Return oDrawingDoc
	Else
'		MsgBox("A Drawing File Named:" & vbCrLf & oDrawingFile & vbCrLf & _
'		"Could not be found.", vbExclamation, "")
	End If
	Return Nothing
End Function

Then, although I'm still not sure what may be going wrong with the 'ExportIDWtoDXF' Sub routine, I modified the Try...Catch block and its feedback message a bit to include a lot more information, including the full file name of the drawing and the full file name of the proposed dxf file it was trying to create.

	Try
		oDXF.SaveCopyAs(oDrawing, oContext, oOptions, oDataMedium)
	Catch oEx As Exception
		MsgBox("SaveCopyAs method of the ExportIDWtoDXF Sub routine failed." & vbCrLf & _
		"While trying to export the following Drawing file:  " & vbCrLf & _
		oDrawing.FullFileName & vbCrLf & _
		"as the following dxf file:  " & vbCrLf & _
		oNewFileName & vbCrLf & _
		oEx.Message & vbCrLf & oEx.StackTrace, vbExclamation, "")
		'Logger.Error(oEx.Message & vbCrLf & oEx.StackTrace)
		oDrawing.ReleaseReference
	End Try

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 17 of 48

dschulteHR4D5
Advocate
Advocate

so i made the changes in your last reply, and getting this now. 

Screenshot 2022-05-25 192415.png

 im trying to play around and edit things to get something to work but my experience with ilogic is minimal so im not really getting anywhere, but im trying lol 

 

i copied a different code, although a bit different, one of your other codes i seen you posted on a different thread, that saves a copy of an idw as dxf, this works just fine when i have an open idw, so i can save a copy as a dxf, so not sure if its having problems referencing the file or the save as settings or what

0 Likes
Message 18 of 48

WCrihfield
Mentor
Mentor

I don't know why I didn't see this sooner.  After looking at the contents of that very informational error message, then looking back at my updated code for what was supposed to be in that error message, I noticed that it is not showing the 'new' full file name that it was trying to save the DXF file to.  Then I looked at the variable I had in that position within the error message (oNewFileName).  Then I looked back at your previous post which contained the whole code, and attempted to follow that variable up through that Sub routine from that point.  I then saw that we were using a slightly different variable name for this within the definition line of that Sub routine as follows:

Sub ExportIDWtoDXF(oDrawing As DrawingDocument, oNewFullFileName As String)

For some reason, we were using the oNewFileName variable after that point, instead of the oNewFullFileName variable.  You either need to use the 'Search and Replace' tool at the top of your iLogic rule editor dialog to search for the oNewFileName variable, and replace it with the oNewFullFileName variable, or the other way around, so that all the references within that Sub routine are using the same variable for this information.  This will probably fix the issue.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 19 of 48

dschulteHR4D5
Advocate
Advocate

Dang!! okay so i changed all the oNewFileName to the oNewFullFileName and it worked, actually so far, it works pretty **** perfectly, testing it on a make**** assembly i made up quick.. BUT, for some reason it is saving each DXF into a rar file, for some reason. 

0 Likes
Message 20 of 48

dschulteHR4D5
Advocate
Advocate

okay so i messed with the default dxf ini settings, i think it was set to a default state to save it as the rar file, so now it is saving, but i dont have a viewer for the dxf file so im not sure if its proper or not, the files aren't showing the file extension so i gotta look at getting a viewer to make sure its proper, right now im at home messing with ilogic so im not at my default workstation so not sure if it will save different at work based on the ini settings

0 Likes