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関連

    [Office]「タッチ」タブの正体!?

    最近下記のようにOfficeのリボンにある「タッチ」タブについての質問…

  2. Office関連

    Excel 2016 Previewで追加された新しい関数

    ※ 下記情報はOffice 2016 Preview版を元にしています…

  3. Office関連

    ランダムな文字列を生成するVBAマクロ

    文字数を指定して0-9,A-Zまでのランダムな文字列を生成するマクロで…

コメント

  • コメント (0)

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

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

Time limit is exhausted. Please reload CAPTCHA.

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

Translate

最近の記事

アーカイブ

PAGE TOP