簡體   English   中英

使用Powershell對具有printSelectedDiv javascript的網頁進行腳本pdf打印

[英]Script pdf printing of webpage that has printSelectedDiv javascript using Powershell

在幾個腳本中,我在 Powershell 中使用wkhtmltopdf來無頭打印網頁內容的 pdf。 這適用於忙於小部件和 javascript 復雜性的網站,其中 pdf 打印輸出是一團糟。

一個這樣的網頁提供了一個打印按鈕並使用 javascript printSelectedDiv 這將打開 Windows 打印對話框,並將從復雜頁面准確打印所需的 div。

我能夠使用 Powershell 自動單擊並提交打印作業。 但是,我希望像其他幾個腳本一樣在計划任務中以無頭方式執行此操作。

我可以使用 Sendkeys 按如下方式自動打印:

$ie = new-object -ComObject "InternetExplorer.Application"
$requestUri = "https://www.complexpagefullofwidgets.com"
$ie.silent = $true
$ie.navigate($requestUri)
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
$doc = $ie.Document

$pdfPrinter = Get-WmiObject -Class Win32_Printer | Where{$_.Name -eq "Microsoft Print to PDF"}
$pdfPrinter.SetDefaultPrinter() | Out-Null

$printButton = $doc.getElementsByTagName("a") | Where-Object {$_.id -eq "btnPrintList"}
$printButton.click()

Start-Sleep -Second 2

$wshell = New-Object -com WScript.Shell
$wshell.sendkeys("{ENTER}")
Start-Sleep -Milliseconds 500
$wshell.sendkeys("%n")
Start-Sleep -Milliseconds 500
$wshell.sendkeys("c:\temp\temp.pdf")
$wshell.sendkeys("{ENTER}")

是否有更好的腳本控制這個過程而不是發送擊鍵? 我不知道發送擊鍵是否可以在計划任務中可靠地無頭工作(如果有的話)。

如果你想繼續使用 wkhtmltopdf,你可以使用這種方法。

您的代碼完全完成了工作,您需要做的就是調用$printButton.click()方法,然后檢查$ie.DocumentBody.InnerHTML對象將包含您請求的頁面的完整 HTML,因此你可以把它發送到 wkhtmltopdf。

$ie.Document.body.innerHTML > c:\temp\Page.html
& 'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' c:\temp\page.html c:\temp\page.pdf

唯一的問題是解析圖像 URL,您必須替換標簽中的 url,將它們從相對鏈接更改為絕對鏈接,將 \\ 替換為您正在加載的頁面的完整 url。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM