Databases are almost everywhere to store and manage the data. It is a common practice of the programmers to retrieve the data from the databases and load it into the applications. When generating PDF files programmatically, one may need to populate the document with the data in database. To accomplish that in .NET applications, this article shows how to add data from database to PDF files in C#.
- .NET API to Add Data from Database to PDF
- Add Data from Database to PDF
- Add Data from Database to PDF in Entity Framework
C# .NET API to Add Data from Database to PDF
We will use Aspose.PDF for .NET to add data from database to PDF files. It is a popular PDF generation and manipulation API that allows you to create PDF files of simple and complex layouts seamlessly. You can either download the API’s binaries or install it using NuGet.
PM> Install-Package Aspose.PDF
Add Data from Database to PDF in C#
In most of the cases, the data is fetched from a database table into a DataTable or DataView. Therefore, for demonstration, we will use a DataTable to add data to a PDF file. To keep the things simpler, we will create and populate the DataTable programmatically without using a database. The following are the steps to add data to a PDF file from database in C#.
- Load the data into a DataTable from database.
- Create a new PDF or load existing one using Document class.
- Create an instance of Table class and set its properties, i.e. column width, borders, etc.
- Import data from database to PDF table using Table.ImportDataTable() method.
- Add the table to the page using **Document.Pages[index].Paragraphs.Add(Table)** method.
- Save the PDF file using Document.Save(string) method.
The following code sample shows how to import data from database to PDF in C#.
The following is the output of the above code sample.
Add Data from Database to PDF in Entity Framework
These days, Entity Framework (EF) is being commonly used by the developers. Therefore, it would be handy to extend the Table class to populate PDF documents with lists or grouped data in EF. The following is the implementation of how to populate a PDF table using a list and grouped data. In both methods, the Table and data is passed as arguments of the method.
Get a Free License
You can get a free temporary license in order to use Aspose.PDF for .NET without evaluation limitations.
In this article, you have learned how to add data from database into PDF files in C#. You have seen how to import data from a DataTable into a table in PDF file. In addition, we have covered the implementation of importing data into PDF using Entity Framework. Besides, you can explore more about the C# PDF API using the documentation. In case you would have any questions or queries, you can contact us via our forum.