juki-hao
Mechanical
- Sep 4, 2023
- 7
Hi everyone,
I am trying to combine the VB code from these two Journals:
My purpose is to batch export from prt to dxf/dwg files, from folder to folder.
This is what it looks like:
I am trying to combine the VB code from these two Journals:
My purpose is to batch export from prt to dxf/dwg files, from folder to folder.
This is what it looks like:
Code:
'NXJournaling.com
'December 1, 2014
'
'export pdf's of all parts in the given folder.
'August 5, 2015
'update: fix for the "part scan error: file already exists" error
' Previous version was not closing assembly components correctly,
' this left the component file in NX memory. When the journal later
' attempted to open the part file to process its drawing sheets,
' the "file already exists" error would be thrown.
Option Strict Off
Imports System
Imports System.IO
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports NXOpen
Imports NXOpen.UF
Module all_parts_in_folder
Dim theSession As Session = Session.GetSession
Dim workPart As Part = theSession.Parts.Work
Dim displayPart As Part = theSession.Parts.Display
Dim initialPart As Part = theSession.Parts.Display
Dim myPdfExporter As New NXJ_PdfExporter()
Dim lw As ListingWindow = theSession.ListingWindow
Sub Main()
lw.Open()
Dim folderToProcess As String = PickFolder("folder of parts to process")
If IsNothing(folderToProcess) Then
'user pressed cancel
lw.WriteLine("pdf export canceled")
Return
End If
lw.WriteLine("Export PDF files")
lw.WriteLine("Start Time: " & CType(TimeOfDay(), String))
lw.WriteLine("")
lw.WriteLine("folder to process: " & folderToProcess)
lw.WriteLine("")
'pick export folder
myPdfExporter.PickExportFolder()
If IsNothing(myPdfExporter.OutputFolder) Then
'user pressed cancel
lw.WriteLine("pdf export canceled")
Return
End If
lw.WriteLine("Export folder: " & myPdfExporter.OutputFolder)
lw.WriteLine("")
processParts(folderToProcess, False)
lw.WriteLine("")
lw.WriteLine("Stop Time: " & CType(TimeOfDay(), String))
End Sub
Function PickFolder(ByVal prompt As String) As String
Dim strPickedFolder As String
lw.Open()
Try
Dim FolderBrowserDialog1 As New FolderBrowserDialog
' Change the .SelectedPath property to the default location
With FolderBrowserDialog1
' Desktop is the root folder in the dialog.
.RootFolder = Environment.SpecialFolder.Desktop
' Change the following line to default to a given path
.SelectedPath = "C:\"
' Prompt the user with a custom message.
.Description = prompt
If .ShowDialog = DialogResult.OK Then
' Display the selected folder if the user clicked on the OK button.
'msgbox(.SelectedPath)
strPickedFolder = .SelectedPath
Return strPickedFolder
Else
'user pressed "cancel", exit the journal
Return Nothing
End If
End With
Catch ex As NXException
lw.WriteLine("Pick folder error: " & ex.Message)
Return Nothing
End Try
End Function
Sub processParts(ByVal directoryPath As String, ByVal includeSubDirs As Boolean)
'Try
Dim nPartFiles As Integer = 0
Dim part1 As Part
Dim files() As String
If includeSubDirs Then
files = Directory.GetFiles(directoryPath, "*.prt", SearchOption.AllDirectories)
Else
files = Directory.GetFiles(directoryPath, "*.prt", SearchOption.TopDirectoryOnly)
End If
For Each fileName As String In files
nPartFiles += 1
lw.WriteLine(" " & nPartFiles & " " & Path.GetFileName(fileName))
If (IsNothing(initialPart)) OrElse (initialPart.FullPath <> fileName) Then
Try
part1 = theSession.Parts.OpenDisplay(fileName, Nothing)
Catch ex As NXException
lw.WriteLine("open error: " & ex.Message)
Catch ex2 As Exception
lw.WriteLine("exception: " & ex2.Message)
End Try
Else
'LW.WriteLine("initial part equals display part: " & initialPart.Equals(displayPart).ToString)
part1 = displayPart
End If
displayPart = theSession.Parts.Display
workPart = theSession.Parts.Display
'do something
'write your own subroutines and/or functions to process the part and call them from here
ExportPdfs()
'close file unless this file was initially open
If (IsNothing(initialPart)) OrElse (initialPart.FullPath <> fileName) Then
'part1.Save(BasePart.SaveComponents.True, BasePart.CloseAfterSave.True)
part1.Close(BasePart.CloseWholeTree.True, BasePart.CloseModified.UseResponses, Nothing)
part1 = Nothing
workPart = Nothing
displayPart = Nothing
End If
If Not IsNothing(initialPart) Then
Dim partLoadStatus1 As PartLoadStatus
Dim status1 As PartCollection.SdpsStatus
status1 = theSession.Parts.SetDisplay(initialPart, False, False, partLoadStatus1)
displayPart = theSession.Parts.Display
partLoadStatus1.Dispose()
theSession.Parts.SetWork(displayPart)
workPart = theSession.Parts.Work
End If
Next fileName
End Sub
Sub ExportPdfs()
lw.WriteLine(displayPart.FullPath)
myPdfExporter.Part = displayPart
'$ show confirmation dialog box on completion
myPdfExporter.ShowConfirmationDialog = False
Try
myPdfExporter.Commit()
Catch ex As Exception
'MessageBox.Show("Error:" & ControlChars.CrLf & ex.GetType.ToString & " : " & ex.Message, "PDF export error", MessageBoxButtons.OK, MessageBoxIcon.Error)
lw.WriteLine("Error: " & ex.Message)
Finally
lw.WriteLine("")
End Try
End Sub
Function PartIsOpen(ByVal filename As String) As Boolean
Dim openParts As New List(Of String)
For Each temp As Part In theSession.Parts
openParts.Add(temp.FullPath)
Next
If openParts.Contains(filename) Then
Return True
Else
Return False
End If
End Function
End Module
#Region "imports"
'** uncomment the imports statments if using this as a standalone class file
'Imports System
'Imports System.IO
'Imports System.Collections
'Imports System.Windows.Forms
'Imports System.Windows.Forms.MessageBox
'Imports NXOpen
'Imports NXOpen.UF
#End Region
'Information for adding this code to your project:
' if you are going to compile your code:
' add this class file to your project, create and use an instance of this class in your code
'
' If you intend to use this in a journal (no compilation required),
' make sure all of the imports statements above are present at the top of your journal file.
' Copy and paste all of the code below here to your journal file (paste it after your "End Module" statement).
' Create and use an instance of this class in your module.
' One of the limitations of a journal is that all the code must be in a single file.
Class NXJ_PdfExporter
#Region "information"
'NXJournaling.com
'Jeff Gesiakowski
'December 9, 2013
'
'NX 8.5
'class to export drawing sheets to pdf file
'
'Please send any bug reports and/or feature requests to: info@nxjournaling.com
'
'version 0.4 {beta}, initial public release
' special thanks to Mike H. and Ryan G.
'
'November 3, 2014
'update to version 0.6
' added a public Sort(yourSortFunction) method to sort the drawing sheet collection according to a custom supplied function.
'
'November 7, 2014
'Added public property: ExportSheetsIndividually and related code changes default value: False
'Changing this property to True will cause each sheet to be exported to an individual pdf file in the specified export folder.
'
'Added new public method: New(byval thePart as Part)
' allows you to specify the part to use at the time of the NXJ_PdfExporter object creation
'
'
'December 1, 2014
'update to version 1.0
'Added public property: SkipBlankSheets [Boolean] {read/write} default value: True
' If the drawing sheet contains no visible objects, it is not output to the pdf file.
' Checking the sheet for visible objects requires the sheet to be opened;
' display updating is suppressed while the check takes place.
'Bugfix:
' If the PickExportFolder method was used and the user pressed cancel, a later call to Commit would still execute and send the output to a temp folder.
' Now, if cancel is pressed on the folder browser dialog a boolean flag is set (_cancelOutput), which the other methods will check before executing.
'
'
'December 4, 2014
'update to version 1.0.1
'Made changes to .OutputPdfFileName property Set method: you can pass in the full path to the file (e.g. C:\temp\pdf-output\12345.dxf);
'or you can simply pass in the base file name for the pdf file (e.g. 12345 or 12345.dxf). The full path will be built based on the
'.OutputFolder property (default value - same folder as the part file, if an invalid folder path is specified it will default to the user's
'"Documents" folder).
'
'
'Public Properties:
' ExportSheetsIndividually [Boolean] {read/write} - flag indicating that the drawing sheets should be output to individual pdf files.
' cannot be used if ExportToTc = True
' default value: False
' ExportToTc [Boolean] {read/write} - flag indicating that the pdf should be output to the TC dataset, False value = output to filesystem
' default value: False
' IsTcRunning [Boolean] {read only} - True if NX is running under TC, false if native NX
' OpenPdf [Boolean] {read/write} - flag to indicate whether the journal should attempt to open the pdf after creation
' default value: False
' OutputFolder [String] {read/write} - path to the output folder
' default value (native): folder of current part
' default value (TC): user's Documents folder
' OutputPdfFileName [String] {read/write} - full file name of outut pdf file (if exporting to filesystem)
' default value (native): <folder of current part>\<part name>_<part revision>{_preliminary}.dxf
' default value (TC): <current user's Documents folder>\<DB_PART_NO>_<DB_PART_REV>{_preliminary}.dxf
' OverwritePdf [Boolean] {read/write} - flag indicating that the pdf file should be overwritten if it already exists
' currently only applies when exporting to the filesystem
' default value: True
' Part [NXOpen.Part] {read/write} - part that contains the drawing sheets of interest
' default value: none, must be set by user
' PartFilePath [String] {read only} - for native NX part files, the path to the part file
' PartNumber [String] {read only} - for native NX part files: part file name
' for TC files: value of DB_PART_NO attribute
' PartRevision [String] {read only} - for native NX part files: value of part "Revision" attribute, if present
' for TC files: value of DB_PART_REV
' PreliminaryPrint [Boolean] {read/write} - flag indicating that the pdf should be marked as an "preliminary"
' when set to True, the output file will be named <filename>_preliminary.dxf
' default value: False
' SheetCount [Integer] {read only} - integer indicating the total number of drawing sheets found in the file
' ShowConfirmationDialog [Boolean] {read/write} - flag indicating whether to show the user a confirmation dialog after pdf is created
' if set to True and ExportToTc = False, user will be asked if they want to open the pdf file
' if user chooses "Yes", the code will attempt to open the pdf with the default viewer
' default value: False
' SkipBlankSheets [Boolean] {read/write} - flag indicating if the user wants to skip drawing sheets with no visible objects.
' default value: True
' SortSheetsByName [Boolean] {read/write} - flag indicating that the sheets should be sorted by name before output to pdf
' default value: True
' TextAsPolylines [Boolean] {read/write} - flag indicating that text objects should be output as polylines instead of text objects
' default value: False set this to True if you are using an NX font and the output changes the 'look' of the text
' UseWatermark [Boolean] {read/write} - flag indicating that watermark text should be applied to the face of the drawing
' default value: False
' WatermarkAddDatestamp [Boolean] {read/write} - flag indicating that today's date should be added to the end of the
' watermark text
' default value: True
' WatermarkText [String] {read/write} - watermark text to use
' default value: "PRELIMINARY PRINT NOT TO BE USED FOR PRODUCTION"
'
'Public Methods:
' New() - initializes a new instance of the class
' New(byval thePart as Part) - initializes a new instance of the class and specifies the NXOpen.Part to use
' PickExportFolder() - displays a FolderPicker dialog box, the user's choice will be set as the output folder
' PromptPreliminaryPrint() - displays a yes/no dialog box asking the user if the print should be marked as preliminary
' if user chooses "Yes", PreliminaryPrint and UseWatermark are set to True
' PromptWatermarkText() - displays an input box prompting the user to enter text to use for the watermark
' if cancel is pressed, the default value is used
' if Me.UseWatermark = True, an input box will appear prompting the user for the desired watermark text. Initial text = Me.WatermarkText
' if Me.UseWatermark = False, calling this method will have no effect
' Commit() - using the specified options, export the given part's sheets to pdf
' SortDrawingSheets() - sorts the drawing sheets in alphabetic order
' SortDrawingSheets(ByVal customSortFunction As System.Comparison(Of NXOpen.Drawings.DrawingSheet)) - sorts the drawing sheets by the custom supplied function
' signature of the sort function must be: {function name}(byval x as Drawings.Drawingsheet, byval y as Drawings.DrawingSheet) as Integer
' a return value < 0 means x comes before y
' a return value > 0 means x comes after y
' a return value = 0 means they are equal (it doesn't matter which is first in the resulting list)
' after writing your custom sort function in the module, pass it in like this: myPdfExporter.Sort(AddressOf {function name})
#End Region
#Region "properties and private variables"
Private Const Version As String = "1.0.1"
Private _theSession As Session = Session.GetSession
Private _theUfSession As UFSession = UFSession.GetUFSession
Private lg As LogFile = _theSession.LogFile
Private _cancelOutput As Boolean = False
Private _drawingSheets As New List(Of Drawings.DrawingSheet)
Private _exportFile As String = ""
Private _partUnits As Integer
Private _watermarkTextFinal As String = ""
Private _outputPdfFiles As New List(Of String)
Private _exportSheetsIndividually As Boolean = False
Public Property ExportSheetsIndividually() As Boolean
Get
Return _exportSheetsIndividually
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property ExportSheetsIndividually")
_exportSheetsIndividually = value
lg.WriteLine(" ExportSheetsIndividually: " & value.ToString)
lg.WriteLine("exiting Set Property ExportSheetsIndividually")
lg.WriteLine("")
End Set
End Property
Private _exportToTC As Boolean = False
Public Property ExportToTc() As Boolean
Get
Return _exportToTC
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property ExportToTc")
_exportToTC = value
lg.WriteLine(" exportToTc: " & _exportToTC.ToString)
Me.GetOutputName()
lg.WriteLine("exiting Set Property ExportToTc")
lg.WriteLine("")
End Set
End Property
Private _isTCRunning As Boolean
Public ReadOnly Property IsTCRunning() As Boolean
Get
Return _isTCRunning
End Get
End Property
Private _openPdf As Boolean = False
Public Property OpenPdf() As Boolean
Get
Return _openPdf
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property OpenPdf")
_openPdf = value
lg.WriteLine(" openPdf: " & _openPdf.ToString)
lg.WriteLine("exiting Set Property OpenPdf")
lg.WriteLine("")
End Set
End Property
Private _outputFolder As String = ""
Public Property OutputFolder() As String
Get
Return _outputFolder
End Get
Set(ByVal value As String)
lg.WriteLine("Set Property OutputFolder")
If _cancelOutput Then
lg.WriteLine(" export pdf canceled")
Exit Property
End If
If Not Directory.Exists(value) Then
Try
lg.WriteLine(" specified directory does not exist, trying to create it...")
Directory.CreateDirectory(value)
lg.WriteLine(" directory created: " & value)
Catch ex As Exception
lg.WriteLine(" ** error while creating directory: " & value)
lg.WriteLine(" " & ex.GetType.ToString & " : " & ex.Message)
lg.WriteLine(" defaulting to: " & My.Computer.FileSystem.SpecialDirectories.MyDocuments)
value = My.Computer.FileSystem.SpecialDirectories.MyDocuments
End Try
End If
_outputFolder = value
_outputPdfFile = IO.Path.Combine(_outputFolder, _exportFile & ".dxf")
lg.WriteLine(" outputFolder: " & _outputFolder)
lg.WriteLine(" outputPdfFile: " & _outputPdfFile)
lg.WriteLine("exiting Set Property OutputFolder")
lg.WriteLine("")
End Set
End Property
Private _outputPdfFile As String = ""
Public Property OutputPdfFileName() As String
Get
Return _outputPdfFile
End Get
Set(ByVal value As String)
lg.WriteLine("Set Property OutputPdfFileName")
lg.WriteLine(" value passed to property: " & value)
_exportFile = IO.Path.GetFileName(value)
If _exportFile.Substring(_exportFile.Length - 4, 4).ToLower = ".dxf" Then
'strip off ".dxf" extension
_exportFile = _exportFile.Substring(_exportFile.Length - 4, 4)
End If
lg.WriteLine(" _exportFile: " & _exportFile)
If Not value.Contains("\") Then
lg.WriteLine(" does not appear to contain path information")
'file name only, need to add output path
_outputPdfFile = IO.Path.Combine(Me.OutputFolder, _exportFile & ".dxf")
Else
'value contains path, update _outputFolder
lg.WriteLine(" value contains path, updating the output folder...")
lg.WriteLine(" parent path: " & Me.GetParentPath(value))
Me.OutputFolder = Me.GetParentPath(value)
_outputPdfFile = IO.Path.Combine(Me.OutputFolder, _exportFile & ".dxf")
End If
'_outputPdfFile = value
lg.WriteLine(" outputPdfFile: " & _outputPdfFile)
lg.WriteLine(" outputFolder: " & Me.OutputFolder)
lg.WriteLine("exiting Set Property OutputPdfFileName")
lg.WriteLine("")
End Set
End Property
Private _overwritePdf As Boolean = True
Public Property OverwritePdf() As Boolean
Get
Return _overwritePdf
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property OverwritePdf")
_overwritePdf = value
lg.WriteLine(" overwritePdf: " & _overwritePdf.ToString)
lg.WriteLine("exiting Set Property OverwritePdf")
lg.WriteLine("")
End Set
End Property
Private _thePart As Part = Nothing
Public Property Part() As Part
Get
Return _thePart
End Get
Set(ByVal value As Part)
lg.WriteLine("Set Property Part")
_thePart = value
_partUnits = _thePart.PartUnits
Me.GetPartInfo()
Me.GetDrawingSheets()
If Me.SortSheetsByName Then
Me.SortDrawingSheets()
End If
lg.WriteLine("exiting Set Property Part")
lg.WriteLine("")
End Set
End Property
Private _partFilePath As String
Public ReadOnly Property PartFilePath() As String
Get
Return _partFilePath
End Get
End Property
Private _partNumber As String
Public ReadOnly Property PartNumber() As String
Get
Return _partNumber
End Get
End Property
Private _partRevision As String = ""
Public ReadOnly Property PartRevision() As String
Get
Return _partRevision
End Get
End Property
Private _preliminaryPrint As Boolean = False
Public Property PreliminaryPrint() As Boolean
Get
Return _preliminaryPrint
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property PreliminaryPrint")
_preliminaryPrint = value
If String.IsNullOrEmpty(_exportFile) Then
'do nothing
Else
Me.GetOutputName()
End If
lg.WriteLine(" preliminaryPrint: " & _preliminaryPrint.ToString)
lg.WriteLine("exiting Set Property PreliminaryPrint")
lg.WriteLine("")
End Set
End Property
Public ReadOnly Property SheetCount() As Integer
Get
Return _drawingSheets.Count
End Get
End Property
Private _showConfirmationDialog As Boolean = False
Public Property ShowConfirmationDialog() As Boolean
Get
Return _showConfirmationDialog
End Get
Set(ByVal value As Boolean)
_showConfirmationDialog = value
End Set
End Property
Private _skipBlankSheets As Boolean = True
Public Property SkipBlankSheets() As Boolean
Get
Return _skipBlankSheets
End Get
Set(ByVal value As Boolean)
_skipBlankSheets = value
End Set
End Property
Private _sortSheetsByName As Boolean
Public Property SortSheetsByName() As Boolean
Get
Return _sortSheetsByName
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property SortSheetsByName")
_sortSheetsByName = value
If _sortSheetsByName = True Then
'sort alphabetically by sheet name
Me.SortDrawingSheets()
Else
'get original collection order of sheets
Me.GetDrawingSheets()
End If
lg.WriteLine(" sortSheetsByName: " & _sortSheetsByName.ToString)
lg.WriteLine("exiting Set Property SortSheetsByName")
lg.WriteLine("")
End Set
End Property
Private _textAsPolylines As Boolean = False
Public Property TextAsPolylines() As Boolean
Get
Return _textAsPolylines
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property TextAsPolylines")
_textAsPolylines = value
lg.WriteLine(" textAsPolylines: " & _textAsPolylines.ToString)
lg.WriteLine("exiting Set Property TextAsPolylines")
lg.WriteLine("")
End Set
End Property
Private _useWatermark As Boolean = False
Public Property UseWatermark() As Boolean
Get
Return _useWatermark
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property UseWatermark")
_useWatermark = value
lg.WriteLine(" useWatermark: " & _useWatermark.ToString)
lg.WriteLine("exiting Set Property UseWatermark")
lg.WriteLine("")
End Set
End Property
Private _watermarkAddDatestamp As Boolean = True
Public Property WatermarkAddDatestamp() As Boolean
Get
Return _watermarkAddDatestamp
End Get
Set(ByVal value As Boolean)
lg.WriteLine("Set Property WatermarkAddDatestamp")
_watermarkAddDatestamp = value
lg.WriteLine(" watermarkAddDatestamp: " & _watermarkAddDatestamp.ToString)
If _watermarkAddDatestamp Then
'to do: internationalization for dates
_watermarkTextFinal = _watermarkText & " " & Today
Else
_watermarkTextFinal = _watermarkText
End If
lg.WriteLine(" watermarkTextFinal: " & _watermarkTextFinal)
lg.WriteLine("exiting Set Property WatermarkAddDatestamp")
lg.WriteLine("")
End Set
End Property
Private _watermarkText As String = "PRELIMINARY PRINT NOT TO BE USED FOR PRODUCTION"
Public Property WatermarkText() As String
Get
Return _watermarkText
End Get
Set(ByVal value As String)
lg.WriteLine("Set Property WatermarkText")
_watermarkText = value
lg.WriteLine(" watermarkText: " & _watermarkText)
lg.WriteLine("exiting Set Property WatermarkText")
lg.WriteLine("")
End Set
End Property
#End Region
#Region "public methods"
Public Sub New()
Me.StartLog()
End Sub
Public Sub New(ByVal thePart As NXOpen.Part)
Me.StartLog()
Me.Part = thePart
End Sub
Public Sub PickExportFolder()
'Requires:
' Imports System.IO
' Imports System.Windows.Forms
'if the user presses OK on the dialog box, the chosen path is returned
'if the user presses cancel on the dialog box, 0 is returned
lg.WriteLine("Sub PickExportFolder")
If Me.ExportToTc Then
lg.WriteLine(" N/A when ExportToTc = True")
lg.WriteLine(" exiting Sub PickExportFolder")
lg.WriteLine("")
Return
End If
Dim strLastPath As String
'Key will show up in HKEY_CURRENT_USER\Software\VB and VBA Program Settings
Try
'Get the last path used from the registry
lg.WriteLine(" attempting to retrieve last export path from registry...")
strLastPath = GetSetting("NX journal", "Export pdf", "ExportPath")
'msgbox("Last Path: " & strLastPath)
Catch e As ArgumentException
lg.WriteLine(" ** Argument Exception: " & e.Message)
Catch e As Exception
lg.WriteLine(" ** Exception type: " & e.GetType.ToString)
lg.WriteLine(" ** Exception message: " & e.Message)
'MsgBox(e.GetType.ToString)
Finally
End Try
Dim FolderBrowserDialog1 As New FolderBrowserDialog
' Then use the following code to create the Dialog window
' Change the .SelectedPath property to the default location
With FolderBrowserDialog1
' Desktop is the root folder in the dialog.
.RootFolder = Environment.SpecialFolder.Desktop
' Select the D:\home directory on entry.
If Directory.Exists(strLastPath) Then
.SelectedPath = strLastPath
Else
.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
End If
' Prompt the user with a custom message.
.Description = "Select the directory to export .dxf file"
If .ShowDialog = DialogResult.OK Then
' Display the selected folder if the user clicked on the OK button.
Me.OutputFolder = .SelectedPath
lg.WriteLine(" selected output path: " & .SelectedPath)
' save the output folder path in the registry for use on next run
SaveSetting("NX journal", "Export pdf", "ExportPath", .SelectedPath)
Else
'user pressed 'cancel', keep original value of output folder
_cancelOutput = True
Me.OutputFolder = Nothing
lg.WriteLine(" folder browser dialog cancel button pressed")
lg.WriteLine(" current output path: {nothing}")
End If
End With
lg.WriteLine("exiting Sub PickExportFolder")
lg.WriteLine("")
End Sub
Public Sub PromptPreliminaryPrint()
lg.WriteLine("Sub PromptPreliminaryPrint")
If _cancelOutput Then
lg.WriteLine(" output canceled")
Return
End If
Dim rspPreliminaryPrint As DialogResult
rspPreliminaryPrint = MessageBox.Show("Add preliminary print watermark?", "Add Watermark?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If rspPreliminaryPrint = DialogResult.Yes Then
Me.PreliminaryPrint = True
Me.UseWatermark = True
lg.WriteLine(" this is a preliminary print")
Else
Me.PreliminaryPrint = False
lg.WriteLine(" this is not a preliminary print")
End If
lg.WriteLine("exiting Sub PromptPreliminaryPrint")
lg.WriteLine("")
End Sub
Public Sub PromptWatermarkText()
lg.WriteLine("Sub PromptWatermarkText")
lg.WriteLine(" useWatermark: " & Me.UseWatermark.ToString)
Dim theWatermarkText As String = Me.WatermarkText
If Me.UseWatermark Then
theWatermarkText = InputBox("Enter watermark text", "Watermark", theWatermarkText)
Me.WatermarkText = theWatermarkText
Else
lg.WriteLine(" suppressing watermark prompt")
End If
lg.WriteLine("exiting Sub PromptWatermarkText")
lg.WriteLine("")
End Sub
Public Sub SortDrawingSheets()
If _cancelOutput Then
Return
End If
If Not IsNothing(_thePart) Then
Me.GetDrawingSheets()
_drawingSheets.Sort(AddressOf Me.CompareSheetNames)
End If
End Sub
Public Sub SortDrawingSheets(ByVal customSortFunction As System.Comparison(Of NXOpen.Drawings.DrawingSheet))
If _cancelOutput Then
Return
End If
If Not IsNothing(_thePart) Then
Me.GetDrawingSheets()
_drawingSheets.Sort(customSortFunction)
End If
End Sub
Public Sub Commit()
If _cancelOutput Then
Return
End If
lg.WriteLine("Sub Commit")
lg.WriteLine(" number of drawing sheets in part file: " & _drawingSheets.Count.ToString)
_outputPdfFiles.Clear()
For Each tempSheet As Drawings.DrawingSheet In _drawingSheets
If Me.PreliminaryPrint Then
_outputPdfFiles.Add(IO.Path.Combine(Me.OutputFolder, tempSheet.Name & "_preliminary.dxf"))
Else
_outputPdfFiles.Add(IO.Path.Combine(Me.OutputFolder, tempSheet.Name & ".dxf"))
End If
Next
'make sure we can output to the specified file(s)
If Me.ExportSheetsIndividually Then
'check each sheet
For Each newPdf As String In _outputPdfFiles
If Not Me.DeleteExistingPdfFile(newPdf) Then
If _overwritePdf Then
'file could not be deleted
MessageBox.Show("The pdf file: " & newPdf & " exists and could not be overwritten." & ControlChars.NewLine & _
"PDF export exiting", "PDF export error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'file already exists and will not be overwritten
MessageBox.Show("The pdf file: " & newPdf & " exists and the overwrite option is set to False." & ControlChars.NewLine & _
"PDF export exiting", "PDF file exists", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Return
End If
Next
Else
'check _outputPdfFile
If Not Me.DeleteExistingPdfFile(_outputPdfFile) Then
If _overwritePdf Then
'file could not be deleted
MessageBox.Show("The pdf file: " & _outputPdfFile & " exists and could not be overwritten." & ControlChars.NewLine & _
"PDF export exiting", "PDF export error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'file already exists and will not be overwritten
MessageBox.Show("The pdf file: " & _outputPdfFile & " exists and the overwrite option is set to False." & ControlChars.NewLine & _
"PDF export exiting", "PDF file exists", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Return
End If
End If
' Dim sheetCount As Integer = 0
' Dim sheetsExported As Integer = 0
' Dim numPlists As Integer = 0
' Dim myPlists() As Tag
' _theUfSession.Plist.AskTags(myPlists, numPlists)
' For i As Integer = 0 To numPlists - 1
' _theUfSession.Plist.Update(myPlists(i))
' Next
' For Each tempSheet As Drawings.DrawingSheet In _drawingSheets
' sheetCount += 1
' lg.WriteLine(" working on sheet: " & tempSheet.Name)
' lg.WriteLine(" sheetCount: " & sheetCount.ToString)
'update any views that are out of date
' lg.WriteLine(" updating OutOfDate views on sheet: " & tempSheet.Name)
' Me.Part.DraftingViews.UpdateViews(Drawings.DraftingViewCollection.ViewUpdateOption.OutOfDate, tempSheet)
' Next
' If Me._drawingSheets.Count > 0 Then
' lg.WriteLine(" done updating views on all sheets")
' Try
' If Me.ExportSheetsIndividually Then
' For Each tempSheet As Drawings.DrawingSheet In _drawingSheets
' lg.WriteLine(" calling Sub ExportPdf")
' lg.WriteLine("")
' If Me.PreliminaryPrint Then
' Me.ExportPdf(tempSheet, IO.Path.Combine(Me.OutputFolder, tempSheet.Name & "_preliminary.dxf"))
' Else
' Me.ExportPdf(tempSheet, IO.Path.Combine(Me.OutputFolder, tempSheet.Name & ".dxf"))
' End If
' Next
' Else
' lg.WriteLine(" calling Sub ExportPdf")
' lg.WriteLine("")
' Me.ExportPdf()
' End If
' Catch ex As Exception
' lg.WriteLine(" ** error exporting PDF")
' lg.WriteLine(" " & ex.GetType.ToString & " : " & ex.Message)
'MessageBox.Show("Error occurred in PDF export" & vbCrLf & ex.Message, "Error exporting PDF", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Throw ex
' End Try
' Else
'no sheets in file
' lg.WriteLine(" ** no drawing sheets in file: " & Me._partNumber)
' End If
If Me.ShowConfirmationDialog Then
Me.DisplayConfirmationDialog()
End If
If (Not Me.ExportToTc) AndAlso (Me.OpenPdf) AndAlso (Me._drawingSheets.Count > 0) Then
'open new pdf print
lg.WriteLine(" trying to open newly created pdf file")
Try
If Me.ExportSheetsIndividually Then
For Each newPdf As String In _outputPdfFiles
System.Diagnostics.Process.Start(newPdf)
Next
Else
System.Diagnostics.Process.Start(Me.OutputPdfFileName)
End If
lg.WriteLine(" pdf open process successful")
Catch ex As Exception
lg.WriteLine(" ** error opening pdf **")
lg.WriteLine(" " & ex.GetType.ToString & " : " & ex.Message)
End Try
End If
lg.WriteLine(" exiting Sub ExportSheetsToPdf")
lg.WriteLine("")
End Sub
#End Region
#Region "private methods"
Private Sub GetPartInfo()
lg.WriteLine("Sub GetPartInfo")
If Me.IsTCRunning Then
_partNumber = _thePart.GetStringAttribute("DB_PART_NO")
_partRevision = _thePart.GetStringAttribute("DB_PART_REV")
lg.WriteLine(" TC running")
lg.WriteLine(" partNumber: " & _partNumber)
lg.WriteLine(" partRevision: " & _partRevision)
Else 'running in native mode
_partNumber = IO.Path.GetFileNameWithoutExtension(_thePart.FullPath)
_partFilePath = IO.Directory.GetParent(_thePart.FullPath).ToString
lg.WriteLine(" Native NX")
lg.WriteLine(" partNumber: " & _partNumber)
lg.WriteLine(" partFilePath: " & _partFilePath)
Try
_partRevision = _thePart.GetStringAttribute("REVISION")
_partRevision = _partRevision.Trim
Catch ex As Exception
_partRevision = ""
End Try
lg.WriteLine(" partRevision: " & _partRevision)
End If
If String.IsNullOrEmpty(_partRevision) Then
_exportFile = _partNumber
Else
_exportFile = _partNumber & "_" & _partRevision
End If
lg.WriteLine("")
Me.GetOutputName()
lg.WriteLine(" exportFile: " & _exportFile)
lg.WriteLine(" outputPdfFile: " & _outputPdfFile)
lg.WriteLine(" exiting Sub GetPartInfo")
lg.WriteLine("")
End Sub
Private Sub GetOutputName()
lg.WriteLine("Sub GetOutputName")
_exportFile.Replace("_preliminary", "")
_exportFile.Replace("_PDF_1", "")
If IsNothing(Me.Part) Then
lg.WriteLine(" Me.Part is Nothing")
lg.WriteLine(" exiting Sub GetOutputName")
lg.WriteLine("")
Return
End If
If Not IsTCRunning And _preliminaryPrint Then
_exportFile &= "_preliminary"
End If
If Me.ExportToTc Then 'export to Teamcenter dataset
lg.WriteLine(" export to TC option chosen")
If Me.IsTCRunning Then
lg.WriteLine(" TC is running")
_exportFile &= "_PDF_1"
Else
'error, cannot export to a dataset if TC is not running
lg.WriteLine(" ** error: export to TC option chosen, but TC is not running")
'todo: throw error
End If
Else 'export to file system
lg.WriteLine(" export to filesystem option chosen")
If Me.IsTCRunning Then
lg.WriteLine(" TC is running")
'exporting from TC to filesystem, no part folder to default to
'default to "MyDocuments" folder
_outputPdfFile = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, _exportFile & ".dxf")
Else
lg.WriteLine(" native NX")
'exporting from native to file system
'use part folder as default output folder
If _outputFolder = "" Then
_outputFolder = _partFilePath
End If
_outputPdfFile = IO.Path.Combine(_outputFolder, _exportFile & ".dxf")
End If
End If
lg.WriteLine(" exiting Sub GetOutputName")
lg.WriteLine("")
End Sub
Private Sub GetDrawingSheets()
_drawingSheets.Clear()
For Each tempSheet As Drawings.DrawingSheet In _thePart.DrawingSheets
If _skipBlankSheets Then
_theUfSession.Disp.SetDisplay(UFConstants.UF_DISP_SUPPRESS_DISPLAY)
Dim currentSheet As Drawings.DrawingSheet = _thePart.DrawingSheets.CurrentDrawingSheet
tempSheet.Open()
If Not IsSheetEmpty(tempSheet) Then
_drawingSheets.Add(tempSheet)
End If
Try
currentSheet.Open()
Catch ex As NXException
lg.WriteLine(" NX current sheet error: " & ex.Message)
Catch ex As Exception
lg.WriteLine(" current sheet error: " & ex.Message)
End Try
_theUfSession.Disp.SetDisplay(UFConstants.UF_DISP_UNSUPPRESS_DISPLAY)
_theUfSession.Disp.RegenerateDisplay()
Else
_drawingSheets.Add(tempSheet)
End If
Next
End Sub
Private Function CompareSheetNames(ByVal x As Drawings.DrawingSheet, ByVal y As Drawings.DrawingSheet) As Integer
'case-insensitive sort
Dim myStringComp As StringComparer = StringComparer.CurrentCultureIgnoreCase
'for a case-sensitive sort (A-Z then a-z), change the above option to:
'Dim myStringComp As StringComparer = StringComparer.CurrentCulture
Return myStringComp.Compare(x.Name, y.Name)
End Function
Private Function GetParentPath(ByVal thePath As String) As String
lg.WriteLine("Function GetParentPath(" & thePath & ")")
Try
Dim directoryInfo As System.IO.DirectoryInfo
directoryInfo = System.IO.Directory.GetParent(thePath)
lg.WriteLine(" returning: " & directoryInfo.FullName)
lg.WriteLine("exiting Function GetParentPath")
lg.WriteLine("")
Return directoryInfo.FullName
Catch ex As ArgumentNullException
lg.WriteLine(" Path is a null reference.")
Throw ex
Catch ex As ArgumentException
lg.WriteLine(" Path is an empty string, contains only white space, or contains invalid characters")
Throw ex
End Try
lg.WriteLine("exiting Function GetParentPath")
lg.WriteLine("")
End Function
Private Sub ExportPdf()
Dim theSession As Session = Session.GetSession()
Dim workPart As Part = theSession.Parts.Work
Dim displayPart As Part = theSession.Parts.Display
Dim ufs As UFSession = UFSession.GetUFSession()
Dim dxfSettingsFile As String
Dim criticalError As Boolean = False
Dim lw As ListingWindow = theSession.ListingWindow
Dim lg As LogFile = theSession.LogFile
Dim dwgs As Drawings.DrawingSheetCollection
dwgs = workPart.DrawingSheets
Dim sheet As Drawings.DrawingSheet
Dim i As Integer = 0
Dim n As Integer = 0
Dim tempCGMFile As String
Dim tempNewFile As String
Dim dxfFile As String
Dim currentPath As String
Dim currentFile As String
Dim originalFile As String
Dim originalPart As Part
Dim killList() As String
Dim partUnits As Integer
Dim strOutputFolder As String
Dim rsp
Dim strRevision As String
Dim exportFile As String
lw.Open()
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'if running Teamcenter, change this to point to your temp import/export dataset file
Const tempTCDXF = "@DB@123/dwg2dxf@A"
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lg.WriteLine("~ Start of drawing to DXF journal ~")
'Get UG install directory using NXOpen API
Dim DXFDWG_DIR As String = theSession.GetEnvironmentVariableValue("DXFDWG_DIR")
dxfSettingsFile = IO.Path.Combine(DXFDWG_DIR, "dxfdwg.def")
lg.WriteLine("looking for dxf settings file: " & dxfSettingsFile)
'check if the dxfSettingsFile exists
If Not File.Exists(dxfSettingsFile) Then
'file does not exist in default directory or user specified directory
lg.WriteLine("The dxf settings file was not found in the specified location: " & dxfSettingsFile)
MsgBox("The dxf settings file (dxfdwg.def) was not found." & vbCrLf & _
"This journal will now exit.", vbOKOnly + vbCritical, "Error")
Exit Sub
End If
lg.WriteLine("DXF settings file found: " & dxfSettingsFile)
'determine if we are running under TC or native
Dim IsTcEng As Boolean = False
ufs.UF.IsUgmanagerActive(IsTcEng)
lg.WriteLine("TC running? " & IsTcEng)
originalPart = displayPart
If IsTcEng Then
lg.WriteLine("tempTCDXF: " & tempTCDXF)
currentFile = workPart.GetStringAttribute("DB_PART_NO")
strRevision = workPart.GetStringAttribute("DB_PART_REV")
originalFile = "@DB/" & currentFile & "/" & strRevision
currentFile = currentFile.Replace("/", "_")
currentFile = currentFile & "_" & strRevision
Else 'running in native mode
currentPath = Path.GetDirectoryName(workPart.FullPath)
currentFile = Path.GetFileNameWithoutExtension(workPart.FullPath)
originalFile = currentFile
Try
strRevision = workPart.GetStringAttribute("REVISION")
strRevision = Trim(strRevision)
Catch ex As NXOpen.NXException
If ex.ErrorCode = 512008 Then
lg.WriteLine("Revision attribute not found")
Else
lg.WriteLine("Error: " & ex.ErrorCode & " " & ex.GetType.ToString & " : " & ex.Message)
End If
strRevision = ""
End Try
If strRevision <> "" Then
currentFile = currentFile & "_" & strRevision
End If
End If
exportFile = currentFile
lg.WriteLine("workPart.FullPath: " & workPart.FullPath)
lg.WriteLine("currentFile: " & currentFile)
lg.WriteLine("strRevision: " & strRevision)
lg.WriteLine("originalFile: " & originalFile)
lg.WriteLine("originalPart: " & originalPart.FullPath)
partUnits = workPart.PartUnits
'0 = inch
'1 = metric
lg.WriteLine("Part units: " & workPart.PartUnits.ToString)
Dim FolderBrowserDialog1 As New FolderBrowserDialog
' Then use the following code to create the Dialog window
' Change the .SelectedPath property to the default location
With FolderBrowserDialog1
' Desktop is the root folder in the dialog.
.RootFolder = Environment.SpecialFolder.Desktop
' Select the C:\ directory on entry.
.SelectedPath = "C:\"
' Prompt the user with a custom message.
.Description = "Select the directory to export .dxf file(s)"
If .ShowDialog = DialogResult.OK Then
strOutputFolder = .SelectedPath
Else
Exit Sub
End If
End With
lg.WriteLine("Output folder: " & strOutputFolder)
For Each sheet In dwgs
i += 1
'in original file, export each drawing sheet as a .cgm file
'prepare for CGM export
tempCGMFile = Path.Combine(strOutputFolder, currentFile & "_" & i & ".cgm")
lg.WriteLine("Exporting temp CGM file: " & tempCGMFile)
If File.Exists(tempCGMFile) Then
lg.WriteLine(tempCGMFile & " already exists, deleting file before export")
Try
File.Delete(tempCGMFile)
Catch ex As UnauthorizedAccessException
lg.WriteLine("Unauthorized access exception, cannot delete file: " & tempCGMFile)
lg.WriteLine("Please check permissions on the file and folder(s) and try again")
lg.WriteLine("Drawing to DXF journal will now exit")
MsgBox("Error: cannot delete file: " & tempCGMFile, MsgBoxStyle.Critical, "Unauthorized access exception")
Exit Sub
Catch ex As ApplicationException
lg.WriteLine("Error occurred while attempting to delete file: " & tempCGMFile)
lg.WriteLine(ex.GetType.ToString & " : " & ex.Message)
MsgBox("Error occurred while attempting to delete file: " & tempCGMFile & vbCrLf & "Drawing to DXF journal will now exit", MsgBoxStyle.Critical, "Error")
End Try
End If
Try
ExportCGM(sheet, tempCGMFile, partUnits)
Catch ex As Exception
MsgBox("Error occurred in CGM export" & vbCrLf & ex.GetType.ToString & " : " & ex.Message & vbCrLf & "journal exiting", vbCritical + vbOKOnly, "Error")
lg.WriteLine("Error occurred in CGM export: " & ex.GetType.ToString & " : " & ex.Message)
Exit Sub
End Try
'import .cgm file to temporary file in preparation for .dxf export
If IsTcEng Then
Dim partLoadStatus1 As PartLoadStatus
Try
lg.WriteLine("theSession.Parts.SetNonmasterSeedPartData(" & tempTCDXF & ")")
theSession.Parts.SetNonmasterSeedPartData(tempTCDXF)
Dim basePart1 As BasePart
lg.WriteLine("Opening part: " & tempTCDXF)
basePart1 = theSession.Parts.OpenBaseDisplay(tempTCDXF, partLoadStatus1)
lg.WriteLine(tempTCDXF & " load status: " & partLoadStatus1.ToString)
Catch ex As Exception
MsgBox("An error occurred while opening the temp dxf import part" & vbCrLf & ex.GetType.ToString & " : " & ex.Message, vbCritical + vbOKOnly, "Error")
lg.WriteLine(tempTCDXF & " load status: " & partLoadStatus1.ToString)
lg.WriteLine("An error occurred while opening: " & tempTCDXF & " " & ex.GetType.ToString & " : " & ex.Message)
Exit Sub
Finally
partLoadStatus1.Dispose()
End Try
Else
'create a new file to import the CGM
tempNewFile = strOutputFolder & "\" & currentFile & "_" & i & ".prt"
lg.WriteLine("tempNewFile: " & tempNewFile)
If File.Exists(tempNewFile) Then
lg.WriteLine("tempNewFile already exists: " & tempNewFile)
rsp = MsgBox("The file: '" & tempNewFile & "' already exists; overwrite?", vbYesNo + vbQuestion, "File exists")
If rsp = vbYes Then
lg.WriteLine("user has chosen to overwrite: " & tempNewFile)
Try
lg.WriteLine("attempting to delete: " & tempNewFile)
File.Delete(tempNewFile)
Catch ex As UnauthorizedAccessException
lg.WriteLine("Unauthorized access exception, check permissions on: " & tempNewFile & " and try again")
MsgBox("Unable to delete file: " & tempNewFile & vbCrLf & "Drawing to DXF journal will now exit", MsgBoxStyle.Critical, "Unauthorized Access Exception")
Exit Sub
Catch ex As ApplicationException
lg.WriteLine("An exception occurred while attempting to delete file: " & tempNewFile)
lg.WriteLine(ex.GetType.ToString & " : " & ex.Message)
lg.WriteLine("Drawing to DXF journal will now exit")
MsgBox("An exception occurred while attempting to delete file: " & tempNewFile & vbCrLf & "Drawing to DXF journal will now exit", MsgBoxStyle.Critical, "Error")
Exit Sub
End Try
Else
lg.WriteLine("User chose not to overwrite the existing file: " & tempNewFile)
lg.WriteLine("Drawing to DXF journal will now exit")
MsgBox("journal exiting", vbOKOnly, "Export cancelled")
Exit Sub
End If
End If
Try
lg.WriteLine("Attempting to create temporary cgm import file: " & tempNewFile)
NewFile(tempNewFile, partUnits)
Catch ex As Exception
lg.WriteLine("Error in temporary cgm import file creation: " & tempNewFile)
lg.WriteLine(ex.GetType.ToString & " : " & ex.Message)
lg.WriteLine("Drawing to DXF journal will now exit")
MsgBox("Error occurred in new file creation" & vbCrLf & ex.Message & vbCrLf & "journal exiting", vbCritical + vbOKOnly, "Error")
Exit Sub
End Try
End If
'now in temporary dxf import file
workPart = theSession.Parts.Work
displayPart = theSession.Parts.Display
lg.WriteLine("work part: " & theSession.Parts.Work.FullPath)
'turn off the display of the drawing sheet, some users report errors if the sheet is displayed when the view is replaced
'1 = Modeling view
'2 = Drawing view
ufs.Draw.SetDisplayState(1)
'replace view to "TOP" before importing the CGM
'this gives better results with fixed view drawing viewers such as edrawings
Dim layout1 As Layout = CType(theSession.Parts.Work.Layouts.Current, Layout)
lg.WriteLine("current layout: " & layout1.Name)
Dim modelingView1 As ModelingView = CType(theSession.Parts.Work.ModelingViews.FindObject("TOP"), ModelingView)
lg.WriteLine("modelingView1: " & modelingView1.Name)
layout1.ReplaceView(theSession.Parts.Work.ModelingViews.WorkView, modelingView1, True)
'Call the ImportCGM subroutine
workPart.Layers.WorkLayer = 1
lg.WriteLine("Calling the ImportCGM(" & tempCGMFile & ")")
ImportCGM(tempCGMFile)
lg.WriteLine("Saving temporary cgm import file: " & tempCGMFile)
workPart.Save(BasePart.SaveComponents.False, BasePart.CloseAfterSave.False)
If IsTcEng Then
ReDim Preserve killList(i)
killList(i) = tempCGMFile
lg.WriteLine("Adding file to kill list: " & tempCGMFile)
Else
'add the temp files to the kill list
ReDim Preserve killList(i * 2)
killList(i * 2 - 1) = tempCGMFile
killList(i * 2) = tempNewFile
lg.WriteLine("Adding file to kill list: " & tempCGMFile)
lg.WriteLine("Adding file to kill list: " & tempNewFile)
End If
dxfFile = Path.Combine(strOutputFolder, currentFile & "_" & i & ".dxf")
lg.WriteLine("DXF file: " & dxfFile)
If File.Exists(dxfFile) Then
rsp = MsgBox("The file: '" & dxfFile & "' already exists; overwrite?", vbYesNo + vbQuestion, "File exists")
lg.WriteLine("The specified DXF output file already exists")
If rsp = vbYes Then
lg.WriteLine("user has chosen to overwrite the existing DXF file")
Try
File.Delete(dxfFile)
Catch ex As UnauthorizedAccessException
lg.WriteLine("Unauthorized access exception, cannot delete file: " & dxfFile)
lg.WriteLine("Please check permissions on the file and folder(s) and try again")
lg.WriteLine("Drawing to DXF journal will now exit")
MsgBox("Error: cannot delete file: " & dxfFile & vbCrLf & "Please check permissions on the file and try again", MsgBoxStyle.Critical, "Unauthorized access exception")
Exit Sub
Catch ex As ApplicationException
lg.WriteLine("Error occurred while attempting to delete file: " & dxfFile)
lg.WriteLine(ex.GetType.ToString & " : " & ex.Message)
MsgBox("Error occurred while attempting to delete file: " & dxfFile & vbCrLf & "Drawing to DXF journal will now exit", MsgBoxStyle.Critical, "Error")
End Try
Else
lg.WriteLine("user chose not to overwrite existing DXF file")
lg.WriteLine("Drawing to DXF journal will now exit")
MsgBox("Journal will now exit", MsgBoxStyle.Exclamation, "Export cancelled")
Exit Sub
End If
End If
Try
'Call ExportDXF subroutine
lg.WriteLine("Calling export DXF routine")
If IsTcEng Then
lg.WriteLine("ExportDXF(" & tempTCDXF & ", " & dxfFile & ")")
ExportDXF(tempTCDXF, dxfFile)
Else
lg.WriteLine("ExportDXF(" & tempNewFile & ", " & dxfFile & ")")
ExportDXF(tempNewFile, dxfFile)
End If
lg.WriteLine("Waiting on creation of DXF file...")
While Not File.Exists(dxfFile)
Application.DoEvents()
End While
lg.WriteLine("DXF file created: " & dxfFile)
Catch ex As Exception
MsgBox("Error occurred in DXF export" & vbCrLf & ex.Message & vbCrLf & "journal exiting", vbCritical + vbOKOnly, "Error")
lg.WriteLine("Error in DXF export: " & ex.GetType.ToString & " : " & ex.Message)
lg.WriteLine("Drawing to DXF journal will now exit")
Exit Sub
Finally
lg.WriteLine("deleting temporary objects from: " & workPart.FullPath)
Dim markId1 As Session.UndoMarkId
markId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Start")
'delete all imported objects (all objects on layer 1)
Dim importEntities() As NXObject
importEntities = workPart.Layers.GetAllObjectsOnLayer(1)
Dim nErrs1 As Integer
nErrs1 = theSession.UpdateManager.AddToDeleteList(importEntities)
Dim nErrs2 As Integer
nErrs2 = theSession.UpdateManager.DoUpdate(markId1)
'close the temporary DXF file
lg.WriteLine("Closing the temporary dxf file")
workPart.Save(BasePart.SaveComponents.False, BasePart.CloseAfterSave.True)
End Try
'make the original part the displayed part
Dim partLoadStatus2 As PartLoadStatus
Dim status1 As PartCollection.SdpsStatus
status1 = theSession.Parts.SetDisplay(originalPart, False, True, partLoadStatus2)
lg.WriteLine("make original part the displayed part")
lg.WriteLine("status1: " & status1.ToString)
workPart = theSession.Parts.Work
displayPart = theSession.Parts.Display
partLoadStatus2.Dispose()
lg.WriteLine("current display part: " & displayPart.FullPath)
Next
If i = 0 Then
lg.WriteLine("This part has no drawing sheets to export")
MsgBox("This part has no drawing sheets to export", MsgBoxStyle.Exclamation, "Huh?")
Else
'cleanup temp files
lg.WriteLine("Cleaning up temporary files")
Dim j As Integer
j = 1
If IsTcEng Then
For j = 1 To i
File.Delete(killList(j))
lg.WriteLine("File deleted: " & killList(j))
Next
Else
For j = 1 To i * 2
File.Delete(killList(j))
lg.WriteLine("File deleted: " & killList(j))
Next
End If
MsgBox("Exported: " & i & " sheets as dxf files", vbOKOnly + vbInformation, "Success!")
lg.WriteLine("Exported: " & i & " sheets as dxf files")
End If
lg.WriteLine("~ End of drawing to DXF export journal ~")
lw.Close()
End Sub
'**********************************************************
Sub ExportCGM(ByVal dwg As Drawings.DrawingSheet, ByVal outputFile As String, ByVal units As Integer)
Dim theSession As Session = Session.GetSession()
Dim workPart As Part = theSession.Parts.Work
Dim displayPart As Part = theSession.Parts.Display
Dim ufs As UFSession = UFSession.GetUFSession()
Dim dxfSettingsFile As String
Dim criticalError As Boolean = False
Dim lw As ListingWindow = theSession.ListingWindow
Dim lg As LogFile = theSession.LogFile
Dim filenames1(0) As String
Dim objCGM As CGMBuilder
objCGM = theSession.Parts.Work.PlotManager.CreateCgmBuilder()
objCGM.Action = CGMBuilder.ActionOption.FileBrowser
objCGM.OutputText = CGMBuilder.OutputTextOption.Polylines
If units = 0 Then
objCGM.Units = CGMBuilder.UnitsOption.English
Else
objCGM.Units = CGMBuilder.UnitsOption.Metric
End If
objCGM.XDimension = dwg.Height
objCGM.YDimension = dwg.Length
objCGM.VdcCoordinates = CGMBuilder.Vdc.Real
objCGM.RasterImages = True
Dim sheets1(0) As NXObject
sheets1(0) = dwg
objCGM.SourceBuilder.SetSheets(sheets1)
filenames1(0) = outputFile
objCGM.SetFilenames(filenames1)
Try
Dim nXObject1 As NXObject
nXObject1 = objCGM.Commit()
Catch ex As Exception
lg.WriteLine("Error in ExportCGM subroutine: " & ex.GetType.ToString & " : " & ex.Message)
Finally
objCGM.Destroy()
End Try
End Sub
'**********************************************************