PowerShellからPDFSharpを呼び出してPDFをページごとに分割します。
オリジナル(拙作)は
https://qiita.com/acknpop/items/de56f3f83403cc0e1985
ですが、iTextSharpの利用が信条的に受け入れがたい人のために。
下準備
まず始めに pdfsharp.dll を入手してください。
nugetするのが本筋ですが、下記はスクリプトを置くフォルダにlibというサブフォルダを作って、その下に pdfsharp.dll を入れる方式です。
nupkgは単にzip圧縮しているだけなので、拡張子をzipに書き換えてやれば展開して中身を取り出せます。
スクリプト
以下を Split-Pages.ps1 として保存。
Split-Pages.ps1
# Split PDF pages
param(
[parameter(mandatory=$true)][string]$sourceDataPath,
[string]$destinationPath
)
function Split-Pages($sourceDataPath, $destinationPath)
{
# path of pdfsharp.dll
[System.Reflection.Assembly]::LoadFrom((Join-Path (Split-Path $script:MyInvocation.MyCommand.Path) "\lib\PdfSharp.dll")) | Out-Null
$pr = [PdfSharp.Pdf.IO.PdfReader]
$mode = [PdfSharp.Pdf.IO.PdfDocumentOpenMode]
$input = $pr::Open([string]$sourceDataPath, $mode::Import)
if([bool]$destinationPath){
$path = Convert-Path $destinationPath
}
else{
$path = Split-Path -Parent $sourceDataPath
}
$fname = [System.IO.Path]::GetFileNameWithoutExtension($sourceDataPath)
$ext = [System.IO.Path]::GetExtension($sourceDataPath)
try {
$pagecount = $input.PageCount
$padding = [string]$pagecount
for($i = 0; $i -lt $pagecount; $i++) {
$pn = [string]($i + 1)
$destinationPath = Join-Path $path ($fname + "_p" + $pn.PadLeft($padding.Length, "0") + $ext)
$doc = New-Object PdfSharp.Pdf.PdfDocument
$doc.AddPage($input.Pages[$i]) | Out-Null
$doc.Save([string]$destinationPath)
}
$input.Close()
}
catch {
Write-Error("Error: " + $_.Exception)
}
}
Split-Pages (Convert-Path $sourceDataPath) $destinationPath
使用例
PowerShellを立ち上げて、
PS> Split-Pages.ps1 元PDFファイル 出力先フォルダ
みたいに使います。
出力先フォルダを指定しない場合は元PDFファイルと同じフォルダに分割したPDFを保存します。
あとがき
PDFの読み込みは、上記の方法でなくFromFile()を使う方が簡単かも。