Skip to content

Instantly share code, notes, and snippets.

@gocha
Created March 24, 2021 08:53
Show Gist options
  • Save gocha/5c91371157d7b4a35d79babeaf1889dd to your computer and use it in GitHub Desktop.
Save gocha/5c91371157d7b4a35d79babeaf1889dd to your computer and use it in GitHub Desktop.
ウェブページを PDF に保存 (Headless Chrome を使用)
<#
.SYNOPSIS
ウェブページを PDF に保存
.DESCRIPTION
Headless Chrome を使用してウェブページを PDF に保存します。
.PARAMETER Path
出力される PDF ファイルのパス。
.PARAMETER Uri
エクスポート元のウェブページの URI。
.PARAMETER Proxy
プロキシサーバーの URI。
.PARAMETER NoHeader
PDF にページ情報を示すヘッダーやフッターを出力しません。
.PARAMETER UserDataDir
Chrome の起動時に使用されるユーザーデータディレクトリ。省略時はランダムな一時パスが使用されます。
.PARAMETER ChromePath
Chrome の実行ファイルのパス。省略時は標準的なインストール先パスが使用されます。
.EXAMPLE
C:\PS> Export-WebPageAsPdf -Verbose sample.pdf https://www.chromestatus.com/
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $True)]
[string] $Path,
[Parameter(Mandatory = $True)]
[Uri] $Uri,
[Parameter(Mandatory = $False)]
[Uri] $Proxy,
[Parameter(Mandatory = $False)]
[switch] $NoHeader,
[Parameter(Mandatory = $False)]
[string] $UserDataDir = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), "Export-WebPageAsPdf-$([System.Guid]::NewGuid())"),
[Parameter(Mandatory = $False)]
[string] $ChromePath = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
)
if ([System.IO.Path]::IsPathRooted($Path)) {
$FullPath = $Path
}
else {
$FullPath = [System.IO.Path]::Combine($pwd, $Path)
}
if (Test-Path $FullPath) {
Remove-Item $FullPath
}
$ChromeArguments = @("`"--user-data-dir=$UserDataDir`"", '--headless', '--disable-gpu', '--no-sandbox', "`"--print-to-pdf=$FullPath`"")
if ($PSBoundParameters['Verbose']) {
$ChromeArguments += '--enable-logging'
}
if (-not [string]::IsNullOrEmpty($Proxy)) {
$ChromeArguments += "--proxy-server=$Proxy"
}
if ($NoHeader) {
$ChromeArguments += '--print-to-pdf-no-header'
}
$ChromeArguments += $Uri
$process = Start-Process -FilePath $ChromePath -ArgumentList $ChromeArguments -Wait -PassThru
if ($process.ExitCode -ne 0 -or -not (Test-Path $FullPath)) {
Write-Error "$Path を保存するときにエラーが発生しました。 (終了コード $($process.ExitCode))"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment