LoginSignup
1
1

More than 3 years have passed since last update.

PowerShellでPDFを右綴じに変換 (w/iTextSharp)

Last updated at Posted at 2020-03-18

PowerShellからiTextSharpを呼び出してPDFを右綴じに変換します。

下準備

まず始めに itextsharp.dll を入手してください。

nugetするのが本筋ですが、スクリプトを置くフォルダにlibというサブフォルダを作って、その下に itextsharp.dll を入れる方式です。
よって、下記スクリプトもこの前提です。

スクリプト

以下を ConvertTo-RightBinding.ps1 として保存。

ConvertTo-RightBinding.ps1
# Convert PDF To Right-bindings
param(
    [parameter(mandatory=$true)][string]$sourceDataPath,
    [parameter(mandatory=$true)][string]$destinationPath
)

function ConvertTo-RightBinding($sourceDataPath, $destinationPath)
{
    # path of itextsharp.dll
    [System.Reflection.Assembly]::LoadFrom((Join-Path (Split-Path $script:MyInvocation.MyCommand.Path) "\lib\itextsharp.dll")) | Out-Null

    $pr = New-Object iTextSharp.text.pdf.PdfReader([string]$sourceDataPath)
    if($pr.IsEncrypted()){
        Write-Error("Encrypted: ", $sourceDataPath)
    }

    try {
        $fs = New-Object System.IO.FileStream([string]$destinationPath, [System.IO.FileMode]::Create)
        $st = New-Object iTextSharp.text.pdf.PdfStamper($pr, $fs)

        $st.AddViewerPreference([iTextSharp.text.pdf.PdfName]::DIRECTION, [iTextSharp.text.pdf.PdfName]::R2L)

        $st.Close()
        $fs.Close()
        $pr.Close()
    }
    catch {
        Write-Error("Error: " + $_.Exception)
    }
}

ConvertTo-RightBinding (Convert-Path $sourceDataPath) $destinationPath

使用例

PowerShellを立ち上げて、

PS> ConvertTo-RightBinding.ps1 PDFファイル (Join-Path $PWD 出力先PDFファイル)

みたいに使います。

C#でバイナリを作らなくていいのは便利だね。

1
1
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
1