LoginSignup
2
1

【C#VB.NET】PDF文書に表を作成

Posted at

表は、通常のテキストよりも視覚的にデータを提示することができます。 PDF文書に表を挿入することで、読者はデータ間の関係を理解しやすくなり、その結果、データに基づいて文書を深く理解することができます。 さらに、表は視覚的にも魅力的です。 表の書式を設定することで、読者に深い印象を残すことができるのです。 この記事では、Free Spire.PDF for .NETを使ってPDF文書に表を作成する方法を紹介します。

Free Spire.PDF for .NETは、PDF文書で表を扱うためにPdfTablePdfGridという2つのクラスを提供しています。 それぞれの違いは以下の通りです。

PdfTable PdfGrid
書式
イベント経由で設定可能、APIは未対応。 API経由で設定可能。
API 経由で設定可能(StringFormat)。 API経由で設定可能(StringFormat)。
セル イベント経由で設定可能、APIは未対応。 API経由で設定可能。
その他
水平方向のセルの結合 未対応。 API経由で設定可能。
垂直方向のセルの結合 イベント経由で設定可能、API は未対応。 API経由で設定可能。
ネストされた表 イベント経由で設定可能、API は未対応。 API経由で設定可能。
イベント BeginCellLayout, EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout

依存関係の追加

Free Spire.PDF for .NETの依存関係は、公式ウェブサイトから手動でダウンロードするか、NuGet Package Manageで検索するか、パッケージマネージャーコンソールで次のコードを使用して追加することができます。

PM> Install-Package FreeSpire.PDF

PdfTableクラスでPDF文書に表を作成する

PdfTableクラスを使って、簡単な書式の表を作成します。 詳しい手順は以下の通りです。

  • PdfDocument のオブジェクトを作成します。
  • PdfDocument.Pages.Add() メソッドを使用して、ページを追加します。
  • PdfTable のオブジェクトを作成します。
  • PdfTable を通して表のスタイルを設定します。
  • PdfTable を通して表にデータを挿入します。
  • PdfTable.BeginRowLayout イベントで、表の行の高さと色を設定します。
  • PdfTable.Draw() メソッドを使用して、ページ上に表を描画します。
  • PdfDocument.SaveToFile() メソッドを使用して、文書を保存します。

C#

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
using System;
using System.Data;
using System.Drawing;

namespace CreatePDFTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //PdfDocumentのオブジェクトを作成する
            PdfDocument doc = new PdfDocument();

            //ページを追加する
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));

            //PdfTableのオブジェクトを作成する
            PdfTable table = new PdfTable();

            //ヘッダーとその他のセルのフォントを設定する
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("HarmonyOS Sans SC", 12f, FontStyle.Regular), true);
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("HarmonyOS Sans SC Medium", 12f, FontStyle.Bold), true);

            //DataTableのオブジェクトを作成する
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("番号");
            dataTable.Columns.Add("名前");
            dataTable.Columns.Add("部門");
            dataTable.Columns.Add("役職");
            dataTable.Columns.Add("レベル");
            dataTable.Rows.Add(new string[] { "1", "デビッド", "開発部", "部長", "1" });
            dataTable.Rows.Add(new string[] { "3", "続橋 友朗", "人事部", "部長", "1" });
            dataTable.Rows.Add(new string[] { "4", "大野下 幸子", "営業部", "部長", "1" });
            dataTable.Rows.Add(new string[] { "7", "村田 結織", "営業部", "一般社員", "2" });
            dataTable.Rows.Add(new string[] { "9", "戌井 悠真", "人事部", "一般社員", "2" });
            dataTable.Rows.Add(new string[] { "11", "今井 光順", "開発部", "一般社員", "2" });

            //データテーブルを表のデータソースとして設定する
            table.DataSource = dataTable;

            //表ヘッダーを表示する(デフォルトではヘッダーは表示されません)
            table.Style.ShowHeader = true;

            //表ヘッダーの文字色と背景色を設定する
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray;
            table.Style.HeaderStyle.TextBrush = PdfBrushes.White;

            //表ヘッダーのテキスト配置を設定する
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

            //その他のセルのテキスト配置を設定する
            for (int i = 0; i < table.Columns.Count; i++)
            {
                table.Columns[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            }

            //イベントを申し込む
            table.BeginRowLayout += Table_BeginRowLayout;

            //ページに表を描画する
            table.Draw(page, new PointF(0, 30));

            //PDF文書を保存する
            doc.SaveToFile("PdfTable.pdf");
            doc.Dispose();
        }

        //イベント ハンドラ
        private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            //行の高を設定する
            args.MinimalHeight = 20f;

            //行の背景色を置き換える
            if (args.RowIndex < 0)
            {
                return;
            }
            if (args.RowIndex % 2 == 1)
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.LightGray;
            }
            else
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.White;
            }
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Imports System
Imports System.Data
Imports System.Drawing

