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 2013 アイコン一覧(I)

    ・Office 2013 アイコン一覧 NUM…

  2. Office関連

    オフィス祭り 2018 in 東京に参加しました。

    先日書いた下記記事の通り、9月15日(土)に品川にある日本マイクロソフ…

  3. Office関連

    Outlookを使ってGmail送信を行うVBAマクロ

    下記G Suite アップデート ブログにある通り、今年の6月には“安…

  4. Office関連

    ポータブル デバイスからファイルをコピーするVBAマクロ

    mougにあった質問関連のメモです。ポータブル デバイスか…

コメント

  • コメント (0)

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

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

Time limit is exhausted. Please reload CAPTCHA.

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

Translate

最近の記事

アーカイブ

PAGE TOP