如何使用 Windows Powershell 自动打印为 PDF

Tha*_*ama 6 powershell

我有一个文件夹,其中有n个word、excel和powerpoint文件,扩展名为“.Doc、.Docx、.xls、.xlsx、.ppt等”。应使用 Microsoft 打印到 PDF 选项将这些文件的内容转换为 PDF,而不改变其格式,并且输出文件应自动保存到扩展名为 .pdf 的文件夹中。

我已经尝试过使用下面的脚本,它只打印 PDF 中的空白页。

请帮忙。

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()
}
Run Code Online (Sandbox Code Playgroud)

谢谢。

小智 4

请参阅: 使用 Powershell Out-Printer 到文件时控制输出位置

使用本机 Powershell cmdlet,您必须解决唯一的问题,即没有 -output 参数 - 但它是在那里处理的。

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
}
Run Code Online (Sandbox Code Playgroud)