Another export to dxf from flat pattern with errors. (dxf is empty )

Another export to dxf from flat pattern with errors. (dxf is empty )

K.TRYFONIDIS
Advocate Advocate
2,800 Views
15 Replies
Message 1 of 16

Another export to dxf from flat pattern with errors. (dxf is empty )

K.TRYFONIDIS
Advocate
Advocate

Hello everyone,

 

I have combined several scripts in here and have read most of the scripts regarding the flat pattern.

 

My goal was to create a script so that it can export 2 identical dxfs to two separate defined by me, folder locations.

 

In first place i wanted to export from the drawing environment the flat pattern in dxf but unfortunately it didn't worked out.

Then i made the script bellow which works very good in sheet metal enviroment except from the fact that the generated dxf,s are empty inside and i get an error message. See attached dxf.

Anyone has a clue why this is happening? Thanks a lot in advance.

This is what shows up when i open the dxf file.

kTRIFONIDIS_1-1643370149955.png

 

And this is what shows when i put it on autodesk viewer

kTRIFONIDIS_0-1643374119685.png

 

 

 

Sub Main()
	'query user
question = MessageBox.Show(" create DXF?", "attention",MessageBoxButtons.YesNo,MessageBoxIcon.Question)
'set condition based on answer
If question = vbYes Then
	
	
  ' Get the DXF translator Add-In.
path_and_nameDXF = ThisDoc.PathAndFileName(False)
Dim DXFAddIn As TranslatorAddIn
DXFAddIn = ThisApplication.ApplicationAddIns.ItemById("{C24E3AC4-122E-11D5-8E91-0010B541CD80}")
'Set a reference to the active document (the document to be published).
Dim oDocument As Document
oDocument = ThisApplication.ActiveDocument

Dim oContext As TranslationContext
oContext = ThisApplication.TransientObjects.CreateTranslationContext
oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism
' Create a NameValueMap object
Dim oOptions As NameValueMap
oOptions = ThisApplication.TransientObjects.CreateNameValueMap
' Create a DataMedium object
Dim oDataMedium3 As DataMedium
oDataMedium3 = ThisApplication.TransientObjects.CreateDataMedium

' Create a DataMedium object
Dim oDataMedium4 As DataMedium
oDataMedium4 = ThisApplication.TransientObjects.CreateDataMedium

If DXFAddIn.HasSaveCopyAsOptions(oDocument, oContext, oOptions) Then
Dim strIniFile As String
strIniFile = "C:\Work\DXF_EXPORT.ini"
oOptions.Value("Export_Acad_IniFile") = strIniFile
End If



    'Set the destination file name
    oDataMedium3.FileName = "C:\Users\KTrifonidisNyfan\Documents\NyfanDXF\" & (Left(ThisDoc.FileName(False), 11)) & ".DXF"
	oDataMedium4.FileName = "C:\Users\KTrifonidisNyfan\Documents\NyfanDXF2\" & (Left(ThisDoc.FileName(False), 11)) & ".DXF"
	
	On Error GoTo handleDXFLock

    'Publish document.
    Call DXFAddIn.SaveCopyAs(oDocument, oContext, oOptions, oDataMedium3)
	Call DXFAddIn.SaveCopyAs(oDocument, oContext, oOptions, oDataMedium4)
	
	
		'Show message box
MessageBox.Show("dxfs are ready at  C:\Users\KTrifonidisNyfan\Documents\NyfanDXF and C:\Users\KTrifonidisNyfan\Documents\NyfanDXF2 ", "success !")
	
	End If
	

	
Exit Sub


handleDXFLock:MessageBox.Show("can't create dxf", "sorry " & ThisApplication.GeneralOptions.UserName & "!")
Resume Next



End Sub

 

0 Likes
Accepted solutions (1)
2,801 Views
15 Replies
Replies (15)
Message 2 of 16

WCrihfield
Mentor
Mentor

Hi @K.TRYFONIDIS.  I'm not sure what all may be going on in that process for you, but if what you are after is a DXF of your sheet metal flat pattern, this may not be the best or most efficient route.  Have you considered using the DataIO object of the FlatPattern object itself to do this task?  Here is a link to a code I posted for a similar task the other day that you may like.  With a little alteration, you could probably use something similar to that.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 3 of 16

JelteDeJong
Mentor
Mentor
Accepted solution

You could try it like this:

