Thursday, 24 August 2023 08:28

C#/VB.NET: PDF에서 테이블 추출

NuGet을 통해 설치됨

PM> Install-Package Spire.PDF

관련된 링크들

PDF는 데이터 공유 및 쓰기에 가장 널리 사용되는 문서 형식 중 하나입니다. PDF 문서, 특히 테이블의 데이터에서 데이터를 추출해야 하는 상황이 발생할 수 있습니다. 예를 들어, PDF 송장 테이블에 유용한 정보가 저장되어 있으며 추가 분석이나 계산을 위해 데이터를 추출하려고 합니다. 이 문서에서는 다음 방법을 보여줍니다 PDF 테이블에서 데이터 추출Spire.PDF for .NET를 사용하여 TXT 파일로 저장합니다.

Spire.PDF for .NET 설치

먼저 Spire.PDF for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

  • Package Manager
PM> Install-Package Spire.PDF 

PDF 테이블에서 데이터 추출

다음은 PDF 문서에서 테이블을 추출하는 주요 단계입니다.

  • PdfDocument 클래스의 인스턴스를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 문서를 로드합니다.
  • PdfTableExtractor.ExtractTable(int pageIndex) 메서드를 사용하여 특정 페이지에서 테이블을 추출합니다.
  • PdfTable.GetText(int rowIndex, int columnIndex) 메서드를 사용하여 특정 테이블 셀의 텍스트를 가져옵니다.
  • 추출된 데이터를 .txt 파일에 저장합니다.
  • C#
  • VB.NET
using System.IO;
    using System.Text;
    using Spire.Pdf;
    using Spire.Pdf.Utilities;
    
    namespace ExtractPdfTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load the sample PDF file
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");
    
                //Create a StringBuilder object
                StringBuilder builder = new StringBuilder();
    
                //Initialize an instance of PdfTableExtractor class
                PdfTableExtractor extractor = new PdfTableExtractor(doc);
    
                //Declare a PdfTable array
                PdfTable[] tableList = null;
    
                //Loop through the pages
                for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
                {
                    //Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex);
    
                    //Determine if the table list is null
                    if (tableList != null && tableList.Length > 0)
                    {
                        //Loop through the table in the list
                        foreach (PdfTable table in tableList)
                        {
                            //Get row number and column number of a certain table
                            int row = table.GetRowCount();
                            int column = table.GetColumnCount();
    
                            //Loop though the row and colunm
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < column; j++)
                                {
                                    //Get text from the specific cell
                                    string text = table.GetText(i, j);
    
                                    //Add text to the string builder
                                    builder.Append(text + " ");
                                }
                                builder.Append("\r\n");
                            }
                        }
                    }
                }
    
                //Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString());
            }
        }
    }
Imports System.IO
    Imports System.Text
    Imports Spire.Pdf
    Imports Spire.Pdf.Utilities
    
    Namespace ExtractPdfTable
        Class Program
            Shared  Sub Main(ByVal args() As String)
                'Create a PdfDocument object
                Dim doc As PdfDocument =  New PdfDocument()
    
                'Load the sample PDF file
                doc.LoadFromFile("C:\Users\Administrator\Desktop\table.pdf")
    
                'Create a StringBuilder object
                Dim builder As StringBuilder =  New StringBuilder()
    
                'Initialize an instance of PdfTableExtractor class
                Dim extractor As PdfTableExtractor =  New PdfTableExtractor(doc)
    
                'Declare a PdfTable array
                Dim tableList() As PdfTable =  Nothing
    
                'Loop through the pages
                Dim pageIndex As Integer
                For  pageIndex = 0 To  doc.Pages.Count- 1  Step  pageIndex + 1
                    'Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex)
    
                    'Determine if the table list is null
                    If tableList <> Nothing And tableList.Length > 0 Then
                        'Loop through the table in the list
                        Dim table As PdfTable
                        For Each table In tableList
                            'Get row number and column number of a certain table
                            Dim row As Integer =  table.GetRowCount()
                            Dim column As Integer =  table.GetColumnCount()
    
                            'Loop though the row and colunm
                            Dim i As Integer
                            For  i = 0 To  row- 1  Step  i + 1
                                Dim j As Integer
                                For  j = 0 To  column- 1  Step  j + 1
                                    'Get text from the specific cell
                                    Dim text As String =  table.GetText(i,j)
    
                                    'Add text to the string builder
                                    builder.Append(text + " ")
                                Next
                                builder.Append("\r\n")
                            Next
                        Next
                    End If
                Next
    
                'Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString())
            End Sub
        End Class
    End Namespace

C#/VB.NET: Extract Tables from PDF

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.

또한보십시오

Thursday, 24 August 2023 08:27

C#/VB.NET: estrae tabelle da PDF

Installato tramite NuGet

PM> Install-Package Spire.PDF

Link correlati

Il PDF è uno dei formati di documento più popolari per la condivisione e la scrittura di dati. Potresti incontrare la situazione in cui è necessario estrarre dati da documenti PDF, in particolare i dati nelle tabelle. Ad esempio, ci sono informazioni utili memorizzate nelle tabelle delle tue fatture PDF e desideri estrarre i dati per ulteriori analisi o calcoli. Questo articolo illustra come estrarre i dati dalle tabelle PDF e salvarlo in un file TXT utilizzando Spire.PDF for .NET.

Installa Spire.PDF for .NET

Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

  • Package Manager
PM> Install-Package Spire.PDF 

Estrai dati da tabelle PDF

Di seguito sono riportati i passaggi principali per estrarre le tabelle da un documento PDF.

  • Crea un'istanza della classe PdfDocument.
  • Caricare il documento PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Estrai le tabelle da una pagina specifica utilizzando il metodo PdfTableExtractor.ExtractTable(int pageIndex).
  • Ottieni il testo di una determinata cella della tabella utilizzando il metodo PdfTable.GetText(int rowIndex, int columnIndex).
  • Salva i dati estratti in un file .txt.
  • C#
  • VB.NET
using System.IO;
    using System.Text;
    using Spire.Pdf;
    using Spire.Pdf.Utilities;
    
    namespace ExtractPdfTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load the sample PDF file
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");
    
                //Create a StringBuilder object
                StringBuilder builder = new StringBuilder();
    
                //Initialize an instance of PdfTableExtractor class
                PdfTableExtractor extractor = new PdfTableExtractor(doc);
    
                //Declare a PdfTable array
                PdfTable[] tableList = null;
    
                //Loop through the pages
                for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
                {
                    //Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex);
    
                    //Determine if the table list is null
                    if (tableList != null && tableList.Length > 0)
                    {
                        //Loop through the table in the list
                        foreach (PdfTable table in tableList)
                        {
                            //Get row number and column number of a certain table
                            int row = table.GetRowCount();
                            int column = table.GetColumnCount();
    
                            //Loop though the row and colunm
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < column; j++)
                                {
                                    //Get text from the specific cell
                                    string text = table.GetText(i, j);
    
                                    //Add text to the string builder
                                    builder.Append(text + " ");
                                }
                                builder.Append("\r\n");
                            }
                        }
                    }
                }
    
                //Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString());
            }
        }
    }
Imports System.IO
    Imports System.Text
    Imports Spire.Pdf
    Imports Spire.Pdf.Utilities
    
    Namespace ExtractPdfTable
        Class Program
            Shared  Sub Main(ByVal args() As String)
                'Create a PdfDocument object
                Dim doc As PdfDocument =  New PdfDocument()
    
                'Load the sample PDF file
                doc.LoadFromFile("C:\Users\Administrator\Desktop\table.pdf")
    
                'Create a StringBuilder object
                Dim builder As StringBuilder =  New StringBuilder()
    
                'Initialize an instance of PdfTableExtractor class
                Dim extractor As PdfTableExtractor =  New PdfTableExtractor(doc)
    
                'Declare a PdfTable array
                Dim tableList() As PdfTable =  Nothing
    
                'Loop through the pages
                Dim pageIndex As Integer
                For  pageIndex = 0 To  doc.Pages.Count- 1  Step  pageIndex + 1
                    'Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex)
    
                    'Determine if the table list is null
                    If tableList <> Nothing And tableList.Length > 0 Then
                        'Loop through the table in the list
                        Dim table As PdfTable
                        For Each table In tableList
                            'Get row number and column number of a certain table
                            Dim row As Integer =  table.GetRowCount()
                            Dim column As Integer =  table.GetColumnCount()
    
                            'Loop though the row and colunm
                            Dim i As Integer
                            For  i = 0 To  row- 1  Step  i + 1
                                Dim j As Integer
                                For  j = 0 To  column- 1  Step  j + 1
                                    'Get text from the specific cell
                                    Dim text As String =  table.GetText(i,j)
    
                                    'Add text to the string builder
                                    builder.Append(text + " ")
                                Next
                                builder.Append("\r\n")
                            Next
                        Next
                    End If
                Next
    
                'Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString())
            End Sub
        End Class
    End Namespace

C#/VB.NET: Extract Tables from PDF

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Thursday, 24 August 2023 08:21

C#/VB.NET : extraire des tableaux d'un PDF

Installé via NuGet

PM> Install-Package Spire.PDF

Le PDF est l'un des formats de document les plus populaires pour le partage et l'écriture de données. Vous pouvez rencontrer la situation où vous devez extraire des données à partir de documents PDF, en particulier les données des tableaux. Par exemple, des informations utiles sont stockées dans les tableaux de vos factures PDF et vous souhaitez extraire les données pour une analyse ou un calcul plus approfondi. Cet article montre comment extraire des données de tableaux PDF et enregistrez-le dans un fichier TXT en utilisant Spire.PDF for .NET.

Installer Spire.PDF for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for .NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

  • Package Manager
PM> Install-Package Spire.PDF 

Extraire des données de tableaux PDF

Voici les principales étapes pour extraire des tableaux d'un document PDF.

  • Créez une instance de la classe PdfDocument.
  • Chargez l'exemple de document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
  • Extrayez les tableaux d’une page spécifique à l’aide de la méthode PdfTableExtractor.ExtractTable(int pageIndex).
  • Obtenez le texte d’une certaine cellule du tableau à l’aide de la méthode PdfTable.GetText(int rowIndex, int columnIndex).
  • Enregistrez les données extraites dans un fichier .txt.
  • C#
  • VB.NET
using System.IO;
    using System.Text;
    using Spire.Pdf;
    using Spire.Pdf.Utilities;
    
    namespace ExtractPdfTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load the sample PDF file
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");
    
                //Create a StringBuilder object
                StringBuilder builder = new StringBuilder();
    
                //Initialize an instance of PdfTableExtractor class
                PdfTableExtractor extractor = new PdfTableExtractor(doc);
    
                //Declare a PdfTable array
                PdfTable[] tableList = null;
    
                //Loop through the pages
                for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
                {
                    //Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex);
    
                    //Determine if the table list is null
                    if (tableList != null && tableList.Length > 0)
                    {
                        //Loop through the table in the list
                        foreach (PdfTable table in tableList)
                        {
                            //Get row number and column number of a certain table
                            int row = table.GetRowCount();
                            int column = table.GetColumnCount();
    
                            //Loop though the row and colunm
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < column; j++)
                                {
                                    //Get text from the specific cell
                                    string text = table.GetText(i, j);
    
                                    //Add text to the string builder
                                    builder.Append(text + " ");
                                }
                                builder.Append("\r\n");
                            }
                        }
                    }
                }
    
                //Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString());
            }
        }
    }
Imports System.IO
    Imports System.Text
    Imports Spire.Pdf
    Imports Spire.Pdf.Utilities
    
    Namespace ExtractPdfTable
        Class Program
            Shared  Sub Main(ByVal args() As String)
                'Create a PdfDocument object
                Dim doc As PdfDocument =  New PdfDocument()
    
                'Load the sample PDF file
                doc.LoadFromFile("C:\Users\Administrator\Desktop\table.pdf")
    
                'Create a StringBuilder object
                Dim builder As StringBuilder =  New StringBuilder()
    
                'Initialize an instance of PdfTableExtractor class
                Dim extractor As PdfTableExtractor =  New PdfTableExtractor(doc)
    
                'Declare a PdfTable array
                Dim tableList() As PdfTable =  Nothing
    
                'Loop through the pages
                Dim pageIndex As Integer
                For  pageIndex = 0 To  doc.Pages.Count- 1  Step  pageIndex + 1
                    'Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex)
    
                    'Determine if the table list is null
                    If tableList <> Nothing And tableList.Length > 0 Then
                        'Loop through the table in the list
                        Dim table As PdfTable
                        For Each table In tableList
                            'Get row number and column number of a certain table
                            Dim row As Integer =  table.GetRowCount()
                            Dim column As Integer =  table.GetColumnCount()
    
                            'Loop though the row and colunm
                            Dim i As Integer
                            For  i = 0 To  row- 1  Step  i + 1
                                Dim j As Integer
                                For  j = 0 To  column- 1  Step  j + 1
                                    'Get text from the specific cell
                                    Dim text As String =  table.GetText(i,j)
    
                                    'Add text to the string builder
                                    builder.Append(text + " ")
                                Next
                                builder.Append("\r\n")
                            Next
                        Next
                    End If
                Next
    
                'Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString())
            End Sub
        End Class
    End Namespace

C#/VB.NET: Extract Tables from PDF

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

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;
                }
            }
        }
    }

C#/VB.NET: Create Tables in PDF

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");
            }
        }
    }

C#/VB.NET: Create Tables in 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.

Veja também

Таблица обеспечивает быстрый и эффективный доступ к данным, отображаемым в строках и столбцах в визуально привлекательной форме. Представленные в виде таблицы данные оказывают большее влияние, чем просто слова, и позволяют читателям легко сравнивать и понимать отношения между ними. В этой статье вы узнаете, как создать таблицу в формате PDF на C# и VB.NET используя Spire.PDF for .NET.

Spire.PDF for .NET предлагает класс PdfTable и PdfGrid для работы с таблицами в документе PDF. Класс PdfTable используется для быстрого создания простых обычных таблиц без лишнего форматирования, а класс PdfGrid используется для создания более сложных таблиц.

В таблице ниже перечислены различия между этими двумя классами.

PdfТаблица PdfGrid
Форматирование
Ряд Можно установить через события. Нет поддержки API. Можно настроить через API.
Столбец Можно установить через API (StringFormat). Можно установить через API (StringFormat).
Клетка Можно установить через события. Нет поддержки API. Можно настроить через API.
Другие
Диапазон столбцов Не поддерживается. Можно настроить через API.
Диапазон строк Можно установить через события. Нет поддержки API. Можно настроить через API.
Вложенная таблица Можно установить через события. Нет поддержки API. Можно настроить через API.
События Бегинцелллайаут, Эндцелллайаут, БегинРовлайаут, ЭндРовлайаут, Бегинпажемакет, ендпажемакаут. Бегинпажемакет, ендпажемакаут.

В следующих разделах показано, как создать таблицу в PDF с помощью классов PdfTable и PdfGrid соответственно.

Установите Spire.PDF for .NET

Для начала вам нужно добавить файлы DLL, включенные в пакет Spire.PDF for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.PDF

Создайте таблицу с помощью класса PdfTable

Ниже приведены шаги для создания таблицы с использованием класса PdfTable.

  • Создайте объект PdfDocument.
  • Добавьте к нему страницу с помощью метода PdfDocument.Pages.Add().
  • Создайте объект Pdftable.
  • Задайте стиль таблицы через свойство PdfTable.Style.
  • Вставить данные в таблицу через свойство PdfTable.DataSource.
  • Установите высоту строки и цвет строки через событие BeginRowLayout.
  • Нарисуйте таблицу на странице PDF с помощью метода PdfTable.Draw().
  • Сохраните документ в файл PDF с помощью метода 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;
                }
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Создайте таблицу с помощью класса PdfGrid

Ниже приведены шаги по созданию таблицы с использованием класса PdfGrid.

  • Создайте объект PdfDocument.
  • Добавьте к нему страницу с помощью метода PdfDocument.Pages.Add().
  • Создайте объект PdfGrid.
  • Задайте стиль таблицы через свойство PdfGrid.Style.
  • Добавьте строки в таблицу с помощью метода PdfGrid.Rows.Add().
  • Вставка данных в определенные ячейки через свойство PdfGridRow.Cells[index].Value.
  • Распределяйте ячейки по столбцам или строкам с помощью свойства PdfGridRow.RowSpan или PdfGridRow.ColumnSpan.
  • Задайте форматирование конкретной ячейки с помощью свойств PdfGridRow.Cells[index].StringFormat и PdfGridRow.Cells[index].Style.
  • Нарисуйте таблицу на странице PDF с помощью метода PdfGrid.Draw().
  • Сохраните документ в файл PDF с помощью метода 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");
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Подать заявку на временную лицензию

Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.

Смотрите также

Thursday, 24 August 2023 08:17

C#/VB.NET: crear tablas en PDF

Über NuGet installiert

PM> Install-Package Spire.PDF

verwandte Links

Eine Tabelle bietet schnellen und effizienten Zugriff auf optisch ansprechende Daten, die in Zeilen und Spalten angezeigt werden. Wenn Daten in einer Tabelle dargestellt werden, haben sie eine größere Wirkung als wenn sie nur in Worten verwendet werden, und ermöglichen es den Lesern, die Beziehungen zwischen ihnen leicht zu vergleichen und zu verstehen. In diesem Artikel erfahren Sie, wie das geht Erstellen Sie eine Tabelle im PDF-Format in C# und VB.NET mit Spire.PDF for .NET.

