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



我有一个文件夹,里面有n个word、excel和powerpoint文件,扩展名为"。doc、。docx、。xls、。xlsx、。ppt等"。使用Microsoft Print to 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()
}

谢谢。

参见:使用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
}

最新更新