Sub Main()
	Dim question = MessageBox.Show(" create DXF?", "attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
    'set condition based on answer
    If question = vbYes Then

        'Set the destination file name
        Dim FileName1 = "C:\Users\KTrifonidisNyfan\Documents\NyfanDXF\" & (Left(ThisDoc.FileName(False), 11)) & ".DXF"
        Dim FileName2 = "C:\Users\KTrifonidisNyfan\Documents\NyfanDXF2\" & (Left(ThisDoc.FileName(False), 11)) & ".DXF"

        Export(ThisDoc.Document, FileName1)
		Export(ThisDoc.Document, FileName2)

        'Show message box
        MessageBox.Show("dxfs are ready at  C:\Users\KTrifonidisNyfan\Documents\NyfanDXF and C:\Users\KTrifonidisNyfan\Documents\NyfanDXF2 ", "success !")

    End If

End Sub

Private Sub Export(doc As PartDocument, newFileName As String)
    Dim oCompDef As SheetMetalComponentDefinition = doc.ComponentDefinition
    If oCompDef.HasFlatPattern = False Then
        oCompDef.Unfold()
    Else
        oCompDef.FlatPattern.Edit()
    End If

    Dim sOut As String = "FLAT PATTERN DXF?AcadVersion=2000&OuterProfileLayer=IV_INTERIOR_PROFILES"
    oCompDef.DataIO.WriteDataToFile(sOut, newFileName)
    oCompDef.FlatPattern.ExitEdit()
End Sub

 With the sOut variable, it's possible to set all kinds of settings. (like line types on layers or not exporting them.) You can find those options in the help.

Jelte de Jong
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

EESignature


Blog: hjalte.nl - github.com

Message 4 of 16

K.TRYFONIDIS
Advocate
Advocate

Thank you very much for spending time to help me!

I only need to find those options now so i can hide bend lines e.t.c

What did you think was the problem before? is it the .Ini file?

 

Thanks again.

0 Likes
Message 5 of 16

WCrihfield
Mentor
Mentor

There was a link to the options within the post I provided a link to.  But here is the link again.

https://help.autodesk.com/view/INVNTOR/2022/ENU/?guid=GUID-451B918E-9374-442D-B9AE-31A8C83674B7 

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 6 of 16

K.TRYFONIDIS
Advocate
Advocate
Thanks @WCrihfield
0 Likes
Message 7 of 16

K.TRYFONIDIS
Advocate
Advocate

@JelteDeJong 

Your script works perfect but i am not familiar with private subs and I would like to put 2 lines of code for an error prompt message in case someone has the dxf open but i cant figure out 

where to put those two lines to work properly. Any ideas?  Thanks in advance.

On Error GoTo handleDXFLock

 

handleDXFLock:MessageBox.Show("message", "message 2" & ThisApplication.GeneralOptions.UserName & "!")

 

0 Likes
Message 8 of 16

JelteDeJong
Mentor
Mentor

I think you should avoid using functionslike:

On Error GoTo ....

and start using Try/Catch functions.

(more info on the site of Microsoft. "On Error Statement" and "Try/Catch"

 

This is also what I implemented in the updated function below. (I could not test the code my self. If it doesn't work, then let me know. Later I will be having more time to check it out)

Private Sub Export(doc As PartDocument, newFileName As String)
    Dim oCompDef As SheetMetalComponentDefinition = doc.ComponentDefinition
    If oCompDef.HasFlatPattern = False Then
        oCompDef.Unfold()
    Else
        oCompDef.FlatPattern.Edit()
    End If

    Dim sOut As String = "FLAT PATTERN DXF?AcadVersion=2000&OuterProfileLayer=IV_INTERIOR_PROFILES"
try
    oCompDef.DataIO.WriteDataToFile(sOut, newFileName)
catch ex as Exception
    MessageBox.Show("message", "message 2" & ThisApplication.GeneralOptions.UserName & "!")
end try
    oCompDef.FlatPattern.ExitEdit()

End Sub

 

Jelte de Jong
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

EESignature


Blog: hjalte.nl - github.com

Message 9 of 16

K.TRYFONIDIS
Advocate
Advocate

Thank you for the information.

Although i didn't provoke the error, the error message still shows.

i think it needs an " exit sub " somewhere.

 

kTRIFONIDIS_0-1643617336984.png

 

0 Likes
Message 10 of 16

WCrihfield
Mentor
Mentor

@K.TRYFONIDIS , @JelteDeJong 

Hi guys.  Just a tip.  As you can see in the example I posted at the link (within 'Message 2' above), if you use the DataIO of the FlatPattern object directly, instead of using the DataIO of the SheetMetalComponentDefinition, you do not have to enter into the Edit mode of the FlatPattern before you use it, and then you don't have to exit back out of Edit mode when your done with it.  It's just cleaner, and more efficient that way, because it's like I mentioned before, the FlatPattern is like its own ComponentDefinition.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 11 of 16

K.TRYFONIDIS
Advocate
Advocate

Hey @WCrihfield 

That is a good advice, thank you. 🙂

0 Likes
Message 12 of 16

JelteDeJong
Mentor
Mentor

I could only reproduce your problem once. After that, I could not reproduce errors anymore. But I got a general idea and it looks like an Inventor message and not so much an API exception that we can cath. We can check if the file is locked or read-only. If so we can inform the user and abort the save before we run into problems. Try the rule below.

It also incorporates the advice from @WCrihfield although there is still a unfold action if there is none FlatPattern. 

Sub Main()
    Dim question = MessageBox.Show(" create DXF?", "attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
    'set condition based on answer
    If question = vbYes Then

        'Set the destination file name
        Dim FileName1 = "C:\Users\KTrifonidisNyfan\Documents\NyfanDXF\" & (Left(ThisDoc.FileName(False), 11)) & ".DXF"
        Dim FileName2 = "C:\Users\KTrifonidisNyfan\Documents\NyfanDXF2\" & (Left(ThisDoc.FileName(False), 11)) & ".DXF"

        Export(ThisDoc.Document, FileName1)
        Export(ThisDoc.Document, FileName2)

        'Show message box
        MessageBox.Show("dxfs are ready at  C:\Users\KTrifonidisNyfan\Documents\NyfanDXF and C:\Users\KTrifonidisNyfan\Documents\NyfanDXF2 ", "success !")

    End If

End Sub

Private Sub Export(doc As PartDocument, newFileName As String)

    Dim fileInfo As New IO.FileInfo(newFileName)
    If (fileInfo.Exists) Then
        If (fileInfo.IsReadOnly) Then
            MessageBox.Show("Target file is readonly!")
            Return
        End If
        If (IsFileLocked(fileInfo)) Then
            MessageBox.Show("Target file is Locked!")
            Return
        End If
    End If

    Dim oCompDef As SheetMetalComponentDefinition = doc.ComponentDefinition
    Try
        If oCompDef.HasFlatPattern = False Then
            oCompDef.Unfold()
            oCompDef.FlatPattern.ExitEdit()
        End If
    Catch
        MessageBox.Show("Unable to create a FlatPattern")
    End Try

    Try
        Dim sOut As String = "FLAT PATTERN DXF?AcadVersion=2000&OuterProfileLayer=IV_INTERIOR_PROFILES"
        oCompDef.FlatPattern.DataIO.WriteDataToFile(sOut, newFileName)
    Catch ex As Exception
        MessageBox.Show("Unable to export the FlatPattern")
    End Try
End Sub

Public Function IsFileLocked(file As IO.FileInfo) As Boolean
    Dim stream = DirectCast(Nothing, IO.FileStream)
    Try
        stream = file.Open(IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.None)
    Catch Ex As Exception
        Return True
    Finally
        If stream IsNot Nothing Then
            stream.Close()
        End If
    End Try
    Return False
End Function

 

 

Jelte de Jong
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

EESignature


Blog: hjalte.nl - github.com

0 Likes
Message 13 of 16

TylerWarner33
Advocate
Advocate

@WCrihfield & @JelteDeJong is there a reason why the translator add-in is not used? I'm also trying to export to DXF for a sheet metal part & getting the empty/corrupted DXF file when using the translator add-in.

 

If using the DataIO.WriteDataToFile method like you showed above, is there a way to incorporate an existing '.ini' file into it or just use System.IO.File.ReadAllText() for the first parameter of DataIO.WriteDataToFile()?

Edit: New link to documentation: https://help.autodesk.com/view/INVNTOR/2025/ENU/?guid=WriteFlatPatternAsDXF_Sample

If this answered your question, click 'Accept Solution'.
If this was helpful, click 'Like'.

Tyler Warner

0 Likes
Message 14 of 16

WCrihfield
Mentor
Mentor

Hi @TylerWarner33.  This is just a logical assumption, but I don't think that using the TranslatorAddIn to export an entire PartDocument object out, and expecting to get only the flat pattern profile will work, because when I have a sheet metal part open, and manually try to use the File > Save As > Save Copy As route, or try to use the File > Export > CAD Format route, the DXF file type is not available in either 'Save as type' list.  DWG, DWF, and others are available though.

 

As far as I know, there is no 'simple/easy' way to 'use' an existing INI file in a way that will 'fill in' that Format String needed for the DataIO.WriteDataToFile method.  However, it does seem like I have seen some folks attempt (if not succeed) at creating a code based routine for 'extracting' the needed data from one of those INI files, and use that to piece together their Format String from that data.  I do not have a link to that discussion or I would share it here, so you may have to search the forum for it.  I don't recall it being that simple looking though, and may have included some XML code language interpretation.  It would be nice to have a custom Function like that though.

 

You may already be aware of this, but while in a sheet metal part, and in flat pattern edit mode, when you right-click on the top model browser node on the flat pattern side, then choose 'Edit Flat Pattern Definition' option from the right-click menu, you modify its orientation, punch reps, and flip bend angle reports.  And also in that same right-click menu is 'Save Copy As'.  At first, the Options button is greyed out, making folks thing that you can not specify any options.  However, if you follow through with specifying path, name, and clicking the Save button, that will open a whole new 'Flat Pattern DXF Export Options', where you can manually specify pretty much all of these settings, which are not found anywhere else, and even offers to save out the INI file (configuration) for you.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 15 of 16

TylerWarner33
Advocate
Advocate

Thanks @WCrihfield , you are correct, it doesn't seem like the part file can use the translator. I require the customization specified in a '.ini' file so DataIO.WriteDataToFile() doesn't work great in this case.

 

Apparently, putting the flat pattern on a drawing sheet & then using the translator does the trick. C# code sample shown below:

 

PartDocument partDocument = (PartDocument)_inventorApplication.ActiveDocument;

string dxfFileName = System.IO.Path.Combine(@"path\to\folder", System.IO.Path.GetFileNameWithoutExtension(partDocument.FullDocumentName) + $".dxf");
string iniFileName = @"path\to\file.ini";

SheetMetalComponentDefinition componentDefinition = (SheetMetalComponentDefinition)partDocument.ComponentDefinition;
if (componentDefinition.HasFlatPattern is false)
{
	componentDefinition.Unfold();
	componentDefinition.FlatPattern.ExitEdit();
}

DrawingDocument drawingDocument = (DrawingDocument)_inventorApplication.Documents.Add(DocumentTypeEnum.kDrawingDocumentObject, CreateVisible: true);
drawingDocument.UnitsOfMeasure.LengthUnits = partDocument.UnitsOfMeasure.LengthUnits;

Sheet sheet = drawingDocument.ActiveSheet; // drawingDocument.Sheets[1];

Point2d viewPosition = _inventorApplication.TransientGeometry.CreatePoint2d(sheet.Width / 2, sheet.Height / 2);

NameValueMap viewOptions = _inventorApplication.TransientObjects.CreateNameValueMap();
viewOptions.Add("SheetMetalFoldedModel", false);

DrawingView drawingView = sheet.DrawingViews.AddBaseView(
		(Inventor._Document)partDocument,
		viewPosition,
		1,
		ViewOrientationTypeEnum.kDefaultViewOrientation,
		DrawingViewStyleEnum.kHiddenLineDrawingViewStyle,
		AdditionalOptions: viewOptions
);

TranslatorAddIn translatorAddIn = (TranslatorAddIn)_inventorApplication.ApplicationAddIns.ItemById["{C24E3AC4-122E-11D5-8E91-0010B541CD80}"];
translatorAddIn?.Activate();
if (translatorAddIn is null || translatorAddIn.Activated is false)
{
	throw new Exception("Failed to activate DXF Translator Add-In.");
}

TranslationContext translationContext = _inventorApplication.TransientObjects.CreateTranslationContext();
translationContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

NameValueMap options = _inventorApplication.TransientObjects.CreateNameValueMap();
if (translatorAddIn.HasSaveCopyAsOptions[drawingDocument, translationContext, options])
{
	options.Value["Export_Acad_IniFile"] = iniFileName;
}

DataMedium dataMedium = _inventorApplication.TransientObjects.CreateDataMedium();
dataMedium.FileName = dxfFileName;

if (System.IO.File.Exists(dxfFileName))
{
	System.IO.File.Delete(dxfFileName);
}
translatorAddIn.SaveCopyAs(drawingDocument, translationContext, options, dataMedium);
			
drawingDocument.Close(true);

 

If this answered your question, click 'Accept Solution'.
If this was helpful, click 'Like'.

Tyler Warner

0 Likes
Message 16 of 16

WCrihfield
Mentor
Mentor

Yep, the flat pattern drawing view route is the other most popular route to go, and offers the ability to do some customization to the view, bend lines, and annotations before the export also.  I pretty much never use that route myself though, because most of my DXF exports are relatively simple, and do not have many 'custom' requirements.  By the way, at some point in the past, I had also looked into just exporting a single 'Sheet' object, using its DataIO, but DWF is the only export format available.  Also looked into exporting just a single DrawingView, using its DataIO, but it only works from 'Apprentice', and only for a 'Bitmap' type, and only when that is 'available'.  Just to be thorough. 😅

 

Edit:  The method for exporting DXF's that I use most are 'export face as DXF', and 'export sketch to DXF'.  The traditional way of exporting a face to DXF by code is to 'select' the face by code, then execute the command that is usually found in the right-click menu.  But I generally do not like doing selections and command executions from my rules, so I tend to favor the process of creating a temporary PlanarSketch on a face, projecting all its edges, then using its DataIO to export it to DXF, then 'UNDO' that transaction, to get rid of the temporary sketch.  No options can be specified either of those two ways, so it tends to use 'last used' settings for the export, which is usually just fine for me.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)