2017-06-08 82 views
2

我想使用Powershell将包含PDF文件的文件夹转换为XPS文件。由于系统限制,我无法下载任何像iTextSharp这样的第三方软件来完成这项工作。使用Powershell将PDF打印到XPS

我已经能够让Powershell打开文档并打开XPS的打印窗口,但名称始终为空。是否有可能使新文件名与原始文件名匹配?

此外,该过程如何实现自动化,因此不需要用户输入(即输入文件名或按下打印)?最后,是否可以更改打印目录?

Get-ChildItem -path $pdf_filepath -recurse -include *.pdf | ForEach-Object {Start-Process -FilePath $_.fullname -Verb Print -PassThru | %{sleep 10;$_} } 

回答

0

这是我会怎么做:

#Define the directory containing your .pdf files 
$mydir="$env:USERPROFILE\Desktop\New folder" 
function print_files($mydir){ 
    #The purpose of this counter is to number your .xps files 
    Get-ChildItem $mydir -Filter *.pdf -Recurse | Foreach-Object { 
     #For each .pdf file in that directory, continue 
     same_time $_.FullName 
    } 
} 
#The following function keeps checking for a new window called "Save Print Output As". When the window shows up, it enters the name of the file and press ENTER. 
function enter_my_names($fullname){ 
    $wshell = New-Object -ComObject wscript.shell; 
    while($wshell.AppActivate('Save Print Output As') -ne $true){ 
     $wshell.AppActivate('Save Print Output As') 
    } 
    $basename = [io.path]::GetFileNameWithoutExtension($fullname) 
    #This is where the name is actually entered 
    $wshell.SendKeys("$basename") 
    $wshell.SendKeys("{ENTER}") 
} 
#The following function launches simultaneously a print job on the input file and a function waiting for the print job to show up to name the file. 
workflow same_time{ 
    Param(
     $fullname 
    ) 
    parallel{ 
     Start-Process -FilePath $fullname –Verb Print -PassThru 
     enter_my_names($fullname) 
    } 
} 
#MAIN PROGRAM 
#Here the script saves your current printer as default 
$defprinter = Get-WmiObject -Query "Select * from Win32_Printer Where Default=$true" 
#Queries for a XPS printer 
$printer = Get-WmiObject -Query "Select * from Win32_Printer Where Name='Microsoft XPS Document Writer'" 
#Sets the XPS printer as Default 
$printer.SetDefaultPrinter() 
#Starts the main job 
print_files($mydir) 
#Sets the old default printer back as default again 
$defprinter.SetDefaultPrinter() 
#This is a small delay to be sure everything is completed before closing Adobe Reader. You can probably shorten it a bit 
sleep 5 
#Finally, close Adobe Reader 
Get-Process "acrord32" | Stop-Process 

干杯!

+0

print_files函数获取目录中文件的名称并将这些名称存储在C:\ c文件夹中供以后使用。 enter_my_names函数打开窗口,调用存储在C:\ c中的名称并用新名称打印该文件。 工作流调用enter_my_names函数并行运行以使其更快。 最后,print_files实际上将文件打印到指定的目录,然后从C:\ c中删除不需要的信息。 我是否准确地描述了这一点?我遇到了后续文件试图覆盖的问题,因为名称没有更改。 – MrKGado

+0

@MrKGado我修改了脚本。现在它绝对更好。它也被评论,以便您可以更好地了解每个部分。它需要安装Adobe Reader,希望它不是一个主要问题。祝你有个愉快的日子 –

+0

这非常有帮助,谢谢!如何使用Get-ChildItem来收集原始文件名,以便打印的文件具有相同的名称?我尝试修改第6和第8行以及其他$计数器块,但最终每次都会打破它。我用 'Get-ChildItem -Path $ mydir -Recurse -Name'来收集文件名,但我一直无法找到如何将它们链接到打印保存名称。有什么想法吗? – MrKGado