Namespace CreatePDFTable
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'PdfDocumentのオブジェクトを作成する
            Dim doc As PdfDocument = New PdfDocument()

            'ページを追加する
            Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, New PdfMargins(40))

            'PdfTableのオブジェクトを作成する
            Dim table As PdfTable = New PdfTable()

            'ヘッダーとその他のセルのフォントを設定する
            table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("HarmonyOS Sans SC", 12.0F, FontStyle.Regular), True)
            table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("HarmonyOS Sans SC Medium", 12.0F, FontStyle.Bold), True)

            'DataTableのオブジェクトを作成する
            Dim dataTable As DataTable = New DataTable()
            dataTable.Columns.Add("番号")
            dataTable.Columns.Add("名前")
            dataTable.Columns.Add("部門")
            dataTable.Columns.Add("役職")
            dataTable.Columns.Add("レベル")
            Dim String() As DataTable.Rows.Add(New
            {
            	 "1", "デビッド", "開発部", "部長", "1" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "3", "続橋 友朗", "人事部", "部長", "1" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "4", "大野下 幸子", "営業部", "部長", "1" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "7", "村田 結織", "営業部", "一般社員", "2" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "9", "戌井 悠真", "人事部", "一般社員", "2" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "11", "今井 光順", "開発部", "一般社員", "2" 
            }
)
 
            'データテーブルを表のデータソースとして設定する
            table.DataSource = dataTable

            '表ヘッダーを表示する(デフォルトではヘッダーは表示されません)
            table.Style.ShowHeader = True

            '表ヘッダーの文字色と背景色を設定する
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray
            table.Style.HeaderStyle.TextBrush = PdfBrushes.White

            '表ヘッダーのテキスト配置を設定する
            table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)

            'その他のセルのテキスト配置を設定する
            Dim i As Integer
            For i = 0 To table.Columns.Count - 1 Step i + 1
                table.Columns(i).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
            Next

            'イベントを申し込む
            table.BeginRowLayout += Table_BeginRowLayout()

            'ページに表を描画する
            table.Draw(page, New PointF(0, 30))

            'PDF文書を保存する
            doc.SaveToFile("PdfTable.pdf")
            doc.Dispose()
        End Sub

        'イベント ハンドラ
        Private Shared Sub Table_BeginRowLayout(ByVal sender As Object, ByVal args As BeginRowLayoutEventArgs)
            '行の高を設定する
            args.MinimalHeight = 20.0F

            '行の背景色を置き換える
            If args.RowIndex < 0 Then
                Return
            End If
            If args.RowIndex % 2 = 1 Then
                args.CellStyle.BackgroundBrush = PdfBrushes.LightGray
            Else
                args.CellStyle.BackgroundBrush = PdfBrushes.White
            End If
        End Sub
    End Class
End Namespace

PdfTableクラスでPDF文書に表を作成する

PdfGridクラスでPDF文書内に表を作成する

PdfGridクラスには、複雑な書式の表を作成するためのより多くの機能があります。 詳細な手順は次のとおりです。

  • PdfDocument のオブジェクトを作成します。
  • PdfDocument.Pages.Add() メソッドを使用して、ページを追加します。
  • PdfGrid のオブジェクトを作成します。
  • PdfGrid.Style プロパティを使って表のスタイルを設定します。
  • PdfGrid.Rows.Add() メソッドを使用して、表に行を追加します。
  • PdfGridRow.Cells[index].Value プロパティを使って、指定したセルにデータを挿入します。
  • PdfGridRow.RowSpan または PdfGridRow.ColumnSpan プロパティを使用してセルを垂直方向または水平方向に結合します。
  • PdfGridRow.Cells[index].StringFormatPdfGridRow.Cells[index].Style プロパティを使用して、指定したセルの書式を設定します。
  • PdfGrid.Draw() メソッドを使用して、ページ上に表を描画します。
  • PdfDocument.SaveToFile() メソッドを使用して、文書を保存します。

C#

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using System;
using System.Drawing;

namespace CreatePDFGrid
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //PdfDocumentのオブジェクトを作成する
            PdfDocument doc = new PdfDocument();

            //ページを追加する
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));

            //PdfGridのオブジェクトを作成する
            PdfGrid grid = new PdfGrid();

            //セルの塗りつぶしを設定する
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

            //フォントを設定する
            grid.Style.Font = new PdfTrueTypeFont(new Font("HarmonyOS Sans SC", 13f, FontStyle.Regular), true);

            //行を追加する
            PdfGridRow row1 = grid.Rows.Add();
            PdfGridRow row2 = grid.Rows.Add();
            PdfGridRow row3 = grid.Rows.Add();
            PdfGridRow row4 = grid.Rows.Add();
            grid.Columns.Add(4);

            //列の幅を取得する
            foreach (PdfGridColumn col in grid.Columns)
            {
                col.Width = 110f;
            }

            //指定したセルにデータを書き込む
            row1.Cells[0].Value = "ご注文とお支払いの状況";
            row2.Cells[0].Value = "注文番号";
            row2.Cells[1].Value = "日付";
            row2.Cells[2].Value = "顧客名";
            row2.Cells[3].Value = "支払いの有無";
            row3.Cells[0].Value = "00223";
            row3.Cells[1].Value = "2022年06月02日";
            row3.Cells[2].Value = "ZOプロパティ";
            row3.Cells[3].Value = "支払い済み";
            row4.Cells[0].Value = "00224";
            row4.Cells[1].Value = "2022年06月03日";
            row4.Cells[3].Value = "未払い";

            //列をまたいでセルをマージする
            row1.Cells[0].ColumnSpan = 4;

            //行をまたいでセルをマージする
            row3.Cells[2].RowSpan = 2;

            //指定したセルのテキスト配置を設定する
            row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);

            //指定したセルの背景色を設定する
            row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Orange;
            row4.Cells[3].Style.BackgroundBrush = PdfBrushes.LightGray;

            //枠線の書式を設定する
            PdfBorders borders = new PdfBorders();
            borders.All = new PdfPen(Color.Orange, 0.8f);
            foreach (PdfGridRow pgr in grid.Rows)
            {
                foreach (PdfGridCell pgc in pgr.Cells)
                {
                    pgc.Style.Borders = borders;
                }
            }

            //ページに表を描画する
            grid.Draw(page, new PointF(0, 30));

            //PDF文書を保存する
            doc.SaveToFile("PdfGrid.pdf");
            doc.Dispose();
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Grid
Imports System
Imports System.Drawing

Namespace CreatePDFGrid
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'PdfDocumentのオブジェクトを作成する
            Dim doc As PdfDocument = New PdfDocument()

            'ページを追加する
            Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, New PdfMargins(40))

            'PdfGridのオブジェクトを作成する
            Dim grid As PdfGrid = New PdfGrid()

            'セルの塗りつぶしを設定する
            grid.Style.CellPadding = New PdfPaddings(1, 1, 1, 1)

            'フォントを設定する
            grid.Style.Font = New PdfTrueTypeFont(New Font("HarmonyOS Sans SC", 13.0F, FontStyle.Regular), True)

            '行を追加する
            Dim row1 As PdfGridRow = grid.Rows.Add()
            Dim row2 As PdfGridRow = grid.Rows.Add()
            Dim row3 As PdfGridRow = grid.Rows.Add()
            Dim row4 As PdfGridRow = grid.Rows.Add()
            grid.Columns.Add(4)

            '列の幅を取得する
            Dim col As PdfGridColumn
            For Each col In grid.Columns
                col.Width = 110.0F
            Next

            '指定したセルにデータを書き込む
            row1.Cells(0).Value = "ご注文とお支払いの状況"
            row2.Cells(0).Value = "注文番号"
            row2.Cells(1).Value = "日付"
            row2.Cells(2).Value = "顧客名"
            row2.Cells(3).Value = "支払いの有無"
            row3.Cells(0).Value = "00223"
            row3.Cells(1).Value = "2022年06月02日"
            row3.Cells(2).Value = "ZOプロパティ"
            row3.Cells(3).Value = "支払い済み"
            row4.Cells(0).Value = "00224"
            row4.Cells(1).Value = "2022年06月03日"
            row4.Cells(3).Value = "未払い"

            '列をまたいでセルをマージする
            row1.Cells(0).ColumnSpan = 4

            '行をまたいでセルをマージする
            row3.Cells(2).RowSpan = 2

            '指定したセルのテキスト配置を設定する
            row1.Cells(0).StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
            row3.Cells(2).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)

            '指定したセルの背景色を設定する
            row1.Cells(0).Style.BackgroundBrush = PdfBrushes.Orange
            row4.Cells(3).Style.BackgroundBrush = PdfBrushes.LightGray

            '枠線の書式を設定する
            Dim borders As PdfBorders = New PdfBorders()
            borders.All = New PdfPen(Color.Orange, 0.8F)
            Dim pgr As PdfGridRow
            For Each pgr In grid.Rows
                Dim pgc As PdfGridCell
                For Each pgc In pgr.Cells
                    pgc.Style.Borders = borders
                Next
            Next

            'ページに表を描画する
            grid.Draw(page, New PointF(0, 30))

            'PDF文書を保存する
            doc.SaveToFile("PdfGrid.pdf")
            doc.Dispose()
        End Sub
    End Class
End Namespace

PdfGridクラスでPDF文書内に表を作成する

この記事では、Free Spire.PDF.for.NETが提供するPdfTableクラスとPdfGridクラスを使ってPDF文書に表を作成する方法を説明します。 開発者は、これらの2つのクラスを使用するように選択する形式のニーズに応じて独自のフォームを作成することができます。
Free Spire.PDF for .NETには他にも多くの機能があります。 以下にいくつかの例を示します。
PDF文書の圧縮
PDFファイルから画像を抽出
PDF文書に透かしを挿入
PDF文書への添付ファイルの追加と削除

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1