VB code to export drawing file to PDF even through there are multiple drawing files are open
VB code to export drawing file to PDF even through there are multiple drawing files are open
(OP)
here is the original code by cowski: http://nxjournaling.com/?q=content/exporting-drawi...
i first played around the code but found that it worked only for the currently displayed part darwing. however, i have multiple part drawing open so i need to update those part drawing after the curently displayed part drawing is exported to PDF.
at first, i added the following
after the modification, i prepare two drawing part file called dwg1.prt and dwg2.prt
i run the code, the NX export dwg1.pdf, that's fine, and ready to switch to another part file
after switching to dwg2.prt, nx ask me that dwg1.pdf already exists, replace it?
then i asked myself why this happened? because at this stage, the displayed part is already dwg2.prt, so the file name should follow the currently displayed part drawing...
i kept modifiying and came up with the following solution marked in RED color:
i first played around the code but found that it worked only for the currently displayed part darwing. however, i have multiple part drawing open so i need to update those part drawing after the curently displayed part drawing is exported to PDF.
at first, i added the following
CODE --> vb
Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.UF
Imports NXOpen.UI
Imports NXOpen.Annotations
Imports NXOpen.Utilities
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Imports System.Collections
Imports System.IO
Imports System.Windows.Forms
Imports System.Windows.Forms.MessageBox
Imports NXOpen.Assemblies
Imports System.Environment
Imports System.Runtime.InteropServices
Module exprotPDF
Dim theUI As UI = UI.GetUI()
Dim theSession As Session = Session.GetSession()
Dim theUfSession As UFSession = UFSession.GetUFSession()
Dim LW As ListingWindow = theSession.ListingWindow
Dim workPart As Part = theSession.Parts.Work
Dim displayPart As Part = theSession.Parts.Display
Sub Main()
LW.Open()
Dim i As Integer
Dim pdfFile As String
Dim currentPath As String
Dim currentFile As String
Dim exportFile As String
Dim partUnits As Integer
Dim strOutputFolder As String
Dim strRevision As String
Dim rspFileExists
Dim rspAdvancePrint
For Each tempPart As Part In theSession.Parts
Dim partLoadStatus1 As PartLoadStatus
Dim status1 As PartCollection.SdpsStatus
status1 = theSession.Parts.SetDisplay(temppart, False, False, partLoadStatus1
Dim dwgs As Drawings.DrawingSheetCollection
dwgs = tempPart.DrawingSheets
Dim sheet As Drawings.DrawingSheet
currentPath = GetFilePath()
currentFile = GetFileName()
Try
strRevision = tempPart.GetStringAttribute("REVISION")
LW.WriteLine(strRevision)
strRevision = Trim(strRevision)
Catch ex As Exception
strRevision = ""
End Try
exportFile = currentFile
strOutputFolder = OutputPath()
'if we don't have a valid directory (ie the user pressed 'cancel') exit the journal
If Not Directory.Exists(strOutputFolder) Then
Exit Sub
End If
strOutputFolder = strOutputFolder & "\"
rspAdvancePrint = MessageBox.Show("Add advance print watermark?", "Add Watermark?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Dim shts As New ArrayList()
For Each sheet In dwgs
shts.Add(sheet.Name)
Next
shts.Sort()
i = 0
Dim sht As String
For Each sht In shts '<-- the shts array
For Each sheet In dwgs
If sheet.Name = sht Then
i = i + 1
If rspAdvancePrint = vbYes Then
pdfFile = strOutputFolder & exportFile & "_advance" & ".pdf"
Else
If strRevision <> "" Then
pdfFile = strOutputFolder & exportFile & "_" & strRevision & ".pdf"
Else
pdfFile = strOutputFolder & exportFile & ".pdf"
End If
End If
'the pdf export uses 'append file', if we are on sheet 1 make sure the user wants to overwrite
'if the drawing is multisheet, don't ask on subsequent sheets
If i = 1 Then
If File.Exists(pdfFile) Then
rspFileExists = MsgBox("The file: '" & pdfFile & "' already exists; overwrite?", vbYesNo + vbQuestion)
If rspFileExists = vbYes Then
Try
File.Delete(pdfFile)
Catch ex As Exception
MsgBox(ex.Message & vbCrLf & "Journal exiting", vbCritical + vbOKOnly, "Error")
Exit Sub
End Try
Else
'msgbox("journal exiting", vbokonly)
Exit Sub
End If
End If
End If
'update any views that are out of date
theSession.Parts.Work.DraftingViews.UpdateViews(Drawings.DraftingViewCollection.ViewUpdateOption.OutOfDate, sheet)
Try
ExportPDF(sheet, pdfFile, partUnits, rspAdvancePrint)
Catch ex As Exception
MsgBox("Error occurred in PDF export" & vbCrLf & ex.Message & vbCrLf & "journal exiting", vbCritical + vbOKOnly, "Error")
Exit Sub
End Try
Exit For
End If
Next
Next
If i = 0 Then
MessageBox.Show("This part has no drawing sheets to export", "PDF export failure", MessageBoxButtons.ok, MessageBoxIcon.Warning)
Else
MessageBox.Show("Exported: " & i & " sheet(s) to pdf file" & vbCrLf & pdfFile, "PDF export success", MessageBoxButtons.ok, MessageBoxIcon.Information)
End If
Next
End Sub
'=============================================================
Function GetFileName()
Dim strPath As String
Dim strPart As String
Dim pos As Integer
'get the full file path
strPath = displayPart.fullpath
'get the part file name
pos = InStrRev(strPath, "\")
strPart = Mid(strPath, pos + 1)
strPath = Left(strPath, pos)
'strip off the ".prt" extension
strPart = Left(strPart, Len(strPart) - 4)
GetFileName = strPart
End Function
'=============================================================
Function GetFilePath()
Dim strPath As String
Dim strPart As String
Dim pos As Integer
'get the full file path
strPath = displayPart.FullPath
'get the part file name
pos = InStrRev(strPath, "\")
strPart = Mid(strPath, pos + 1)
strPath = Left(strPath, pos)
'strip off the ".prt" extension
strPart = Left(strPart, Len(strPart) - 4)
GetFilePath = strPath
End Function
'=============================================================
Function OutputPath()
'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
Dim strLastPath As String
Dim strOutputPath 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
strLastPath = GetSetting("NX journal", "Export pdf", "ExportPath")
'msgbox("Last Path: " & strLastPath)
Catch e As ArgumentException
Catch e As Exception
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 = "D:\home"
End If
' Prompt the user with a custom message.
.Description = "Select the directory to export .pdf file"
If .ShowDialog = DialogResult.OK Then
' Display the selected folder if the user clicked on the OK button.
OutputPath = .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', exit the subroutine
OutputPath = 0
'exit sub
End If
End With
End Function
'=============================================================
Sub ExportPDF(ByVal dwg As Drawings.DrawingSheet, ByVal outputFile As String, ByVal units As Integer, ByVal advancePrint As Integer)
Dim printPDFBuilder1 As PrintPDFBuilder
printPDFBuilder1 = workPart.PlotManager.CreatePrintPdfbuilder()
printPDFBuilder1.Scale = 1.0
printPDFBuilder1.Action = PrintPDFBuilder.ActionOption.Native
printPDFBuilder1.Colors = PrintPDFBuilder.Color.BlackOnWhite
printPDFBuilder1.Size = PrintPDFBuilder.SizeOption.ScaleFactor
If units = 0 Then
printPDFBuilder1.Units = PrintPDFBuilder.UnitsOption.English
Else
printPDFBuilder1.Units = PrintPDFBuilder.UnitsOption.Metric
End If
printPDFBuilder1.XDimension = dwg.height
printPDFBuilder1.YDimension = dwg.length
printPDFBuilder1.OutputText = PrintPDFBuilder.OutputTextOption.Polylines
printPDFBuilder1.RasterImages = True
printPDFBuilder1.ImageResolution = PrintPDFBuilder.ImageResolutionOption.Medium
printPDFBuilder1.Append = True
If advancePrint = vbyes Then
printPDFBuilder1.AddWatermark = True
printPDFBuilder1.Watermark = "ADVANCE PRINT NOT TO BE USED FOR PRODUCTION " & Today
Else
printPDFBuilder1.AddWatermark = False
printPDFBuilder1.Watermark = ""
End If
Dim sheets1(0) As NXObject
Dim drawingSheet1 As Drawings.DrawingSheet = CType(dwg, Drawings.DrawingSheet)
sheets1(0) = drawingSheet1
printPDFBuilder1.SourceBuilder.SetSheets(sheets1)
printPDFBuilder1.Filename = outputFile
Dim nXObject1 As NXObject
nXObject1 = printPDFBuilder1.Commit()
printPDFBuilder1.Destroy()
End Sub
'===================================================================
End Module after the modification, i prepare two drawing part file called dwg1.prt and dwg2.prt
i run the code, the NX export dwg1.pdf, that's fine, and ready to switch to another part file
after switching to dwg2.prt, nx ask me that dwg1.pdf already exists, replace it?
then i asked myself why this happened? because at this stage, the displayed part is already dwg2.prt, so the file name should follow the currently displayed part drawing...
i kept modifiying and came up with the following solution marked in RED color:
CODE --> vb
Option Strict Off
Imports System
Imports NXOpen
Imports NXOpen.UF
Imports NXOpen.UI
Imports NXOpen.Annotations
Imports NXOpen.Utilities
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Imports System.Collections
Imports System.IO
Imports System.Windows.Forms
Imports System.Windows.Forms.MessageBox
Imports NXOpen.Assemblies
Imports System.Environment
Imports System.Runtime.InteropServices
Module exprotPDF
Dim theUI As UI = UI.GetUI()
Dim theSession As Session = Session.GetSession()
Dim theUfSession As UFSession = UFSession.GetUFSession()
Dim LW As ListingWindow = theSession.ListingWindow
Sub Main()
'Dim workPart As Part = theSession.Parts.Work <---disabled by me originally outside of the Main
'Dim displayPart As Part = theSession.Parts.Display <---disabled by me originally outside of the Main
LW.Open()
Dim i As Integer
Dim pdfFile As String
Dim currentPath As String
Dim currentFile As String
Dim exportFile As String
Dim partUnits As Integer
Dim strOutputFolder As String
Dim strRevision As String
Dim rspFileExists
Dim rspAdvancePrint
For Each tempPart As Part In theSession.Parts
Dim partLoadStatus1 As PartLoadStatus
Dim status1 As PartCollection.SdpsStatus
status1 = theSession.Parts.SetDisplay(temppart, False, False, partLoadStatus1
Dim dwgs As Drawings.DrawingSheetCollection
dwgs = tempPart.DrawingSheets
Dim sheet As Drawings.DrawingSheet
currentPath = GetFilePath()
currentFile = GetFileName()
Try
strRevision = tempPart.GetStringAttribute("REVISION")
LW.WriteLine(strRevision)
strRevision = Trim(strRevision)
Catch ex As Exception
strRevision = ""
End Try
exportFile = currentFile
strOutputFolder = OutputPath()
'if we don't have a valid directory (ie the user pressed 'cancel') exit the journal
If Not Directory.Exists(strOutputFolder) Then
Exit Sub
End If
strOutputFolder = strOutputFolder & "\"
rspAdvancePrint = MessageBox.Show("Add advance print watermark?", "Add Watermark?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Dim shts As New ArrayList()
For Each sheet In dwgs
shts.Add(sheet.Name)
Next
shts.Sort()
i = 0
Dim sht As String
For Each sht In shts '<-- the shts array
For Each sheet In dwgs
If sheet.Name = sht Then
i = i + 1
If rspAdvancePrint = vbYes Then
pdfFile = strOutputFolder & exportFile & "_advance" & ".pdf"
Else
If strRevision <> "" Then
pdfFile = strOutputFolder & exportFile & "_" & strRevision & ".pdf"
Else
pdfFile = strOutputFolder & exportFile & ".pdf"
End If
End If
'the pdf export uses 'append file', if we are on sheet 1 make sure the user wants to overwrite
'if the drawing is multisheet, don't ask on subsequent sheets
If i = 1 Then
If File.Exists(pdfFile) Then
rspFileExists = MsgBox("The file: '" & pdfFile & "' already exists; overwrite?", vbYesNo + vbQuestion)
If rspFileExists = vbYes Then
Try
File.Delete(pdfFile)
Catch ex As Exception
MsgBox(ex.Message & vbCrLf & "Journal exiting", vbCritical + vbOKOnly, "Error")
Exit Sub
End Try
Else
'msgbox("journal exiting", vbokonly)
Exit Sub
End If
End If
End If
'update any views that are out of date
theSession.Parts.Work.DraftingViews.UpdateViews(Drawings.DraftingViewCollection.ViewUpdateOption.OutOfDate, sheet)
Try
ExportPDF(sheet, pdfFile, partUnits, rspAdvancePrint)
Catch ex As Exception
MsgBox("Error occurred in PDF export" & vbCrLf & ex.Message & vbCrLf & "journal exiting", vbCritical + vbOKOnly, "Error")
Exit Sub
End Try
Exit For
End If
Next
Next
If i = 0 Then
MessageBox.Show("This part has no drawing sheets to export", "PDF export failure", MessageBoxButtons.ok, MessageBoxIcon.Warning)
Else
MessageBox.Show("Exported: " & i & " sheet(s) to pdf file" & vbCrLf & pdfFile, "PDF export success", MessageBoxButtons.ok, MessageBoxIcon.Information)
End If
Next
End Sub
'=============================================================
Function GetFileName()
Dim strPath As String
Dim strPart As String
Dim pos As Integer
Dim displayPart As Part = theSession.Parts.Display '<--added by me
'get the full file path
strPath = displayPart.fullpath
'get the part file name
pos = InStrRev(strPath, "\")
strPart = Mid(strPath, pos + 1)
strPath = Left(strPath, pos)
'strip off the ".prt" extension
strPart = Left(strPart, Len(strPart) - 4)
GetFileName = strPart
End Function
'=============================================================
Function GetFilePath()
Dim strPath As String
Dim strPart As String
Dim pos As Integer
Dim displayPart As Part = theSession.Parts.Display '<--added by me
'get the full file path
strPath = displayPart.FullPath
'get the part file name
pos = InStrRev(strPath, "\")
strPart = Mid(strPath, pos + 1)
strPath = Left(strPath, pos)
'strip off the ".prt" extension
strPart = Left(strPart, Len(strPart) - 4)
GetFilePath = strPath
End Function
'=============================================================
Function OutputPath()
'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
Dim strLastPath As String
Dim strOutputPath 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
strLastPath = GetSetting("NX journal", "Export pdf", "ExportPath")
'msgbox("Last Path: " & strLastPath)
Catch e As ArgumentException
Catch e As Exception
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 = "D:\home"
End If
' Prompt the user with a custom message.
.Description = "Select the directory to export .pdf file"
If .ShowDialog = DialogResult.OK Then
' Display the selected folder if the user clicked on the OK button.
OutputPath = .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', exit the subroutine
OutputPath = 0
'exit sub
End If
End With
End Function
'=============================================================
Sub ExportPDF(ByVal dwg As Drawings.DrawingSheet, ByVal outputFile As String, ByVal units As Integer, ByVal advancePrint As Integer)
Dim printPDFBuilder1 As PrintPDFBuilder
Dim workPart As Part = theSession.Parts.Work '<--added by me
printPDFBuilder1 = workPart.PlotManager.CreatePrintPdfbuilder()
printPDFBuilder1.Scale = 1.0
printPDFBuilder1.Action = PrintPDFBuilder.ActionOption.Native
printPDFBuilder1.Colors = PrintPDFBuilder.Color.BlackOnWhite
printPDFBuilder1.Size = PrintPDFBuilder.SizeOption.ScaleFactor
If units = 0 Then
printPDFBuilder1.Units = PrintPDFBuilder.UnitsOption.English
Else
printPDFBuilder1.Units = PrintPDFBuilder.UnitsOption.Metric
End If
printPDFBuilder1.XDimension = dwg.height
printPDFBuilder1.YDimension = dwg.length
printPDFBuilder1.OutputText = PrintPDFBuilder.OutputTextOption.Polylines
printPDFBuilder1.RasterImages = True
printPDFBuilder1.ImageResolution = PrintPDFBuilder.ImageResolutionOption.Medium
printPDFBuilder1.Append = True
If advancePrint = vbyes Then
printPDFBuilder1.AddWatermark = True
printPDFBuilder1.Watermark = "ADVANCE PRINT NOT TO BE USED FOR PRODUCTION " & Today
Else
printPDFBuilder1.AddWatermark = False
printPDFBuilder1.Watermark = ""
End If
Dim sheets1(0) As NXObject
Dim drawingSheet1 As Drawings.DrawingSheet = CType(dwg, Drawings.DrawingSheet)
sheets1(0) = drawingSheet1
printPDFBuilder1.SourceBuilder.SetSheets(sheets1)
printPDFBuilder1.Filename = outputFile
Dim nXObject1 As NXObject
nXObject1 = printPDFBuilder1.Commit()
printPDFBuilder1.Destroy()
End Sub
'===================================================================
End Module 




RE: VB code to export drawing file to PDF even through there are multiple drawing files are open
what 's the difference between declaring displaypart and workpart inside or outside the Sub Main()?
those added line were added because I guess that if displayPart and workPart are declared outside the Main(), it means they are global....
since i have multiple part files, i need to treat them individually, and that's why i deleted the declared workpart and displayed part outside the Main() and add them locally...
are my guess wrong AND any solution ?
thank you :)
RE: VB code to export drawing file to PDF even through there are multiple drawing files are open
Mike Hyde
www.astonmartin.com
NX8.5 with TC9.1
RE: VB code to export drawing file to PDF even through there are multiple drawing files are open
CODE
'Output pdf of all parts in session. Option Strict Off Imports System Imports System.IO Imports System.Collections.Generic Imports System.Windows.Forms Imports NXOpen Imports NXOpen.UF Module Module2 Sub Main() Dim theSession As Session = Session.GetSession If IsNothing(theSession.Parts.Display) Then MessageBox.Show("Active Part Required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Return End If Dim workPart As Part = theSession.Parts.Work Dim displayPart As Part = theSession.Parts.Display For Each tempPart As Part In theSession.Parts Dim partLoadStatus1 As PartLoadStatus Dim status1 As PartCollection.SdpsStatus status1 = theSession.Parts.SetDisplay(tempPart, False, False, partLoadStatus1) workPart = theSession.Parts.Work displayPart = theSession.Parts.Display partLoadStatus1.Dispose() Dim myPdfExporter As New NXJ_PdfExporter myPdfExporter.Part = displayPart '$ show confirmation dialog box on completion myPdfExporter.ShowConfirmationDialog = True Try myPdfExporter.Commit() Catch ex As Exception MessageBox.Show("Error:" & ControlChars.CrLf & ex.GetType.ToString & " : " & ex.Message, "PDF export error", MessageBoxButtons.OK, MessageBoxIcon.Error) Finally myPdfExporter = Nothing End Try Next End Sub End Module 'copy and paste the pdf export class code here 'code not shown for brevitywww.nxjournaling.com