Spire.PDF for .NET bietet die Klassen PdfTable und PdfGrid für die Arbeit mit den Tabellen in einem PDF-Dokument. Die PdfTable-Klasse wird zum schnellen Erstellen einfacher, regulärer Tabellen ohne allzu große Formatierung verwendet, während die PdfGrid-Klasse zum Erstellen komplexerer Tabellen verwendet wird.

In der folgenden Tabelle sind die Unterschiede zwischen diesen beiden Klassen aufgeführt.

PdfTable PdfGrid
Formatierung
Reihe Kann über Ereignisse eingestellt werden. Keine API-Unterstützung. Kann über die API eingestellt werden.
Spalte Kann über die API (StringFormat) festgelegt werden. Kann über die API (StringFormat) festgelegt werden.
Zelle Kann über Ereignisse eingestellt werden. Keine API-Unterstützung. Kann über die API eingestellt werden.
Andere
Spaltenspanne Nicht unterstützt. Kann über die API eingestellt werden.
Zeilenspanne Kann über Ereignisse eingestellt werden. Keine API-Unterstützung. Kann über die API eingestellt werden.
Geschachtelter Tisch Kann über Ereignisse eingestellt werden. Keine API-Unterstützung. Kann über die API eingestellt werden.
Veranstaltungen BeginCellLayout, EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout.

In den folgenden Abschnitten wird gezeigt, wie Sie mit der PdfTable-Klasse bzw. der PdfGrid-Klasse eine Tabelle in PDF erstellen.

Installieren Sie Spire.PDF for .NET

Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.PDF

Erstellen Sie eine Tabelle mit der PdfTable-Klasse

Im Folgenden finden Sie die Schritte zum Erstellen einer Tabelle mithilfe der PdfTable-Klasse.

  • Erstellen Sie ein PdfDocument-Objekt.
  • Fügen Sie mit der Methode PdfDocument.Pages.Add() eine Seite hinzu.
  • Erstellen Sie ein Pdftable-Objekt.
  • Legen Sie den Tabellenstil über die Eigenschaft PdfTable.Style fest.
  • Fügen Sie Daten über die Eigenschaft PdfTable.DataSource in die Tabelle ein.
  • Legen Sie die Zeilenhöhe und die Zeilenfarbe über das BeginRowLayout-Ereignis fest.
  • Zeichnen Sie eine Tabelle auf der PDF-Seite mit der Methode PdfTable.Draw().
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer PDF-Datei.
  • 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;
                }
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Erstellen Sie eine Tabelle mit der Klasse PdfGrid

Nachfolgend finden Sie die Schritte zum Erstellen einer Tabelle mit der PdfGrid-Klasse.

  • Erstellen Sie ein PdfDocument-Objekt.
  • Fügen Sie mit der Methode PdfDocument.Pages.Add() eine Seite hinzu.
  • Erstellen Sie ein PDFGrid-Objekt.
  • Legen Sie den Tabellenstil über die Eigenschaft PdfGrid.Style fest.
  • Fügen Sie der Tabelle mithilfe der Methode PdfGrid.Rows.Add() Zeilen hinzu.
  • Fügen Sie Daten über die Eigenschaft PdfGridRow.Cells[index].Value in bestimmte Zellen ein.
  • Erweitern Sie Zellen über Spalten oder Zeilen mithilfe der Eigenschaft PdfGridRow.RowSpan oder PdfGridRow.ColumnSpan.
  • Legen Sie die Formatierung einer bestimmten Zelle über die Eigenschaften PdfGridRow.Cells[index].StringFormat und PdfGridRow.Cells[index].Style fest.
  • Zeichnen Sie eine Tabelle auf der PDF-Seite mit der Methode PdfGrid.Draw().
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer PDF-Datei.
  • 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");
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Thursday, 24 August 2023 08:16

C#/VB.NET: crear tablas en PDF

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

Una tabla brinda acceso rápido y eficiente a los datos que se muestran en filas y columnas de una manera visualmente atractiva. Cuando se presentan en una tabla, los datos tienen un mayor impacto que cuando se usan solo como palabras y permiten a los lectores comparar y comprender fácilmente las relaciones entre ellos. En este artículo, aprenderá cómo cree una tabla en PDF en C# y VB.NET usando Spire.PDF for .NET.

Spire.PDF for .NET ofrece las clases PdfTable y PdfGrid para trabajar con las tablas en un documento PDF. La clase PdfTable se usa para crear rápidamente tablas simples y regulares sin demasiado formato, mientras que la clase PdfGrid se usa para crear tablas más complejas.

La siguiente tabla enumera las diferencias entre estas dos clases.

PdfTable PdfCuadrícula
Formateo
Fila Se puede establecer a través de eventos. Sin soporte de API. Se puede configurar a través de la API.
Columna Se puede configurar a través de API (StringFormat). Se puede configurar a través de API (StringFormat).
Celúla Se puede establecer a través de eventos. Sin soporte de API. Se puede configurar a través de la API.
Otros
Tramo de columna No apoyo. Se puede configurar a través de la API.
Intervalo de filas Se puede establecer a través de eventos. Sin soporte de API. Se puede configurar a través de la API.
tabla anidada Se puede establecer a través de eventos. Sin soporte de API. Se puede configurar a través de la API.
Eventos BeginCellLayout,  EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout.

Las siguientes secciones muestran cómo crear una tabla en PDF usando la clase PdfTable y la clase PdfGrid, respectivamente.

Instalar Spire.PDF for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.PDF

Crear una tabla usando la clase PdfTable

Los siguientes son los pasos para crear una tabla usando la clase PdfTable.

  • Cree un objeto PdfDocument.
  • Agregue una página usando el método PdfDocument.Pages.Add().
  • Cree un objeto Pdftable.
  • Establezca el estilo de la tabla a través de la propiedad PdfTable.Style.
  • Inserte datos en la tabla a través de la propiedad PdfTable.DataSource.
  • Establezca la altura de la fila y el color de la fila a través del evento BeginRowLayout.
  • Dibuje una tabla en la página PDF utilizando el método PdfTable.Draw().
  • Guarde el documento en un archivo PDF utilizando el 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;
                }
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Crear una tabla usando la clase PdfGrid

A continuación se muestran los pasos para crear una tabla utilizando la clase PdfGrid.

  • Cree un objeto PdfDocument.
  • Agregue una página usando el método PdfDocument.Pages.Add().
  • Cree un objeto PdfGrid.
  • Establezca el estilo de la tabla a través de la propiedad PdfGrid.Style.
  • Agregue filas a la tabla usando el método PdfGrid.Rows.Add().
  • Inserte datos en celdas específicas a través de la propiedad PdfGridRow.Cells[index].Value.
  • Distribuya celdas en columnas o filas a través de la propiedad PdfGridRow.RowSpan o PdfGridRow.ColumnSpan.
  • Establezca el formato de una celda específica a través de las propiedades PdfGridRow.Cells[index].StringFormat y PdfGridRow.Cells[index].Style.
  • Dibuje una tabla en la página PDF utilizando el método PdfGrid.Draw().
  • Guarde el documento en un archivo PDF utilizando el 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");
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Solicitar una Licencia Temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

Thursday, 24 August 2023 08:15

C#/VB.NET: PDF로 테이블 만들기

테이블을 사용하면 시각적으로 보기 좋은 방식으로 행과 열에 표시된 데이터에 빠르고 효율적으로 액세스할 수 있습니다. 표로 제시될 때 데이터는 단순히 단어로 사용될 때보다 더 큰 영향을 미치며 독자가 데이터 간의 관계를 쉽게 비교하고 이해할 수 있도록 합니다. 이 기사에서는 다음을 수행하는 방법을 배웁니다 C# 및 VB.NET에서 PDF로 테이블 만들기 Spire.PDF for .NET사용.

Spire.PDF for .NET는 PDF 문서의 테이블 작업을 위해 PdfTablePdfGrid 클래스를 제공합니다. PdfTable 클래스는 너무 많은 서식을 지정하지 않고 간단하고 일반 테이블을 빠르게 만드는 데 사용되는 반면 PdfGrid 클래스는 더 복잡한 테이블을 만드는 데 사용됩니다.

아래 표에는 이 두 클래스의 차이점이 나열되어 있습니다.

PDF 테이블 Pdf그리드
포맷팅
이벤트를 통해 설정할 수 있습니다. API 지원이 없습니다. API를 통해 설정할 수 있습니다.
API(StringFormat)를 통해 설정할 수 있습니다. API(StringFormat)를 통해 설정할 수 있습니다.
이벤트를 통해 설정할 수 있습니다. API 지원이 없습니다. API를 통해 설정할 수 있습니다.
기타
열 범위 지원하지 않습니다. API를 통해 설정할 수 있습니다.
행 범위 이벤트를 통해 설정할 수 있습니다. API 지원이 없습니다. API를 통해 설정할 수 있습니다.
중첩 테이블 이벤트를 통해 설정할 수 있습니다. API 지원이 없습니다. API를 통해 설정할 수 있습니다.
이벤트 BeginCellLayout,  EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout.

다음 섹션에서는 각각 PdfTable 클래스와 PdfGrid 클래스를 사용하여 PDF로 표를 만드는 방법을 보여줍니다.

Spire.PDF for .NET 설치

먼저 Spire.PDF for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

PM> Install-Package Spire.PDF

PdfTable 클래스를 사용하여 테이블 만들기

다음은 PdfTable 클래스를 사용하여 테이블을 만드는 단계입니다.

  • PdfDocument 개체를 만듭니다.
  • PdfDocument.Pages.Add() 메서드를 사용하여 페이지를 추가합니다.
  • Pdftable 개체를 만듭니다.
  • PdfTable.Style 속성을 통해 테이블 스타일을 설정합니다.
  • PdfTable.DataSource 속성을 통해 테이블에 데이터를 삽입합니다.
  • BeginRowLayout 이벤트를 통해 행 높이와 행 색상을 설정합니다.
  • PdfTable.Draw() 메서드를 사용하여 PDF 페이지에 테이블을 그립니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 PDF 파일로 저장합니다.
  • 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;
                }
            }
        }
    }

C#/VB.NET: Create Tables in PDF

PdfGrid 클래스를 사용하여 테이블 만들기

다음은 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() 메서드를 사용하여 PDF 페이지에 테이블을 그립니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 PDF 파일로 저장합니다.
  • 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");
            }
        }
    }

C#/VB.NET: Create Tables in PDF

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.

또한보십시오

Thursday, 24 August 2023 08:14

C#/VB.NET: crea tabelle in PDF

Installato tramite NuGet

PM> Install-Package Spire.PDF

Link correlati

Una tabella fornisce un accesso rapido ed efficiente ai dati visualizzati in righe e colonne in modo visivamente accattivante. Quando vengono presentati in una tabella, i dati hanno un impatto maggiore rispetto a quando vengono usati solo come parole e consentono ai lettori di confrontare e comprendere facilmente le relazioni tra di loro. In questo articolo imparerai come creare una tabella in PDF in C# e VB.NET utilizzando Spire.PDF for .NET.

Spire.PDF for .NET offre la classe PdfTable e PdfGrid per lavorare con le tabelle in un documento PDF. La classe PdfTable viene utilizzata per creare rapidamente tabelle semplici e regolari senza troppa formattazione, mentre la classe PdfGrid viene utilizzata per creare tabelle più complesse.

La tabella seguente elenca le differenze tra queste due classi.

PdfTable PdfGrid
Formattazione
Riga Può essere impostato tramite eventi. Nessun supporto API. Può essere impostato tramite API.
Colonna Può essere impostato tramite API (StringFormat). Può essere impostato tramite API (StringFormat).
Cellula Può essere impostato tramite eventi. Nessun supporto API. Può essere impostato tramite API.
Altri
Intervallo di colonne Non supporto. Può essere impostato tramite API.
Intervallo di fila Può essere impostato tramite eventi. Nessun supporto API. Può essere impostato tramite API.
Tavolo annidato Può essere impostato tramite eventi. Nessun supporto API. Può essere impostato tramite API.
Eventi BeginCellLayout,  EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. InizioLayoutPagina, FineLayoutPagina.

Le sezioni seguenti mostrano come creare una tabella in PDF utilizzando rispettivamente la classe PdfTable e la classe PdfGrid.

Installa Spire.PDF for .NET

Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.PDF

Creare una tabella utilizzando la classe PdfTable

Di seguito sono riportati i passaggi per creare una tabella utilizzando la classe PdfTable.

  • Creare un oggetto PdfDocument.
  • Aggiungi una pagina usando il metodo PdfDocument.Pages.Add().
  • Crea un oggetto Pdftable.
  • Impostare lo stile della tabella tramite la proprietà PdfTable.Style.
  • Inserire i dati nella tabella tramite la proprietà PdfTable.DataSource.
  • Imposta l'altezza e il colore della riga tramite l'evento BeginRowLayout.
  • Disegna la tabella sulla pagina PDF usando il metodo PdfTable.Draw().
  • Salvare il documento in un file PDF utilizzando il metodo 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;
                }
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Creare una tabella utilizzando la classe PdfGrid

Di seguito sono riportati i passaggi per creare una tabella utilizzando la classe PdfGrid.

  • Creare un oggetto PdfDocument.
  • Aggiungi una pagina usando il metodo PdfDocument.Pages.Add().
  • Crea un oggetto PdfGrid.
  • Impostare lo stile della tabella tramite la proprietà PdfGrid.Style.
  • Aggiungi righe alla tabella utilizzando il metodo PdfGrid.Rows.Add().
  • Inserisci i dati in celle specifiche tramite la proprietà PdfGridRow.Cells[index].Value.
  • Estendi le celle su colonne o righe tramite la proprietà PdfGridRow.RowSpan o PdfGridRow.ColumnSpan.
  • Impostare la formattazione di una cella specifica tramite le proprietà PdfGridRow.Cells[index].StringFormat e PdfGridRow.Cells[index].Style.
  • Disegna la tabella sulla pagina PDF usando il metodo PdfGrid.Draw().
  • Salvare il documento in un file PDF utilizzando il metodo 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");
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Un tableau fournit un accès rapide et efficace aux données affichées dans les lignes et les colonnes d'une manière visuellement attrayante. Lorsqu'elles sont présentées dans un tableau, les données ont un impact plus important que lorsqu'elles sont simplement utilisées sous forme de mots et permettent aux lecteurs de comparer et de comprendre facilement les relations entre elles. Dans cet article, vous apprendrez à créer un tableau au format PDF en C# et VB.NET à l'aide de Spire.PDF for .NET.

Spire.PDF for .NET propose les classes PdfTable et PdfGrid pour travailler avec les tableaux d'un document PDF. La classe PdfTable est utilisée pour créer rapidement des tableaux simples et réguliers sans trop de formatage, tandis que la classe PdfGrid est utilisée pour créer des tableaux plus complexes.

Le tableau ci-dessous liste les différences entre ces deux classes.

PdfTable PdfGrid
Mise en page
Rangée Peut être défini par des événements. Aucune prise en charge d'API. Peut être défini via l'API.
Colonne Peut être défini via l'API (StringFormat). Peut être défini via l'API (StringFormat).
Cellule Peut être défini par des événements. Aucune prise en charge d'API. Peut être défini via l'API.
Autres
Portée de la colonne Pas de support. Peut être défini via l'API.
Étendue de la ligne Peut être défini par des événements. Aucune prise en charge d'API. Peut être défini via l'API.
Tableau imbriqué Peut être défini par des événements. Aucune prise en charge d'API. Peut être défini via l'API.
Événements BeginCellLayout, EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout.

Les sections suivantes montrent comment créer un tableau au format PDF à l'aide de la classe PdfTable et de la classe PdfGrid, respectivement.

Installer Spire.PDF for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for .NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.PDF

Créer un tableau à l'aide de la classe PdfTable

Voici les étapes pour créer un tableau à l'aide de la classe PdfTable.

  • Créez un objet PdfDocument.
  • Ajoutez-y une page en utilisant la méthode PdfDocument.Pages.Add().
  • Créez un objet Pdftable.
  • Définissez le style de tableau via la propriété PdfTable.Style.
  • Insérez des données dans la table via la propriété PdfTable.DataSource.
  • Définissez la hauteur et la couleur des lignes via l'événement BeginRowLayout.
  • Dessinez un tableau sur la page PDF à l'aide de la méthode PdfTable.Draw().
  • Enregistrez le document dans un fichier PDF à l'aide de la méthode 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;
                }
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Créer une table à l'aide de la classe PdfGrid

Vous trouverez ci-dessous les étapes pour créer une table à l'aide de la classe PdfGrid.

  • Créez un objet PdfDocument.
  • Ajoutez-y une page en utilisant la méthode PdfDocument.Pages.Add().
  • Créez un objet PdfGrid.
  • Définissez le style de tableau via la propriété PdfGrid.Style.
  • Ajoutez des lignes au tableau à l'aide de la méthode PdfGrid.Rows.Add().
  • Insérez des données dans des cellules spécifiques via la propriété .
  • Étendez les cellules sur des colonnes ou des lignes via la propriété PdfGridRow.RowSpan ou PdfGridRow.ColumnSpan.
  • Définissez la mise en forme d'une cellule spécifique via les propriétés PdfGridRow.Cells[index].StringFormat et PdfGridRow.Cells[index].Style.
  • Dessinez un tableau sur la page PDF à l'aide de la méthode PdfGrid.Draw().
  • Enregistrez le document dans un fichier PDF à l'aide de la méthode 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");
            }
        }
    }

C#/VB.NET: Create Tables in PDF

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également