Office関連

[PowerShell]iTextSharpを使ってPDFファイルを結合する

mougにあった質問「2つのPDFファイルを結合するには」の回答用に書いた、PowerShellからiTextSharpを使ってPDFファイルを結合するコードです。

[System.Reflection.Assembly]::LoadFrom("C:\System\iTextSharp\itextsharp.dll");
$reader1 = New-Object iTextSharp.text.pdf.PdfReader("C:\Test\Sample01.pdf");
$reader2 = New-Object iTextSharp.text.pdf.PdfReader("C:\Test\Sample02.pdf");
$fs = New-Object System.IO.FileStream("C:\Test\Output.pdf", [System.IO.FileMode]::OpenOrCreate);
$copy = New-Object iTextSharp.text.pdf.PdfCopyFields($fs);
$copy.AddDocument($reader1);
$copy.AddDocument($reader2);
$copy.Close();
$fs.Close();
$reader1.Close();
$reader2.Close();

iTextSharpはPowerShellからも簡単に使えて便利ですね!
ちなみに、上記コードをVBAから-Commandオプションを使って処理を実行するようにしたのが下記コードになります。

Option Explicit

Public Sub Sample()
  Dim v As Variant '結合元PDFファイル
  
  v = Array( _
        "C:\Test\Sample01.pdf", _
        "C:\Test\Sample02.pdf", _
        "C:\Test\Sample03.pdf" _
      )
  MergePDF v, "C:\Test\Output.pdf"
End Sub

Private Sub MergePDF(ByVal InputFilePath As Variant, _
                     ByVal OutputFilePath As String)
'iTextSharpを使ってPDFファイルを結合
  Dim com As String
  Dim i As Long
  Const DllFilePath As String = "C:\System\iTextSharp\itextsharp.dll" 'itextsharp.dllファイルのパス
  
  com = "powershell -Command "
  com = com & "[System.Reflection.Assembly]::LoadFrom('" & DllFilePath & "');"
  For i = LBound(InputFilePath) To UBound(InputFilePath)
    com = com & "$reader" & i & " = New-Object iTextSharp.text.pdf.PdfReader('" & InputFilePath(i) & "');"
  Next
  com = com & "$fs = New-Object System.IO.FileStream('" & OutputFilePath & "', [System.IO.FileMode]::OpenOrCreate);"
  com = com & "$copy = New-Object iTextSharp.text.pdf.PdfCopyFields($fs);"
  For i = LBound(InputFilePath) To UBound(InputFilePath)
    com = com & "$copy.AddDocument($reader" & i & ");"
  Next
  com = com & "$copy.Close();"
  com = com & "$fs.Close();"
  For i = LBound(InputFilePath) To UBound(InputFilePath)
    com = com & "$reader" & i & ".Close();"
  Next
  VBA.Shell com, vbNormalNoFocus
End Sub

バッチ処理を行うのであればPowerShellでコードを書けば良いので、敢えてVBAを使う必要は無さそうですが、既存のマクロにPDFファイルの結合処理を組み込みたいときには使えるかもしれません。

参考Webページ

関連Webページ

Google ドライブ プラグイン for Microsoft Officeを使ってみた。前のページ

Acrobatを使ってPDFファイルを結合するVBAマクロ次のページ

関連記事

  1. Office関連

    ページ毎に処理を行うWordマクロ

    Wordのマクロで「ページ毎に○○したい」という要望があったので、簡単…

  2. Office関連

    「図のリセット」を実行するExcelマクロ

    Msdn フォーラムに「Excel2010-VBA 画像「図の書式設定…

  3. Office関連

    [PowerPoint]テーブルを「変形」して値の変化を強調

    前回の記事と同じく、Insider版のバージョン 1903 (ビルド …

  4. Office関連

    Re: 【Wordマクロ】Word起動時に、前回終了時に開いていたファイルを表示

    Word MVPの新田さんがブログで面白い記事を書かれていました。…

  5. Office関連

    メールを閉じたときに指定したフォルダに移動するOutlookマクロ

    先日Twitterで @akashi_keirin さんが下記ツイート…

  6. Office関連

    [Excel Services ECMAScript]セルにデータを入力する。

    埋め込んだExcelワークブックのセルにデータを入力するコードです。…

コメント

  • コメント (0)

  • トラックバックは利用できません。

  1. この記事へのコメントはありません。

Time limit is exhausted. Please reload CAPTCHA.

※本ページはプロモーションが含まれています。

Translate

最近の記事

アーカイブ

PAGE TOP