简体   繁体   English

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

[英]How to Automate Print to PDF with Windows Powershell

I have a folder with n number of word, excel, and powerpoint files with extension ".Doc, .Docx, .xls, .xlsx, .ppt, etc".我有一个包含 n 个单词的文件夹,excel,以及扩展名为“.Doc、.Docx、.xls、.xlsx、.ppt 等”的 powerpoint 文件。 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. 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.我已经尝试使用下面的脚本,它只打印 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.谢谢你。

See: Control output location when using Powershell Out-Printer to a File请参阅: 使用 Powershell 输出打印机到文件时控制 output 位置

Using native Powershell cmdlet, you have to work around the only thing that there is no -output parameter - but it is handled there.使用本机 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM