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

标签 windows powershell printtopdf

我有一个文件夹,其中包含 n 个 word、excel 和 powerpoint 文件,扩展名为“.Doc、.Docx、.xls、.xlsx、.ppt 等”。这些文件的内容应转换为 PDF,而无需使用 Microsoft Print to 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()
}

谢谢。

最佳答案

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

使用 native 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
}

关于windows - 如何使用 Windows Powershell 自动打印为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65760455/

相关文章:

puppeteer - 表情符号在 Chrome Headless 的 PDF 输出中转换为灰色

c - 通过 Cygwin 运行可执行文件

c++ - 使用C++导入注册表文件

windows - 通过命令行配置windows服务

javascript - 覆盖 javascript/jquery 中的 CMD+N 或 CTRL+N 快捷键?

powershell - RDS快照可以跨AWS账户传输吗?

powershell - 解释 Powershell [void] 行为

powershell - 新提示和 Powershell -run as 和 -nonewwindow 问题的多个输入