Magicodes.IEを用いたPDF帳票出力の実践ガイド

Magicodes.IE.Pdf を活用して、柔軟なPDF帳票出力を実現する方法を解説します。

主な機能と属性設定

PdfExporterAttribute は、出力全体のレイアウトや書式を制御します。代表的なプロパティは以下の通りです:

  • Name:ドキュメントタイトル
  • FontSize:基本フォントサイズ
  • Orientation:縦横方向(Portrait / Landscape)
  • PaperKind:用紙サイズ(デフォルトはA4)
  • IsWriteHtml:中間HTML出力の有無
  • HeaderSettings / FooterSettings:ヘッダー・フッターのカスタマイズ

列見出しの表示名は、ExporterHeaderAttributeDisplayName プロパティで指定可能です。Display 属性も同様の用途ですが、優先度は低くなります。

導入手順

まず、必要なNuGetパッケージをインストールします:

Install-Package Magicodes.IE.Pdf

シンプルなテーブル出力

以下のようにDTOクラスを定義し、データリストを渡すだけで標準テンプレートによる表形式出力が可能です:

[PdfExporter(Name = "生徒情報一覧")]
public class PupilRecord
{
    [ExporterHeader(DisplayName = "氏名")]
    public string FullName { get; set; }

    [ExporterHeader(DisplayName = "年齢")]
    public int YearsOld { get; set; }
}

// 出力処理
var generator = new PdfExporter();
await generator.ExportListByTemplate("output.pdf", new List<PupilRecord>
{
    new() { FullName = "山田太郎", YearsOld = 17 },
    new() { FullName = "鈴木花子", YearsOld = 18 }
});

カスタムテンプレートによる帳票出力

HTMLテンプレートを用いて、領収書のような自由レイアウトのPDFを作成できます:

<html>
<head>
    <style>
        body { font-family: 'MS Mincho'; }
        .header { text-align: center; font-size: 20pt; }
        .field-label { width: 15%; text-align: right; padding-right: 1em; }
    </style>
</head>
<body>
    <div class="header">@Model.CompanyTitle</div>
    <p>受取日:@Model.TransactionDate.ToString("D")</p>
    <table>
        <tr>
            <td class="field-label">金額</td>
            <td>¥@Model.Amount.ToString("N0")</td>
        </tr>
        <tr>
            <td class="field-label">宛名</td>
            <td>@Model.RecipientName</td>
        </tr>
    </table>
</body>
</html>

対応するDTOと出力コード:

public class PaymentVoucher
{
    public string CompanyTitle => "株式会社サンプル";
    public DateTime TransactionDate { get; set; }
    public decimal Amount { get; set; }
    public string RecipientName { get; set; }
}

// テンプレート読み込みと出力
var templateContent = await File.ReadAllTextAsync("voucher.html");
var exporter = new PdfExporter();
await exporter.ExportByTemplate("voucher.pdf", new PaymentVoucher
{
    TransactionDate = DateTime.Now,
    Amount = 15000,
    RecipientName = "テスト顧客"
}, templateContent);

複数帳票の一括出力

ループ構造をテンプレートに組み込むことで、複数レコードを1ファイルにまとめて出力できます:

@foreach (var item in Model.Transactions)
{
    <div style="page-break-after: always;">
        <h3>領収書 No. @item.SerialNumber</h3>
        <p>金額: ¥@item.Amount.ToString("N0")</p>
        <p>日付: @item.IssueDate.ToString("D")</p>
    </div>
}

バッチ処理用のモデルと実行コード:

public class BatchExportModel
{
    public List<TransactionRecord> Transactions { get; set; } = new();
}

var batchData = new BatchExportModel();
for (int i = 1; i <= 5; i++)
{
    batchData.Transactions.Add(new TransactionRecord
    {
        SerialNumber = $"INV-{i:D4}",
        Amount = 10000 * i,
        IssueDate = DateTime.Now.AddDays(-i)
    });
}

var batchTemplate = await File.ReadAllTextAsync("batch_template.html");
await new PdfExporter().ExportByTemplate("batch_output.pdf", batchData, batchTemplate);

環境依存の注意点

このライブラリは wkhtmltopdf を内部で使用しており、Windows/Linux 両対応です。ただし、Linux 環境(特にコンテナ内)では日本語フォントの事前インストールが必要な場合があります。Dockerfile などで適切なフォントパッケージを追加してください。

タグ: Magicodes.IE PdfExporter wkhtmltopdf

5月15日 17:42 投稿