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 アドイン

    OfficeJS Snippet Explorerを使って新しいOffice アドインを体験する。

    前回の記事と打って変わって元のOffice アドインの記事に戻ります(…

  2. アイコン一覧

    Office 2013 アイコン一覧(N)

    ・Office 2013 アイコン一覧 NUM…

  3. Office アドイン

    [Office用アプリ]JavaScript API for Office ライブラリ v1.1

    2014/01/24 追加記事を書きました。・JavaScript…

  4. Excel

    Google TTSで文字列を読み上げるマクロ

    2012/02/09 追記:関連記事・Google翻訳…

  5. Office関連

    [リボン・カスタマイズ]グループの表示・非表示をトグルボタンで切り替える。

    数年前に書いた記事に下記コメントをいただきました。Excelに…

コメント

  • コメント (0)

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

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

Time limit is exhausted. Please reload CAPTCHA.

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

Translate

最近の記事

アーカイブ

PAGE TOP