LAB302
từng bước vững vàng, mở lối tương lai
UPLINK ESTABLISHED // Autodesk > App script
REC_20260603_66ME Chu Đình Quý

iLogic xuất pdf từ thư mục chứa nhiều file idw

DATA_CORE_READY
Dim oApp As Inventor.Application = ThisApplication

' ==========================================
' 1. CHỌN THƯ MỤC CHỨA IDW
' ==========================================
Dim fbd As New System.Windows.Forms.FolderBrowserDialog
fbd.Description = "Chọn thư mục chứa các file IDW cần gộp"
If fbd.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then Return

Dim folderPath As String = fbd.SelectedPath
Dim files() As String = System.IO.Directory.GetFiles(folderPath, "*.idw")
Array.Sort(files)

If files.Length = 0 Then
    MessageBox.Show("Không tìm thấy file IDW nào trong thư mục: " & vbCrLf & folderPath, _
                    "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    Return
End If

' ==========================================
' 2. KHỞI TẠO BIẾN & MASTER DOC (ẢN)
' ==========================================
Dim logLines As New System.Collections.Generic.List(Of String)
Dim failedFiles As New System.Collections.Generic.List(Of String)
Dim totalSheetsCopied As Integer = 0
Dim sheetCounter As Integer = 0

' Tạo Master Document ẩn để gộp trang
Dim masterDoc As DrawingDocument = oApp.Documents.Add(DocumentTypeEnum.kDrawingDocumentObject, "", False)
Dim defaultEmptySheet As Sheet = masterDoc.Sheets.Item(1)
Dim isFirstSheetRemoved As Boolean = False

' ==========================================
' 3. DUYỆT & COPY TẤT CẢ SHEETS
' ==========================================
For Each fileName As String In files
    Dim srcDoc As DrawingDocument = Nothing
    Try
        ' Mở file IDW ẩn
        srcDoc = oApp.Documents.Open(fileName, False)

        If srcDoc Is Nothing Then
            failedFiles.Add(System.IO.Path.GetFileName(fileName) & " (Không mở được)")
            Continue For
        End If

        Dim sheetCount As Integer = srcDoc.Sheets.Count
        If sheetCount = 0 Then
            failedFiles.Add(System.IO.Path.GetFileName(fileName) & " (Không có sheet nào)")
            srcDoc.Close(True)
            Continue For
        End If

        ' Duyệt qua tất cả các sheet trong file nguồn
        For Each sh As Sheet In srcDoc.Sheets
            Try
                ' Copy sheet sang master doc
                sh.CopyTo(masterDoc)
                totalSheetsCopied += 1
                sheetCounter += 1

                ' Sheet vừa copy sẽ tự động nằm ở vị trí cuối cùng
                Dim copiedSheet As Sheet = masterDoc.Sheets.Item(masterDoc.Sheets.Count)

                ' --- TẠO TÊN SHEET ĐỂ LÀM BOOKMARK PDF ---
                ' Cấu trúc Bookmark: [Tên File] - [Tên Sheet Gốc]
                Dim baseFileName As String = System.IO.Path.GetFileNameWithoutExtension(fileName)
                Dim newName As String = baseFileName & " - " & sh.Name

                ' Cắt bớt tên nếu quá dài (Inventor giới hạn độ dài tên sheet)
                If newName.Length > 80 Then newName = newName.Substring(0, 80)

                ' Tránh lỗi trùng tên sheet trong cùng một bản vẽ master
                Try
                    copiedSheet.Name = newName
                Catch
                    copiedSheet.Name = newName & "_" & sheetCounter.ToString("D3")
                End Try

                ' --- XÓA SHEET TRẮNG LÚC ĐẦU (CHỈ THỰC HIỆN 1 LẦN) ---
                If Not isFirstSheetRemoved AndAlso masterDoc.Sheets.Count > 1 Then
                    Try
                        defaultEmptySheet.Delete()
                        isFirstSheetRemoved = True
                    Catch
                        ' Bỏ qua nếu có lỗi hệ thống không lường trước
                    End Try
                End If

                logLines.Add("  ✔ Đã gộp: " & copiedSheet.Name)

            Catch exSheet As Exception
                logLines.Add("  ✘ Lỗi Sheet '" & sh.Name & "': " & exSheet.Message)
                failedFiles.Add(System.IO.Path.GetFileName(fileName) & " | Sheet: " & sh.Name)
            End Try
        Next

        ' Đóng file nguồn (không lưu)
        srcDoc.Close(True)
        logLines.Add("[OK] " & System.IO.Path.GetFileName(fileName) & " (" & sheetCount & " sheets)")

    Catch exFile As Exception
        logLines.Add("[LỖI] " & System.IO.Path.GetFileName(fileName) & ": " & exFile.Message)
        failedFiles.Add(System.IO.Path.GetFileName(fileName) & " (Ngoại lệ File)")
        Try
            If srcDoc IsNot Nothing Then srcDoc.Close(True)
        Catch
        End Try
    End Try
Next

' ==========================================
' 4. KIỂM TRA TRƯỚC KHI EXPORT PDF
' ==========================================
If totalSheetsCopied = 0 Then
    MessageBox.Show("Không có sheet nào được copy. Không thể xuất PDF!", "Lỗi", _
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
    masterDoc.Close(True)
    Return
End If

' ==========================================
' 5. EXPORT MASTER DOC SANG PDF
' ==========================================
Dim pdfPath As String = folderPath & "\ALL_DRAWINGS_MERGED.pdf"
Dim exportOK As Boolean = False

Try
    Dim pdfAddIn As TranslatorAddIn = oApp.ApplicationAddIns.ItemById("{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}")
    If pdfAddIn Is Nothing Then Throw New Exception("Không tìm thấy PDF Add-In trong Inventor.")

    Dim ctx As TranslationContext = oApp.TransientObjects.CreateTranslationContext()
    ctx.Type = IOMechanismEnum.kFileBrowseIOMechanism

    Dim opt As NameValueMap = oApp.TransientObjects.CreateNameValueMap()

    If pdfAddIn.HasSaveCopyAsOptions(masterDoc, ctx, opt) Then
        opt.Value("Sheet_Range") = PrintRangeEnum.kPrintAllSheets
        opt.Value("Vector_Resolution") = 400
        opt.Value("All_Color_AS_Black") = False
        opt.Value("Remove_Line_Weights") = False
        ' Inventor mặc định tự động tạo Bookmark dựa theo Name của các Sheet khi xuất nhiều trang
    End If

    Dim dm As DataMedium = oApp.TransientObjects.CreateDataMedium()
    dm.FileName = pdfPath

    ' Xuất file
    pdfAddIn.SaveCopyAs(masterDoc, ctx, opt, dm)
    exportOK = True

Catch exPdf As Exception
    MessageBox.Show("Lỗi khi xuất PDF:" & vbCrLf & exPdf.Message, "Lỗi Export", _
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

' ==========================================
' 6. DỌN DẸP & BÁO CÁO
' ==========================================
Try
    masterDoc.Close(True) ' Đóng Master Doc không lưu
Catch
End Try

' Xây dựng hộp thoại thông báo tóm tắt
Dim summary As String = ""
If exportOK Then
    summary &= "XUẤT PDF THÀNH CÔNG!" & vbCrLf
    summary &= "Đường dẫn: " & pdfPath & vbCrLf
Else
    summary &= "XUẤT PDF THẤT BẠI!" & vbCrLf
End If

summary &= "────────────────────────" & vbCrLf
summary &= "Tổng số file IDW: " & files.Length & vbCrLf
summary &= "Tổng số trang PDF: " & totalSheetsCopied & vbCrLf

If failedFiles.Count > 0 Then
    summary &= vbCrLf & "File/Sheet bị lỗi (" & failedFiles.Count & "):" & vbCrLf
    For Each f As String In failedFiles
        summary &= "  • " & f & vbCrLf
    Next
End If

' Lưu file Text Log
Try
    Dim logPath As String = folderPath & "\export_pdf_log.txt"
    Dim allLog As String = "=== LOG XUẤT PDF GỘP ===" & vbCrLf & _
                           "Thời gian: " & Now.ToString("yyyy-MM-dd HH:mm:ss") & vbCrLf & _
                           "Thư mục: " & folderPath & vbCrLf & vbCrLf & _
                           String.Join(vbCrLf, logLines.ToArray())
    System.IO.File.WriteAllText(logPath, allLog, System.Text.Encoding.UTF8)
    summary &= vbCrLf & "Đã lưu chi tiết log tại: export_pdf_log.txt"
Catch
End Try

MessageBox.Show(summary, "Kết Quả Export", MessageBoxButtons.OK, _
                If(exportOK, MessageBoxIcon.Information, MessageBoxIcon.Warning))