Save As PDF macro, how to save one or two directories back?

I found a macro online for performing a "save as PDF", but it saves the file under the current working directory. The way our file structure is set up, we have a folder named "PDF" typically one to two directories back. Is there a way to manipulate the existing code so it drops the files under the correct directory?

Here's the existing code:

Sub main()

       

    Set swApp = Application.SldWorks

    Set swModel = swApp.ActiveDoc

   

    ' Strip off SolidWorks drawing file extension (.slddrw)

    ' and add DXF file extension (.dxf)

    sPathName = swModel.GetPathName

    sPathName = Left(sPathName, Len(sPathName) - 6)

    sPathName = sPathName + "pdf"

   

    ' Show current settings

    Debug.Print "DxfMapping             = " & swApp.GetUserPreferenceToggle(swDxfMapping)

    Debug.Print "DXFDontShowMap         = " & swApp.GetUserPreferenceToggle(swDXFDontShowMap)

   

    Debug.Print "DxfVersion             = " & swApp.GetUserPreferenceIntegerValue(swDxfVersion)

    Debug.Print "DxfOutputFonts         = " & swApp.GetUserPreferenceIntegerValue(swDxfOutputFonts)

    Debug.Print "DxfMappingFileIndex    = " & swApp.GetUserPreferenceIntegerValue(swDxfMappingFileIndex)

    Debug.Print "DxfOutputLineStyles    = " & swApp.GetUserPreferenceIntegerValue(swDxfOutputLineStyles)

    Debug.Print "DxfOutputNoScale       = " & swApp.GetUserPreferenceIntegerValue(swDxfOutputNoScale)

       

    Debug.Print "DxfMappingFiles        = " & swApp.GetUserPreferenceStringListValue(swDxfMappingFiles)

   

    Debug.Print "DxfOutputScaleFactor   = " & swApp.GetUserPreferenceDoubleValue(swDxfOutputScaleFactor)

    Debug.Print ""

       

 

    ' Turn off showing of map

    bShowMap = swApp.GetUserPreferenceToggle(swDXFDontShowMap)

    Debug.Print "bShowMap = " & bShowMap

   

    swApp.SetUserPreferenceToggle swDXFDontShowMap, False

       

    bRet = swModel.SaveAs4(sPathName, swSaveAsCurrentVersion, swSaveAsOptions_Silent, nErrors, nWarnings)

    Beep

    If bRet = False Then

        nRetval = swApp.SendMsgToUser2("Problems saving file.", swMbWarning, swMbOk)

    End If

    ' Restore old setting

    swApp.SetUserPreferenceToggle swDXFDontShowMap, bShowMap

End Sub

'----------------------------------------------

SolidworksApi macros
Answers 21
DG
DG 2015-05-12 Best Answer

Replace these lines

<p><span style="color: #2873ee;">            sPathName = swModel.GetPathName</span></p><p style="min-height: 8pt; padding: 0px; padding-left: 30px;"><span style="color: #2873ee;"> </span> </p><p style="padding-left: 30px;"><span style="color: #2873ee;">    sPathName = Left(sPathName, Len(sPathName) - 6)</span></p><p style="min-height: 8pt; padding: 0px; padding-left: 30px;"><span style="color: #2873ee;"> </span> </p><p style="padding-left: 30px;"><span style="color: #2873ee;">    sPathName = sPathName + "pdf"</span></p>

With

