Explanation of the Code:
Initialization: The code first initializes the SolidWorks application and gets the currently active document using swApp.ActiveDoc.
Check for Open Document: It checks whether a document is currently open. If not, it displays a warning message.
Set the PDF Save Path: The file path where the PDF should be saved is specified. You can modify this path as required.
Export PDF Data Object: The GetExportFileData(2) method is used to create a PDF export object (2 indicates PDF export).
Save the Document as PDF: The SaveAs3 method is called to save the document in PDF format, and the function checks if the operation is successful.
Important Points:
Make sure the file path in the filePath variable is correct and accessible. You can also modify it to dynamically select a folder based on the document name or location.
The .SaveAs3 method is used here, which is compatible with most SolidWorks versions.
This macro will save the PDF with the same name as the active document in the specified directory.
' Save the currently active document as a PDF
Dim swApp As Object
Dim swModel As SldWorks.ModelDoc2
Dim swExportPDFData As SldWorks.ExportPdfData
Dim filePath As String
Dim errors As Long
Dim warnings As Long
Sub main()
' Get the SolidWorks application object
Set swApp = Application.SldWorks
' Get the currently active model document
Set swModel = swApp.ActiveDoc
' Check if a document is open
If swModel Is Nothing Then
MsgBox "No document is open. Please open a document to save as PDF.", vbExclamation, "No Document"
Exit Sub
End If
' Set the file path to save the PDF
filePath = "C:UsersYourUsernameDocuments" & swModel.GetTitle() & ".pdf"
' Create an ExportPDFData object
Set swExportPDFData = swApp.GetExportFileData(2) ' 2 is for PDF export
' Export the document as a PDF
If swModel.SaveAs3(filePath, 0, 0, errors, warnings) = False Then
MsgBox "Failed to save the document as PDF. Please check the file path and permissions.", vbCritical, "Save Error"
Else
MsgBox "Document successfully saved as PDF at: " & filePath, vbInformation, "Save Success"
End If
End Sub
To export a drawing or model in SolidWorks to a PDF using VBA, you can use the following approach. This macro automates the process of saving a currently open document (part, assembly, or drawing) as a PDF file in the specified location.
Steps to Create the VBA Macro:
Open SolidWorks and make sure a drawing or part/assembly is open.
Go to Tools > Macro > New.
Save the macro with a .swp extension and give it a name (e.g., SaveAsPDF.swp).
The VBA editor will open. Copy and paste the following code:
VBA Code to Export as PDF: