Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
Uma tabela fornece acesso rápido e eficiente aos dados exibidos em linhas e colunas de maneira visualmente atraente. Quando apresentados em uma tabela, os dados têm um impacto maior do que quando usados apenas como palavras e permitem que os leitores comparem e entendam facilmente as relações entre eles. Neste artigo, você aprenderá como crie uma tabela em PDF em C# e VB.NET usando Spire.PDF for .NET.
O Spire.PDF for .NET oferece as classes PdfTable e PdfGrid para trabalhar com as tabelas em um documento PDF. A classe PdfTable é usada para criar rapidamente tabelas simples e regulares sem muita formatação, enquanto a classe PdfGrid é usada para criar tabelas mais complexas.
A tabela abaixo lista as diferenças entre essas duas classes.
| Tabela Pdf | PDFGrid | |
| Formatação | ||
| Linha | Pode ser definido através de eventos. Sem suporte de API. | Pode ser definido por meio da API. |
| Coluna | Pode ser definido por meio da API (StringFormat). | Pode ser definido por meio da API (StringFormat). |
| Célula | Pode ser definido através de eventos. Sem suporte de API. | Pode ser definido por meio da API. |
| Outros | ||
| Extensão da coluna | Não suporta. | Pode ser definido por meio da API. |
| Expansão de linha | Pode ser definido através de eventos. Sem suporte de API. | Pode ser definido por meio da API. |
| Tabela aninhada | Pode ser definido através de eventos. Sem suporte de API. | Pode ser definido por meio da API. |
| Eventos | BeginCellLayout, EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. | BeginPageLayout, EndPageLayout. |
As seções a seguir demonstram como criar uma tabela em PDF usando a classe PdfTable e a classe PdfGrid, respectivamente.
Instalar o Spire.PDF for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.
PM> Install-Package Spire.PDF
Criar uma tabela usando a classe PDFTable
A seguir estão as etapas para criar uma tabela usando a classe PdfTable.
- Crie um objeto PdfDocument.
- Adicione uma página usando o método PdfDocument.Pages.Add().
- Crie um objeto Pdftable.
- Defina o estilo da tabela por meio da propriedade PdfTable.Style.
- Insira dados na tabela por meio da propriedade PdfTable.DataSource.
- Defina a altura e a cor da linha por meio do evento BeginRowLayout.
- Desenhe a tabela na página PDF usando o método PdfTable.Draw().
- Salve o documento em um arquivo PDF usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using System;
using System.Data;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
namespace CreateTable
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Add a page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));
//Create a PdfTable object
PdfTable table = new PdfTable();
//Set font for header and the rest cells
table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Times New Roman", 12f, FontStyle.Regular), true);
table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Times New Roman", 12f, FontStyle.Bold), true);
//Crate a DataTable
DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID");
dataTable.Columns.Add("Name");
dataTable.Columns.Add("Department");
dataTable.Columns.Add("Position");
dataTable.Columns.Add("Level");
dataTable.Rows.Add(new string[] { "1", "David", "IT", "Manager", "1" });
dataTable.Rows.Add(new string[] { "3", "Julia", "HR", "Manager", "1" });
dataTable.Rows.Add(new string[] { "4", "Sophie", "Marketing", "Manager", "1" });
dataTable.Rows.Add(new string[] { "7", "Wickey", "Marketing", "Sales Rep", "2" });
dataTable.Rows.Add(new string[] { "9", "Wayne", "HR", "HR Supervisor", "2" });
dataTable.Rows.Add(new string[] { "11", "Mia", "Dev", "Developer", "2" });
//Set the datatable as the data source of table
table.DataSource = dataTable;
//Show header(the header is hidden by default)
table.Style.ShowHeader = true;
//Set font color and backgroud color of header row
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray;
table.Style.HeaderStyle.TextBrush = PdfBrushes.White;
//Set text alignment in header row
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
//Set text alignment in other cells
for (int i = 0; i < table.Columns.Count; i++)
{
table.Columns[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
}
//Register with BeginRowLayout event
table.BeginRowLayout += Table_BeginRowLayout;
//Draw table on the page
table.Draw(page, new PointF(0, 30));
//Save the document to a PDF file
doc.SaveToFile("PdfTable.pdf");
}
//Event handler
private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
{
//Set row height
args.MinimalHeight = 20f;
//Alternate row color
if (args.RowIndex < 0)
{
return;
}
if (args.RowIndex % 2 == 1)
{
args.CellStyle.BackgroundBrush = PdfBrushes.LightGray;
}
else
{
args.CellStyle.BackgroundBrush = PdfBrushes.White;
}
}
}
}

Criar uma tabela usando a classe PDFGrid
Abaixo estão as etapas para criar uma tabela usando a classe PdfGrid.
- Crie um objeto PdfDocument.
- Adicione uma página usando o método PdfDocument.Pages.Add().
- Crie um objeto PDFGrid.
- Defina o estilo da tabela através da propriedade PdfGrid.Style.
- Adicione linhas à tabela usando o método PdfGrid.Rows.Add().
- Insira dados em células específicas por meio da propriedade PdfGridRow.Cells[index].Value.
- Distribua células em colunas ou linhas por meio da propriedade PdfGridRow.RowSpan ou PdfGridRow.ColumnSpan.
- Defina a formatação de uma célula específica por meio das propriedades PdfGridRow.Cells[index].StringFormat e PdfGridRow.Cells[index].Style.
- Desenhe a tabela na página PDF usando o método PdfGrid.Draw().
- Salve o documento em um arquivo PDF usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using System.Drawing;
namespace CreateGrid
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Add a page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4,new PdfMargins(40));
//Create a PdfGrid
PdfGrid grid = new PdfGrid();
//Set cell padding
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
//Set font
grid.Style.Font = new PdfTrueTypeFont(new Font("Times New Roman", 13f, FontStyle.Regular), true);
//Add rows
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
PdfGridRow row3 = grid.Rows.Add();
PdfGridRow row4 = grid.Rows.Add();
grid.Columns.Add(4);
//Set column width
foreach (PdfGridColumn col in grid.Columns)
{
col.Width = 110f;
}
//Write data into specific cells
row1.Cells[0].Value = "Order and Payment Status";
row2.Cells[0].Value = "Order number";
row2.Cells[1].Value = "Date";
row2.Cells[2].Value = "Customer";
row2.Cells[3].Value = "Paid or not";
row3.Cells[0].Value = "00223";
row3.Cells[1].Value = "2022/06/02";
row3.Cells[2].Value = "Brick Lane Realty";
row3.Cells[3].Value = "Yes";
row4.Cells[0].Value = "00224";
row4.Cells[1].Value = "2022/06/03";
row4.Cells[3].Value = "No";
//Span cell across columns
row1.Cells[0].ColumnSpan = 4;
//Span cell across rows
row3.Cells[2].RowSpan = 2;
//Set text alignment of specific cells
row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
//Set background color of specific cells
row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Orange;
row4.Cells[3].Style.BackgroundBrush = PdfBrushes.LightGray;
//Format cell border
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;
}
}
//Draw table on the page
grid.Draw(page, new PointF(0, 30));
//Save the document to a PDF file
doc.SaveToFile("PdfGrid.pdf");
}
}
}

Solicitar uma licença temporária
Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.