Last active
September 8, 2016 14:04
-
-
Save Stephanevg/82928b1af35e9812ae632180beebe692 to your computer and use it in GitHub Desktop.
Print a webpage with powershell. More information here -> http://powershelldistrict.com/print-webpage-pdf-powershell/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Print-WebPageToPDF{ | |
<# | |
.SYNOPSIS | |
Prints a specefic webPage to PDF. | |
.DESCRIPTION | |
If no fileName is given, it will print the file name with the current date & time | |
.EXAMPLE | |
Will print a file called powershelldistrict.pdf to the path C:\temp\print | |
Print-WebPageToPDF -WebSiteURL 'http://powershelldistrict.com' -Path C:\temp\print -FileName 'powershelldistrict.pdf' | |
.EXAMPLE | |
Print a file with a timestamp from when the job was launched. EG: 20160818-113329.pdf | |
Print-WebPageToPDF -WebSiteURL 'http://powershelldistrict.com' -Path C:\temp\print | |
.NOTES | |
-Author: Stephane van Gulick | |
-contact : @stephanevg | |
.LINK | |
http://www.powershelldistrict.com | |
#> | |
[cmdletBinding()] | |
Param( | |
$WebSiteURL, | |
[ValidateScript({ | |
(get-Item $_ ).PSIsContainer | |
})]$Path = 'C:\temp\print\', | |
[String]$FileName = (get-date -uformat '%Y%m%d-%T').Replace(":","") + ".pdf", | |
[switch]$ShowWindow | |
) | |
try{ | |
$ExportPath = join-Path -Path $Path -ChildPath $FileName | |
$ie=new-object -com internetexplorer.application | |
if ($showWindow){ | |
$ie.Visible = $true | |
}else{ | |
$ie.Visible = $false | |
} | |
$ie.navigate($WebSiteURL) | |
$PDFCreator = New-Object -ComObject PDFCreator.JobQueue | |
while ($ie.ReadyState -ne 4){ | |
write-verbose " ReadyState: $($ie.ReadyState). waiting 2sec more.." | |
start-sleep 2 | |
} | |
write-verbose "Page Loaded" | |
#start-sleep -seconds 5 | |
#A dely of 5 seconds is mandatory To avoid the following Error message : Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100 (DRAGDROP_E_NOTREGISTERED)) | |
$ie.execWB(6,2) | |
$PDFCreator.Initialize() | |
while ($PDFCreator.count -lt 1){ | |
write-verbose " No Print jobs found: $($PDFCreator.count). waiting 2sec more.." | |
start-sleep 2 | |
} | |
write-verbose "Print job found: $($PDFCreator.count). waiting 2sec more.." | |
#start-sleep -seconds 10 | |
$PJ = $PDFCreator.NextJob | |
$PJ.SetProfileSetting('ShowProgress',$false) | |
$PJ.SetProfileSetting('OpenViewer',$false) | |
$PJ.ConvertTo($ExportPath) | |
}catch{ | |
$_ | |
}Finally{ | |
$PDFCreator.ReleaseCom() | |
$ie.quit() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment