5

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.

miken32
  • 42,008
  • 16
  • 111
  • 154
Tharaka Wijerama
  • 73
  • 1
  • 1
  • 6

1 Answers1

3

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
}
upe
  • 1,862
  • 1
  • 19
  • 33
  • Great answer that works. Didn't know about `[System.Windows.Forms.SendKeys]` Note that `$focus` might be tuned if computer is slow... – moutonjr Jun 30 '22 at 08:16
  • 1
    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. – Tilo Oct 03 '22 at 18:14