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ページ
- Hello, iTextSharp! – Life like a clown
- http://d.hatena.ne.jp/tt_clown/20111104/itext_sharp
関連Webページ
- [PowerShell]iTextSharpを使ってPDFファイルのページ数を取得する
- //www.ka-net.org/blog/?p=2317
- Acrobatを使ってPDFファイルを結合するVBAマクロ
- //www.ka-net.org/blog/?p=5866

 
  















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