1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PowerShellでPDFをページごとに分割 (PDFSharp版)

Posted at

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()を使う方が簡単かも。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?