Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations KootK on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

PDF Export Jorunal Help

Status
Not open for further replies.

JSDesign

Automotive
Aug 6, 2014
9
Hello,

I currently use the journal code below to export PDF's of my assembly. Everything works great but one improvement I am trying to get help with is how to hide all sub components before exporting the sheet. Reason being is currently it exports the pdf and some purchased parts which we do not want to show are showing and we have to go back and fix individual files. this becomes time consuming and would greatly improve our process.

Thanks,

Code:
Option Strict Off
Imports System
Imports System.IO
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports NXOpen
Imports NXOpen.UF
Imports NXOpen.Assemblies


Module Module1

    Dim theSession As Session = Session.GetSession

    Sub Main()

        If IsNothing(theSession.Parts.Display) Then
            MessageBox.Show("Active Part Required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return
        End If

        Dim lw As ListingWindow = theSession.ListingWindow
        lw.Open()

        Dim workPart As Part = theSession.Parts.Work

        Dim myAsmInfo As New NXJ_Assembly_info
        myAsmInfo.Part = workPart

        Dim myPdfExporter As New NXJ_PdfExporter
        myPdfExporter.PickExportFolder()

        myPdfExporter.Part = workPart
        Try
            myPdfExporter.Commit()
        Catch ex As NXException

        End Try

        For Each tempPart As Part In myAsmInfo.AllUniqueParts
            myPdfExporter.Part = tempPart

            ChangeDisplayPart(tempPart)

            Try
                myPdfExporter.Commit()
            Catch ex As Exception
                MessageBox.Show("Error:" & ControlChars.CrLf & ex.GetType.ToString & " : " & ex.Message, "PDF export error", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End Try

        Next

        ChangeDisplayPart(workPart)
        myPdfExporter = Nothing


    End Sub

    Sub ChangeDisplayPart(ByVal newPart As Part)

        Dim markId1 As Session.UndoMarkId
        markId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Change Display Part")

        Dim partLoadStatus1 As PartLoadStatus
        Dim status1 As PartCollection.SdpsStatus
        status1 = theSession.Parts.SetDisplay(newPart, False, False, partLoadStatus1)

        partLoadStatus1.Dispose()

    End Sub

End Module


'*******************************************************************************


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.
    '
    'Public Properties:
    '  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}.pdf
    '           default value (TC): <current user's Documents folder>\<DB_PART_NO>_<DB_PART_REV>{_preliminary}.pdf
    '  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: the current work part
    '  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.pdf
    '           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
    '  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
    '  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


#End Region


#Region "properties and private variables"

    Private Const Version As String = "0.4.0"

    Private _theSession As Session = Session.GetSession
    Private _theUfSession As UFSession = UFSession.GetUFSession
    Private lg As LogFile = _theSession.LogFile

    Private _drawingSheets As New List(Of Drawings.DrawingSheet)
    Private _exportFile As String = ""
    Private _partUnits As Integer
    Private _watermarkTextFinal As String = ""

    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 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 & ".pdf")
            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")
            _outputPdfFile = value
            lg.WriteLine("  outputPdfFile: " & value)
            'update _outputFolder
            Me.OutputFolder = Me.GetParentPath(_outputPdfFile)
            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()
            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 _sortSheetsByName As Boolean = True
    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
                Me.SortDrawingSheets()
            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()

        lg.WriteLine("")
        lg.WriteLine("~ NXJournaling.com: Start of drawing to PDF journal ~")
        lg.WriteLine("  ~~ Version: " & Version & " ~~")
        lg.WriteLine("  ~~ Timestamp of run: " & DateTime.Now.ToString & " ~~")
        lg.WriteLine("PdfExporter Sub New()")

        'determine if we are running under TC or native
        _theUfSession.UF.IsUgmanagerActive(_isTCRunning)
        lg.WriteLine("IsTcRunning: " & _isTCRunning.ToString)

        lg.WriteLine("exiting Sub New")
        lg.WriteLine("")

    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 .pdf 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
                lg.WriteLine("  folder browser dialog cancel button pressed")
                lg.WriteLine("  current output path: " & Me.OutputFolder)
            End If
        End With

        lg.WriteLine("exiting Sub PickExportFolder")
        lg.WriteLine("")

    End Sub

    Public Sub PromptPreliminaryPrint()

        lg.WriteLine("Sub PromptPreliminaryPrint")

        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 Commit()

        lg.WriteLine("Sub ExportSheetsToPdf")
        lg.WriteLine("  number of drawing sheets in part file: " & _drawingSheets.Count.ToString)

        Dim sheetCount As Integer = 0
        Dim sheetsExported As Integer = 0

        For Each tempSheet As Drawings.DrawingSheet In _drawingSheets

            sheetCount += 1

            lg.WriteLine("  working on sheet: " & tempSheet.Name)
            lg.WriteLine("  sheetCount: " & sheetCount.ToString)

            '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 sheetCount = 1 Then
                'export to file system
                If File.Exists(_outputPdfFile) Then
                    lg.WriteLine("  specified output file already exists")
                    If Me.OverwritePdf Then
                        Try
                            lg.WriteLine("  user chose to overwrite existing pdf file")
                            File.Delete(_outputPdfFile)
                        Catch ex As Exception
                            'rethrow error?
                            lg.WriteLine("  ** error while attempting to delete existing pdf file")
                            lg.WriteLine("  " & ex.GetType.ToString & " : " & ex.Message)
                        End Try
                    Else
                        'file exists, overwrite option is set to false - do nothing
                        lg.WriteLine("  specified pdf file exists, user chose not to overwrite")
                        lg.WriteLine("  exiting Sub ExportSheetsToPdf")
                        lg.WriteLine("")
                        Exit Sub
                    End If
                End If

            End If

            '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
                lg.WriteLine("  calling Sub ExportPdf")
                lg.WriteLine("")
                Me.ExportPdf()
            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
                System.Diagnostics.Process.Start(Me.OutputPdfFileName)
                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")
        Else

            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 & ".pdf")
                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 & ".pdf")
                End If

            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
            _drawingSheets.Add(tempSheet)
        Next

    End Sub

    Private Sub SortDrawingSheets()

        If _sortSheetsByName Then
            Me.GetDrawingSheets()
            _drawingSheets.Sort(AddressOf CompareSheetNames)
        End If

    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()

        lg.WriteLine("Sub ExportPdf")

        Dim printPDFBuilder1 As PrintPDFBuilder

        printPDFBuilder1 = _thePart.PlotManager.CreatePrintPdfbuilder()
        printPDFBuilder1.Scale = 1.0
        printPDFBuilder1.Colors = PrintPDFBuilder.Color.BlackOnWhite
        printPDFBuilder1.Size = PrintPDFBuilder.SizeOption.ScaleFactor
        printPDFBuilder1.RasterImages = True
        printPDFBuilder1.ImageResolution = PrintPDFBuilder.ImageResolutionOption.Medium

        If _thePart.PartUnits = BasePart.Units.Inches Then
            lg.WriteLine("  part units: English")
            printPDFBuilder1.Units = PrintPDFBuilder.UnitsOption.English
        Else
            lg.WriteLine("  part units: Metric")
            printPDFBuilder1.Units = PrintPDFBuilder.UnitsOption.Metric
        End If

        If _textAsPolylines Then
            lg.WriteLine("  output text as polylines")
            printPDFBuilder1.OutputText = PrintPDFBuilder.OutputTextOption.Polylines
        Else
            lg.WriteLine("  output text as text")
            printPDFBuilder1.OutputText = PrintPDFBuilder.OutputTextOption.Text
        End If

        lg.WriteLine("  useWatermark: " & _useWatermark.ToString)
        If _useWatermark Then
            printPDFBuilder1.AddWatermark = True
            printPDFBuilder1.Watermark = _watermarkTextFinal
        Else
            printPDFBuilder1.AddWatermark = False
            printPDFBuilder1.Watermark = ""
        End If

        lg.WriteLine("  export to TC? " & _exportToTC.ToString)
        If _exportToTC Then
            'output to dataset
            printPDFBuilder1.Relation = PrintPDFBuilder.RelationOption.Manifestation
            printPDFBuilder1.DatasetType = "PDF"
            printPDFBuilder1.NamedReferenceType = "PDF_Reference"
            'printPDFBuilder1.Action = PrintPDFBuilder.ActionOption.Overwrite
            printPDFBuilder1.Action = PrintPDFBuilder.ActionOption.New
            printPDFBuilder1.DatasetName = _exportFile & "_PDF_1"
            lg.WriteLine("  dataset name: " & _exportFile)

            Try
                lg.WriteLine("  printPDFBuilder1.Assign")
                printPDFBuilder1.Assign()
            Catch ex As NXException
                lg.WriteLine("  ** error with printPDFBuilder1.Assign")
                lg.WriteLine("  " & ex.ErrorCode & " : " & ex.Message)
            End Try

        Else
            'output to filesystem
            lg.WriteLine("  pdf file: " & _outputPdfFile)
            printPDFBuilder1.Action = PrintPDFBuilder.ActionOption.Native
            printPDFBuilder1.Append = False
            printPDFBuilder1.Filename = _outputPdfFile

        End If

        printPDFBuilder1.SourceBuilder.SetSheets(_drawingSheets.ToArray)

        Dim nXObject1 As NXObject
        Try
            lg.WriteLine("  printPDFBuilder1.Commit")
            nXObject1 = printPDFBuilder1.Commit()

        Catch ex As NXException
            lg.WriteLine("  ** error with printPDFBuilder1.Commit")
            lg.WriteLine("  " & ex.ErrorCode & " : " & ex.Message)

            'If Me.ExportToTc Then

            '    Try
            '        lg.WriteLine("  trying new dataset option")
            '        printPDFBuilder1.Action = PrintPDFBuilder.ActionOption.New
            '        printPDFBuilder1.Commit()
            '    Catch ex2 As NXException
            '        lg.WriteLine("  ** error with printPDFBuilder1.Commit")
            '        lg.WriteLine("  " & ex2.ErrorCode & " : " & ex2.Message)

            '    End Try

            'End If

        Finally
            printPDFBuilder1.Destroy()
        End Try

        lg.WriteLine("  exiting Sub ExportPdf")
        lg.WriteLine("")

    End Sub

    Private Sub DisplayConfirmationDialog()

        Dim sb As New Text.StringBuilder

        If Me._drawingSheets.Count = 0 Then
            MessageBox.Show("No drawing sheets found in file.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return
        End If

        sb.Append("The following sheets were output to PDF:")
        sb.AppendLine()
        For Each tempSheet As Drawings.DrawingSheet In _drawingSheets
            sb.AppendLine("   " & tempSheet.Name)
        Next
        sb.AppendLine()

        If Not Me.ExportToTc Then
            sb.AppendLine("Open pdf file now?")
        End If

        Dim prompt As String = sb.ToString

        Dim response As DialogResult
        If Me.ExportToTc Then
            response = MessageBox.Show(prompt, Me.OutputPdfFileName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            response = MessageBox.Show(prompt, Me.OutputPdfFileName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
        End If

        If response = DialogResult.Yes Then
            Me.OpenPdf = True
        Else
            Me.OpenPdf = False
        End If

    End Sub


#End Region

End Class

'******************************************************

Public Class NXJ_Assembly_info

#Region "Private Variables"

    Private Const Version As String = "0.1.0"

    Private _theSession As Session = Session.GetSession()
    Private _theUfSession As UFSession = UFSession.GetUFSession

    Private _components As New List(Of Assemblies.Component)
    Private _uniqueParts As New List(Of Part)
    Private _allComponents As New List(Of Assemblies.Component)
    Private _allUniqueParts As New List(Of Part)
    Private _notLoaded As New List(Of String)

    Private lg As LogFile = _theSession.LogFile

#End Region

#Region "Properties"

    Private _isTCRunning As Boolean
    Public ReadOnly Property IsTCRunning() As Boolean
        Get
            Return _isTCRunning
        End Get
    End Property

    Private _thePart As Part = Nothing
    Public Property Part() As Part
        Get
            Return _thePart
        End Get
        Set(ByVal value As Part)
            _thePart = value
            'Me.GetInfo()
            Me.GetAllInfo()
        End Set
    End Property

    Public ReadOnly Property AllComponents() As List(Of Component)
        Get
            Return _allComponents
        End Get
    End Property

    Public ReadOnly Property AllUniqueParts() As List(Of Part)
        Get
            Return _allUniqueParts
        End Get
    End Property

    Public ReadOnly Property Components As List(Of Component)
        Get

            Return _components
        End Get
    End Property

    Public ReadOnly Property UniqueParts As List(Of Part)
        Get
            Return _uniqueParts
        End Get
    End Property

    Public ReadOnly Property NotLoaded As List(Of String)
        Get
            Return _notLoaded
        End Get
    End Property

#End Region

    Public Sub New()

        lg.WriteLine("")
        lg.WriteLine("~ NXJournaling.com: NXJ_Assembly_info object created ~")
        lg.WriteLine("  ~~ Version: " & Version & " ~~")
        lg.WriteLine("  ~~ Timestamp of run: " & DateTime.Now.ToString & " ~~")
        lg.WriteLine("NXJ_Assembly_info Sub New()")

        'determine if we are running under TC or native
        _theUfSession.UF.IsUgmanagerActive(_isTCRunning)
        lg.WriteLine("IsTcRunning: " & _isTCRunning.ToString)

        lg.WriteLine("exiting Sub New")
        lg.WriteLine("")


    End Sub

    Private Sub GetAllInfo()

        'get all component info from assembly (all levels)
        lg.WriteLine("Sub GetAllInfo()")

        Try
            Dim c As ComponentAssembly = Me.Part.ComponentAssembly
            If Not IsNothing(c.RootComponent) Then
                '*** insert code to process 'root component' (assembly file)
                lg.WriteLine("  part has components")
                '*** end of code to process root component
                lg.WriteLine("  calling GetAllComponentChildren")
                GetAllComponentChildren(c.RootComponent)
            Else
                '*** insert code to process piece part, part has no components
                lg.WriteLine("  part has no components")
            End If
        Catch ex As NXException
            lg.WriteLine("Sub GetAllInfo error: " & ex.ErrorCode)
            lg.WriteLine("  " & ex.Message)
        End Try

        lg.WriteLine("exiting Sub GetAllInfo()")

    End Sub

    Private Sub GetAllComponentChildren(ByVal comp As Component)

        For Each child As Component In comp.GetChildren()
            lg.WriteLine(child.DisplayName)
            '*** insert code to process component or subassembly

            If Me.LoadComponent(child) Then

                _allComponents.Add(child)

                Dim tempPart As Part = child.Prototype.OwningPart
                If Not _allUniqueParts.Contains(tempPart) Then
                    _allUniqueParts.Add(tempPart)
                End If

            Else
                'component could not be loaded
            End If
            '*** end of code to process component or subassembly
            If child.GetChildren.Length <> 0 Then
                '*** this is a subassembly, add code specific to subassemblies

                '*** end of code to process subassembly
            Else
                'this component has no children (it is a leaf node)
                'add any code specific to bottom level components

            End If
            Me.GetAllComponentChildren(child)
        Next
    End Sub


    Private Sub GetInfo()

        'get top level component info from assembly (no recursion)
        lg.WriteLine("Sub GetInfo()")

        Try
            Dim c As ComponentAssembly = Part.ComponentAssembly
            If Not IsNothing(c.RootComponent) Then
                '*** insert code to process 'root component' (assembly file)
                lg.WriteLine("  part has components")
                '*** end of code to process root component
                lg.WriteLine("  calling GetComponentChildren")
                Me.GetComponentChildren(c.RootComponent)
            Else
                '*** insert code to process piece part, part has no components
                lg.WriteLine("  part has no components")
            End If
        Catch ex As NXException
            lg.WriteLine("Sub GetInfo error: " & ex.ErrorCode)
            lg.WriteLine("  " & ex.Message)
        End Try

        lg.WriteLine("exiting GetInfo()")

    End Sub

    Private Sub GetComponentChildren(ByVal comp As Component)

        For Each child As Component In comp.GetChildren()
            '*** insert code to process component or subassembly
            _components.Add(child)
            Dim tempPart As Part = child.Prototype.OwningPart
            If Not _uniqueParts.Contains(tempPart) Then
                _uniqueParts.Add(tempPart)
            End If
            '*** end of code to process component or subassembly
            If child.GetChildren.Length <> 0 Then
                '*** this is a subassembly, add code specific to subassemblies

                '*** end of code to process subassembly
            Else
                'this component has no children (it is a leaf node)
                'add any code specific to bottom level components

            End If
        Next
    End Sub

    Private Function LoadComponent(ByVal theComponent As Component) As Boolean

        lg.WriteLine("Sub LoadComponent()")

        Dim thePart As Part = theComponent.Prototype.OwningPart

        Dim partName As String = ""
        Dim refsetName As String = ""
        Dim instanceName As String = ""
        Dim origin(2) As Double
        Dim csysMatrix(8) As Double
        Dim transform(3, 3) As Double

        Try
            If thePart.IsFullyLoaded Then
                'component is fully loaded
            Else
                'component is partially loaded
            End If
            lg.WriteLine("  component: " & theComponent.DisplayName & " is already partially or fully loaded")
            lg.WriteLine("  return: True")
            lg.WriteLine("exiting Sub LoadComponent()")
            lg.WriteLine("")
            Return True
        Catch ex As NullReferenceException
            'component is not loaded
            Try
                lg.WriteLine("  component not loaded, retrieving part information")
                _theUfSession.Assem.AskComponentData(theComponent.Tag, partName, refsetName, instanceName, origin, csysMatrix, transform)
                lg.WriteLine("  component part file: " & partName)

                Dim theLoadStatus As PartLoadStatus
                _theSession.Parts.Open(partName, theLoadStatus)

                If theLoadStatus.NumberUnloadedParts > 0 Then
                    If theLoadStatus.NumberUnloadedParts > 1 Then
                        lg.WriteLine("  problem loading " & theLoadStatus.NumberUnloadedParts.ToString & " components")
                    Else
                        lg.WriteLine("  problem loading 1 component")
                    End If

                    Dim allReadOnly As Boolean = True
                    For i As Integer = 0 To theLoadStatus.NumberUnloadedParts - 1
                        lg.WriteLine("part name: " & theLoadStatus.GetPartName(i))
                        lg.WriteLine("part status: " & theLoadStatus.GetStatus(i))
                        If theLoadStatus.GetStatus(i) = 641058 Then
                            'read-only warning, file loaded ok
                        Else
                            '641044: file not found
                            allReadOnly = False
                            If Not _notLoaded.Contains(partName) Then
                                _notLoaded.Add(partName)
                            End If
                        End If
                        lg.WriteLine("status description: " & theLoadStatus.GetStatusDescription(i))
                        lg.WriteLine("")
                    Next
                    If allReadOnly Then
                        lg.WriteLine("  read-only warnings only")
                        lg.WriteLine("  return: True")
                        Return True
                    Else
                        'warnings other than read-only...
                        lg.WriteLine("  return: False")
                        lg.WriteLine("exiting Sub LoadComponent()")
                        lg.WriteLine("")
                        Return False
                    End If
                Else
                    lg.WriteLine("  component(s) loaded successfully")
                    lg.WriteLine("  return: True")
                    lg.WriteLine("exiting Sub LoadComponent()")
                    lg.WriteLine("")
                    Return True
                End If

            Catch ex2 As NXException
                lg.WriteLine("  Load error: " & ex2.Message)
                lg.WriteLine("  error code: " & ex2.ErrorCode)
                lg.WriteLine("  return: False")
                lg.WriteLine("exiting Sub LoadComponent()")
                lg.WriteLine("")
                If ex2.Message.ToLower = "file not found" Then
                    If Not _notLoaded.Contains(partName) Then
                        _notLoaded.Add(partName)
                    End If
                End If
                Return False
            End Try
        Catch ex As NXException
            lg.WriteLine("  Error in Sub LoadComponent: " & ex.Message)
            lg.WriteLine("  return: False")
            lg.WriteLine("exiting Sub LoadComponent()")
            lg.WriteLine("")
            Return False
        End Try

    End Function

End Class
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor