6

I have a folder with n number of word, excel, and powerpoint files with extension ".Doc, .Docx, .xls, .xlsx, .ppt, etc". The content of these files should be converted to PDF without altering its format using Microsoft Print to PDF option and the output files should be saved to a folder with .pdf extension automatically.

I have already tried using below script and it prints only blank pages in PDF.

Please help.

function ConvertTo-PDF {
    param(
        $TextDocumentPath
    )
    
    Add-Type -AssemblyName System.Drawing
    $doc = New-Object System.Drawing.Printing.PrintDocument
    $doc.DocumentName = $TextDocumentPath
    $doc.PrinterSettings = new-Object System.Drawing.Printing.PrinterSettings
    $doc.PrinterSettings.PrinterName = 'Microsoft Print to PDF'
    $doc.PrinterSettings.PrintToFile = $true
    $file=[io.fileinfo]$TextDocumentPath
    $pdf= [io.path]::Combine($file.DirectoryName, $file.BaseName) + '.pdf'
    $doc.PrinterSettings.PrintFileName = $pdf
    $doc.Print()
    $doc.Dispose()
}

Thank you.

1 Answer 1

4

See: Control output location when using Powershell Out-Printer to a File

Using native Powershell cmdlet, you have to work around the only thing that there is no -output parameter - but it is handled there.

Function Printto-PDF ($filepath) {
       $VerbosePreference = "Continue"
       add-type -AssemblyName microsoft.VisualBasic
       add-type -AssemblyName System.Windows.Forms
       $focus = 2000
       $FilePath = Get-Item $Filepath
       $newfile = $Filepath.basename + '.pdf'
       Start-Process $Filepath.fullname -verb Print | out-printer -name "Microsoft print to PDF"  
       start-sleep -Milliseconds $focus
       [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
       start-sleep -Milliseconds 250
       [System.Windows.Forms.SendKeys]::SendWait($newfile)
       start-sleep -Milliseconds 250
       [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
       start-sleep -Milliseconds 1500
}
Sign up to request clarification or add additional context in comments.

4 Comments

Great answer that works. Didn't know about [System.Windows.Forms.SendKeys] Note that $focus might be tuned if computer is slow...
on tif (win 10) I get a pop up "how do you want to print your pictures" So the above process depends on what Windows show in the right click print dialog.
A clarification, because it was not clear to me immetiately. If you put in the $newFIle the whole path, you can choose where it is saved. :)
I think this requires that you set adobe acrobat as your default reader

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.