他人から入手したPDFファイルに対してPdfDocument.LoadFromStreamAsync
メソッドを試すと、うまく読み取れないPDFファイルが意外と多い。
# PowerShell 5.1, Windows 11 (2025年5月頃)Set-StrictMode -Version Latest Add-Type -AssemblyName PresentationFramework Add-Type -AssemblyName System.Runtime.WindowsRuntime $null= [Windows.Data.Pdf.PdfDocument, Windows.Data, ContentType = WindowsRuntime] # AsTask$methodInfo_AsTask_PdfDoc_IAsyncOp_CancelToken= $( [System.WindowsRuntimeSystemExtensions].GetMethods() |Where-Object { $_.Name -eq"AsTask" } |Where-Object { $pis=$_.GetParameters() $pis.Length -eq2 -and$pis[0].ParameterType.Name -eq'IAsyncOperation`1' -and$pis[1].ParameterType.Name -eq'CancellationToken' } ).MakeGenericMethod(@([Windows.Data.Pdf.PdfDocument])) # PDFファイルのパスを取得$fPath=& { $ofd=New-Object -TypeName Microsoft.Win32.OpenFileDialog -Property @{ Filter="PDF File|*.pdf" Multiselect =$false } if ($ofd.ShowDialog()) { $ofd.FileNames[0] } } $fStream=[System.IO.File]::Open($fPath,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite -bor[System.IO.FileShare]::Delete) $raStream=[System.IO.WindowsRuntimeStreamExtensions]::AsRandomAccessStream($fStream) # PdfDocument.LoadFromStreamAsync メソッド$iAsyncOp_PdfDoc=[Windows.Data.Pdf.PdfDocument]::LoadFromStreamAsync($raStream,"password") $cancelTokenSrc=[System.Threading.CancellationTokenSource]::new() # AsTask$task_PdfDoc=$methodInfo_AsTask_PdfDoc_IAsyncOp_CancelToken.Invoke($null, @($iAsyncOp_PdfDoc,$cancelTokenSrc.Token)) try { if ($task_PdfDoc.Wait(15000)) { $pdfDoc=$task_PdfDoc.Result # PDF文書のページ数などを表示$pdfDoc|Format-Table|Out-String -Width80 -Stream|Where-Object { $_ -ne"" } |Write-Host -ForegroundColor Yellow } else { $cancelTokenSrc.Cancel() } } catch { $_|Write-Host -ForegroundColor Red if ($_.Exception.InnerException -is[System.AggregateException]) { "System.AggregateException"|Write-Host -ForegroundColor Yellow $_.Exception.InnerException |Format-List -Force|Out-String -Width80 -Stream|Where-Object { $_ -ne"" } |Write-Host -ForegroundColor Yellow } } $raStream.Dispose() $fStream.Dispose()