2011年1月28日金曜日

iTextSharpでPDFファイル結合

using iTextSharp.text;
using iTextSharp.text.pdf;

//出力ファイルが存在している場合は削除
//1番目のファイルが合体するファイル
if (File.Exists(args[0].ToString()))
{
File.Delete(args[0].ToString());
}

Document doc = null; // 出力ファイルDocument
PdfCopy copy = null; // 出力ファイルPdfCopy

try
{
//-------------------------------------------------------------------------------------
// ファイル件数分、ファイル結合
//-------------------------------------------------------------------------------------
for (int i = 1; i < args.Length; i++)
{
// リーダー取得
PdfReader reader = new PdfReader(args[i].ToString());

// 入力ファイル1を出力ファイルの雛形にする
if (i == 1)
{
// Document作成
doc = new Document(reader.GetPageSizeWithRotation(1));

// 出力ファイルPdfCopy作成
copy = new PdfCopy(doc, new FileStream(args[0].ToString(), FileMode.Create));

// 出力ファイルDocumentを開く
doc.Open();

// 文章プロパティ設定
doc.AddKeywords((string)reader.Info["Keywords"]);
doc.AddAuthor((string)reader.Info["Author"]);
doc.AddTitle((string)reader.Info["Title"]);
doc.AddCreator((string)reader.Info["Creator"]);
doc.AddSubject((string)reader.Info["Subject"]);
}

// PDFコンテンツを取得、copyオブジェクトに追加
for (int iPageCnt = 1; iPageCnt <= reader.NumberOfPages; iPageCnt++)
{
PdfImportedPage page = copy.GetImportedPage(reader, iPageCnt);
copy.AddPage(page);
}

// フォーム入力を結合
PRAcroForm form = reader.AcroForm;
if (form != null)
copy.CopyAcroForm(reader);

// リーダーを閉じる
reader.Close();
}
}
finally
{
if (copy != null)
copy.Close();

if (doc != null)
doc.Close();
}

0 件のコメント:

コメントを投稿