<p>     Dim sFileName As String</p><p>    sFileName = Mid(swModel.GetPathName, InStrRev(swModel.GetPathName, "\") + 1)</p><p>    sFileName = Left(sFileName, InStrRev(sFileName, ".") - 1)</p><p>    </p><p>    sPathName = Left(swModel.GetPathName, InStrRev(swModel.GetPathName, "PDF\") + 3)</p><p>    sPathName = sPathName & sFileName & ".PDF"</p>
SJ
SJ 2015-05-12

Hi Deepak:

Thanks for the quick reply. I tried your snippet and it failed to work, it saved the PDF under C:\

The actual directory name isn't PDF, but rather 04 PDFs, so I changed your one line to read

sPathName = Left(swModel.GetPathName, InStrRev(swModel.GetPathName, "04 PDFs\") + 3)

instead of

sPathName = Left(swModel.GetPathName, InStrRev(swModel.GetPathName, "PDF\") + 3)

Here's an actual path for example

Drawings live here - C:\EPDM_Vault\Projects\101046\01 SolidWorks\30000_Mining\Drawings

PDFs to go here - C:\EPDM_Vault\Projects\101046\04 PDFs

Any suggestions?

DG
DG 2015-05-12

If your folder structure is same for all and provided PDF folder exists then you can use

<p><span style="color: #333333; font-family: Verdana, 'Verdana Ref', Geneva, Tahoma, sans-serif;">sPathName = Left(swModel.GetPathName, InStrRev(swModel.GetPathName, </span><strong style="font-family: Verdana, 'Verdana Ref', Geneva, Tahoma, sans-serif; color: #333333;">"04 PDFs\"</strong><span style="color: #333333; font-family: Verdana, 'Verdana Ref', Geneva, Tahoma, sans-serif;">) + 7) ' 7 is character count for <strong style="font-family: Verdana, 'Verdana Ref', Geneva, Tahoma, sans-serif; color: #333333;">04 PDFs</strong></span></p>

If the folder structure is different then it could become little tricky. I'll see if I can find the apporpirate codes that could find the PDF string in the path.

Else simple option would be to use a file browse option which will ask you for the file path when saving PDF.

KR
KR 2015-05-12

This will save the the current model with a new extension up a certain number of directories from the current model directory. The new extension and number of directories above are specified in the constants at top.

<p>Const DIR_ABOVE As Integer = 2</p><p>Const NEW_EXTENSION As String = "PDF"</p><p></p><p>Sub main()</p><p>    Dim swApp As SldWorks.SldWorks</p><p>    Dim swModel As SldWorks.ModelDoc2</p><p>    </p><p>    Set swApp = Application.SldWorks</p><p>    Set swModel = swApp.ActiveDoc</p><p>    </p><p>    ' Create new file name</p><p>    Dim strModelPath As String</p><p>    Dim strSavePath As String</p><p>    Dim strFileName As String</p><p>    Dim vSplit As Variant</p><p>    </p><p>    strModelPath = swModel.GetPathName</p><p>    strFileName = Right(strModelPath, Len(strModelPath) - InStrRev(strModelPath, "\"))</p><p>    vSplit = Split(strFileName, ".")</p><p>    strFileName = vSplit(0) & "." & NEW_EXTENSION</p><p>    </p><p>    ' Create new directory</p><p>    vSplit = Split(strModelPath, "\")</p><p>    </p><p>    Dim i As Integer</p><p>    For i = 0 To UBound(vSplit) - DIR_ABOVE - 1</p><p>        strSavePath = strSavePath & vSplit(i) & "\"</p><p>    Next i</p><p>    strSavePath = strSavePath & strFileName</p><p>    </p><p>    Debug.Print "Original path: " & strModelPath</p><p>    Debug.Print "New save path: " & strSavePath</p><p>    </p><p>    ' Save</p><p>    bRet = swModel.Extension.SaveAs(strSavePath, swSaveAsCurrentVersion, _</p><p>        swSaveAsOptions_Silent, Nothing, Empty, Empty)</p><p></p><p>    If bRet = False Then swApp.SendMsgToUser "Problems saving file."</p><p>End Sub</p>

Keith

SolidWorks API Training

SJ
SJ 2015-05-12

I see. I'm lucky then, because our folder structure will always be "04 PDFs" where the file has to save to.

OK, I fixed the character as you noted (I understand how that works now, thank you), but its still not working right. When I run the macro, the PDF gets saved to the C drive and renames to EPDM101046-731063.pdf (where "101046-731063" is the drawing name).
So two things are happening:

1) EPDM is being added to the front of the file name.

2) The file is saving in the wrong directory.

Any insight?

SJ
SJ 2015-05-12

Thanks for reply Keith, I didn't try this code, because it sounds like it only saves the file "x" number of directories back.

I need it to go back "x" number of directories until it finds the folder named "04 PDFs" and then saves the PDF under that directory.

IK
IK 2015-05-12

​then change this piece of code

  1.     For i = 0 To UBound(vSplit)  - 1 
  2.         strSavePath = strSavePath & vSplit(i) & "\" 
  3.         If dir(strSavePath & "04 PDFs", vbDirectory) <> "" then
  4.        strSavePath = strSavePath & "04 PDFs &"\"
  5.         exit for
  6.         end if
  7.     Next i 
SJ
SJ 2015-05-12

Hi Ivana:

Thanks for the suggestion. I swapped the code you recommended but still no cigar, but it was closer.

The file ended up saving to:

C:\EPDM_Vault\Projects\101046\01 SolidWorks\

But, I need it to go here

C:\EPDM_Vault\Projects\101046\04 PDFs\

Any more suggestions?

'------------------------------------------------------------------

'

' Preconditions: Drawing file is open.

'

' Postconditions: DXF file is generated, overwriting any existing file.

'

'------------------------------------------------------------------

Option Explicit

    Dim swApp                   As SldWorks.SldWorks

    Dim swModel                 As SldWorks.ModelDoc2

    Dim sPathName               As String

    Dim nErrors                 As Long

    Dim nWarnings               As Long

    Dim nRetval                 As Long

    Dim bShowMap                As Boolean

    Dim bRet                    As Boolean

    Const DIR_ABOVE As Integer = 2

    Const NEW_EXTENSION As String = "PDF"

     

    Sub main()

        Dim swApp As SldWorks.SldWorks

        Dim swModel As SldWorks.ModelDoc2

         

        Set swApp = Application.SldWorks

        Set swModel = swApp.ActiveDoc

         

        ' Create new file name

        Dim strModelPath As String

        Dim strSavePath As String

        Dim strFileName As String

        Dim vSplit As Variant

         

        strModelPath = swModel.GetPathName

        strFileName = Right(strModelPath, Len(strModelPath) - InStrRev(strModelPath, "\"))

        vSplit = Split(strFileName, ".")

        strFileName = vSplit(0) & "." & NEW_EXTENSION

         

        ' Create new directory

        vSplit = Split(strModelPath, "\")

         

        Dim i As Integer

    For i = 0 To UBound(vSplit) - DIR_ABOVE - 1

            strSavePath = strSavePath & vSplit(i) & "\"

            If Dir(strSavePath & "04 PDFs") <> "" Then

    strSavePath = strSavePath & "04 PDFs &" \ ""

    Exit For

    End If

        Next i

        strSavePath = strSavePath & strFileName

         

        Debug.Print "Original path: " & strModelPath

        Debug.Print "New save path: " & strSavePath

         

        ' Save

        bRet = swModel.Extension.SaveAs(strSavePath, swSaveAsCurrentVersion, _

            swSaveAsOptions_Silent, Nothing, Empty, Empty)

     

        If bRet = False Then swApp.SendMsgToUser "Problems saving file."

    End Sub

IK
IK 2015-05-12

​this is wrong, I am typing on iPad, so I can't check syntax

strSavePath = strSavePath & "04 PDFs &" \ ""

it has to be : strSavePath = strSavePath & "04 PDFs\"

SJ
SJ 2015-05-12

I fixed that and still no go.

It looks like it's going back up the folders until it can see the directory "04 PDFs\",

but then dumps the file under the last working directory "01 SoldWorks\" instead of then dumping it in "04 PDFs\"

But I don't know any better...

Any other suggestions?

JS
JS 2015-05-12

If you can, consider switching from VBA to VB.NET or C#.  You have much more powerful APIs at your disposal that can eliminate all of the ugly hacking and slashing of strings:

<p>            ModelDoc2 mDoc = swApp.ActiveDoc as ModelDoc2;</p><p>            string filePath = mDoc.GetPathName();</p><p>            string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);</p><p>            DirectoryInfo parentDirInfo = new DirectoryInfo(filePath);</p><p>            while (parentDirInfo != null && !parentDirInfo.Name.Equals("04 PDFs"))</p><p>            {</p><p>                parentDirInfo = parentDirInfo.Parent;</p><p>            }</p><p>            if (parentDirInfo == null)</p><p>            {</p><p>                MessageBox.Show("No parent PDF directory found");</p><p>                return;</p><p>            }</p><p>            string newFileName = parentDirInfo.FullName + Path.DirectorySeparatorChar + filenameWithoutExtension + ".pdf";</p><p>            ExportPdfData exportData = swApp.GetExportFileData((int)swExportDataFileType_e.swExportPdfData) as ExportPdfData;</p><p>            exportData.ExportAs3D = false;</p><p>            exportData.SetSheets((int)swExportDataSheetsToExport_e.swExportData_ExportAllSheets, null);</p><p>            int errors = 0;</p><p>            int warnings = 0;</p><p>            ModelDocExtension mDocExt = mDoc.Extension;</p><p>            mDocExt.SaveAs(newFileName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, 0, exportData, ref errors, ref warnings);</p><p>            if (errors != 0)</p><p>            {</p><p>                MessageBox.Show("Errors saving PDF: " + errors);</p><p>            }</p><p>            if (warnings != 0)</p><p>            {</p><p>                MessageBox.Show("Warnings saving PDF: " + warnings);</p><p>            }</p>
KR
KR 2015-05-12

This will find a folder called FOLDER_NAME in one of the parent directories, starting with the root directory and working forward.

<p>Const NEW_EXTENSION As String = "PDF"</p><p>Const FOLDER_NAME As String = "04 PDFs"</p><p></p><p>Sub main()</p><p>    </p><p>    If FOLDER_NAME = Empty Then Exit Sub</p><p>    </p><p>    Dim swApp As SldWorks.SldWorks</p><p>    Dim swModel As SldWorks.ModelDoc2</p><p>    </p><p>    Set swApp = Application.SldWorks</p><p>    Set swModel = swApp.ActiveDoc</p><p>    </p><p>    ' Create new file name</p><p>    Dim strModelPath As String</p><p>    Dim strSavePath As String</p><p>    Dim strSaveFolder As String</p><p>    Dim strFileName As String</p><p>    Dim vSplit As Variant</p><p>    </p><p>    strModelPath = swModel.GetPathName</p><p></p><p>    If swModel.GetPathName = Empty Then</p><p>        swApp.SendMsgToUser "Please save model."</p><p>        Exit Sub</p><p>    End If</p><p></p><p>    strFileName = Right(strModelPath, _</p><p>        Len(strModelPath) - InStrRev(strModelPath, "\"))</p><p>    vSplit = Split(strFileName, ".")</p><p>    strFileName = vSplit(0) & "." & NEW_EXTENSION</p><p>    </p><p>    ' Create new directory</p><p>    vSplit = Split(strModelPath, "\")</p><p>    </p><p>    Dim intDirAbove As Integer</p><p>    Dim i As Integer</p><p>    Dim bFound As Boolean</p><p>    </p><p>    bFound = False</p><p>    </p><p>    For i = 0 To UBound(vSplit) - intDirAbove</p><p>        strSaveFolder = strSaveFolder & vSplit(i) & "\"</p><p>        </p><p>        If Dir(strSaveFolder & FOLDER_NAME, vbDirectory) <> Empty Then</p><p>            bFound = True</p><p>            Exit For</p><p>        End If</p><p>        </p><p>    Next i</p><p>    </p><p>    If bFound = False Then</p><p>        swApp.SendMsgToUser "Failed to find correct folder."</p><p>        Exit Sub</p><p>    End If</p><p>    </p><p>    strSavePath = strSaveFolder & FOLDER_NAME & "\" & strFileName</p><p>    </p><p>    Debug.Print "Original path: " & strModelPath</p><p>    Debug.Print "New save path: " & strSavePath</p><p>    </p><p>    ' Save</p><p>    bRet = swModel.Extension.SaveAs(strSavePath, swSaveAsCurrentVersion, _</p><p>        swSaveAsOptions_Silent, Nothing, Empty, Empty)</p><p>    </p><p>    If bRet = False Then swApp.SendMsgToUser "Problems saving file."</p><p>End Sub</p>

Keith

SolidWorks API Tutorials

DG
DG 2015-05-13

Sorry as I had not tested the macro completely. Try this one (though it is also not full proof but it is working as desired). Tested it by creating the same folder structure on C drive.

I've also added to check if the 04 PDFs directory/folder is not there then create it.

SJ
SJ 2015-05-13

Thank you Sir!

That did it.

Quick Question

If I change all instances of "PDF" with "DWG" and "04 PDFs" with "03 AutoCAD" (and update the character count), will it save a DWG to "03 AutoCAD"?

DG
DG 2015-05-13

I think it should work provided you've same folder structure.

I had removed the mapping and other DXF options as those were not required for PDF.

KR
KR 2015-05-13

For those looking for a more flexible solution: The macro I posted yesterday afternoon​​ doesn't depend on the folder structure or folder names. It will always find the folder with the specified name in one of the parent directories or the current directory.

Keith

SolidWorks API Tutorials

JF
JF 2018-01-30

Deepak,

What would I need to change in your macro posted here to be able to save to a set file path?

Jeffrey

DG
DG 2018-01-30

Remove the highlighted lines

And then replace this part of the line with you path. For e.g. "C:\Users\DEEPAK\Desktop\"

The path has to be in quotes and should have \ in the end before " like the example.

comment imagecomment imagecomment imagecomment image
JF
JF 2018-01-30

Thank you! That worked perfect!

AA
AA 2019-01-31

Thanks so much Deepak!

Your macro helped a lot. I tweaked it a little to fit my needs.

I keep the PDF next to the drawings but in a separate folder.

Like this:

  • Project
    • 3D
    • Drawings
      • pdf

The macro now does this automatically.

Maybe it will help someone.

DG
DG 2019-01-31

​, thanks for sharing