How to Generate PDF from Template in C#

In today's culture, Portable Document Format (PDF) documents are more prevalent than ever. A variety of enterprises use this file type for producing invoices, cover page and other documents. Developers add page numbers and page breaks to assist in meeting the needs of their clients. The libraries/NuGet packages that are readily available today for PDF generation have made creating PDFs simpler than ever. When choosing a .NET Library to use in our projects, We must take into account the ease in which the library helps us create, read, and write PDF files.

IronPDF Features

IronPDF is one of the best HTML-to-PDF converters available on the market. IronPDF can handle almost any operation that a browser is capable of handling. It can create PDF files from HTML5, JavaScript, CSS, and images. The .NET PDF library makes it simple to produce/generate PDF files, read existing PDFs, and edit PDF files. Possible modifications include changing font sizes, pagination, text content, etc. Users of IronPDF can create form fields in rendered PDF documents.

IronPDF is compatible with all .NET Framework project types, including ASP.NET, Windows Forms, and other traditional Windows application types. IronPDF is capable of rendering ASPX, Razor, and other MVC view components directly into PDFs.

IronPDF's full set of features include:

  • Convert images to PDFs (and PDF pages into images)
  • Merge and split PDFs
  • Complete PDF forms programmatically
  • Extract text and images from PDFs
  • IronPDF has the ability to convert picture files as well as HTML files to PDF.
  • IronPDF can merge and split PDFs, fill out and submit them programmatically, and extract text and images
  • Create PDFs from web pages, HTML markup, and offline HTML documents
  • Generate PDFs from web pages locked behind HTML login forms.
  • Annotate PDFs.
  • Add headers, footers, text, images, bookmarks, watermarks, and more

Creating a New Project in Visual Studio

This article will generate IronPDF's document generation abilities with a simple Console Application.

Open Visual Studio software and go to the File menu. Select "New project", and then select "Console App".

How to Generate PDFs from Templates, Figure 1: New Project

New Project

Specify the project name and its location. Click on the Next button and choose a .NET Framework.

How to Generate PDFs from Templates, Figure 2: .NET Framework Selection

.NET Framework Selection

Finally, click on Create to generate the new Visual Studio project.

How to Generate PDFs from Templates, Figure 3: .NET Program.cs

Program.cs

3. Install the IronPDF Library

The IronPDF library can be downloaded and installed in four ways.

These four ways are:

  • Use Visual Studio.
  • Use the Visual Studio Command-Line.
  • Download from the NuGet website directly.
  • Download from the IronPDF website directly.

3.1 Using Visual Studio

The NuGet Package Manager is available in the Visual Studio software for easy installation of packages from NuGet. The below screenshot shows how to open the NuGet Package Manager GUI.

How to Generate PDFs from Templates, Figure 4: NuGet Package Manager

NuGet Package Manager

Search for "IronPDF" in the Browse tab of the Package Manager GUI.

How to Generate PDFs from Templates, Figure 5: IronPDF Installation

IronPDF Installation

Choose the IronPdf package (first option) and click on the Install button to add it to the Solution.

3.2 Using the Visual Studio Command-Line

In Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console

Enter the following command in the Package Manager Console tab and press ENTER.

Install-Package IronPdf
How to Generate PDFs from Templates, Figure 6: Install IronPDF

Install IronPDF

3.3 Download from the NuGet Website Directly

  • Navigate to the link.
  • Click the Download package from the menu on the right-hand side.
  • Double-click the downloaded package from within Windows Explorer to install it in your project automatically.

3.4 Download from the IronPDF Website Directly

Click here to download the latest version of the IronPDF package.

Once downloaded, follow the steps below to add the package to the project.

  • Right-click the project from the Solution Explorer window.
  • Then, select the options Reference and browse the location of the downloaded reference.
  • Next, click OK to add the reference.

4. Create a PDF Document from Template

The code example below shows us how to create PDF files from the given HTML template with just a few lines of code.

var Renderer = new IronPdf.ChromePdfRenderer();
Renderer.RenderHtmlAsPdf(BuildTemplate()).SaveAs("Test.pdf");

        static string BuildTemplate()
        {
            var builder = new StringBuilder();
            builder.Append("<table border='1'>");
            builder.Append("<tr>");
            builder.Append("<th>");
            builder.Append("Cat Family");
            builder.Append("</th>");
            builder.Append("</tr>");
            foreach (var item in GetData())
            {
                builder.Append("<tr>");
                builder.Append("<td>");
                builder.Append(item.ToString());
                builder.Append("</td>");
                builder.Append("</tr>");
            }
            builder.Append("</table>");
            return builder.ToString();
        }
        static List<string> GetData()
        {
            List<string> _data = new List<string>();
            _data.Add("Lion");
            _data.Add("Tiger");
            _data.Add("Cat");
            _data.Add("cheetah");
            _data.Add("lynx");
            return _data;
        }
var Renderer = new IronPdf.ChromePdfRenderer();
Renderer.RenderHtmlAsPdf(BuildTemplate()).SaveAs("Test.pdf");

        static string BuildTemplate()
        {
            var builder = new StringBuilder();
            builder.Append("<table border='1'>");
            builder.Append("<tr>");
            builder.Append("<th>");
            builder.Append("Cat Family");
            builder.Append("</th>");
            builder.Append("</tr>");
            foreach (var item in GetData())
            {
                builder.Append("<tr>");
                builder.Append("<td>");
                builder.Append(item.ToString());
                builder.Append("</td>");
                builder.Append("</tr>");
            }
            builder.Append("</table>");
            return builder.ToString();
        }
        static List<string> GetData()
        {
            List<string> _data = new List<string>();
            _data.Add("Lion");
            _data.Add("Tiger");
            _data.Add("Cat");
            _data.Add("cheetah");
            _data.Add("lynx");
            return _data;
        }
Dim Renderer = New IronPdf.ChromePdfRenderer()
Renderer.RenderHtmlAsPdf(BuildTemplate()).SaveAs("Test.pdf")

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'		static string BuildTemplate()
'		{
'			var builder = New StringBuilder();
'			builder.Append("<table border='1'>");
'			builder.Append("<tr>");
'			builder.Append("<th>");
'			builder.Append("Cat Family");
'			builder.Append("</th>");
'			builder.Append("</tr>");
'			foreach (var item in GetData())
'			{
'				builder.Append("<tr>");
'				builder.Append("<td>");
'				builder.Append(item.ToString());
'				builder.Append("</td>");
'				builder.Append("</tr>");
'			}
'			builder.Append("</table>");
'			Return builder.ToString();
'		}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'		static List(Of string) GetData()
'		{
'			List<string> _data = New List<string>();
'			_data.Add("Lion");
'			_data.Add("Tiger");
'			_data.Add("Cat");
'			_data.Add("cheetah");
'			_data.Add("lynx");
'			Return _data;
'		}
VB   C#

In the above code, first create an object for the IronPDF class which allow us to access all the features of the IronPDF. Then we use the RenderHtmlAsPdf method to create a PDF document for us from the HTML string. By using the RenderHtmlAsPdf method, we can use a string of any length. This method also accepts references to internal and external CSS files that the string may include.

We are building an HTML string from the list. Lists have the set of values of the type string or data model object. In this example, we are using list of string type and building HTML template with the HTML tag table, table row, table definition. We are using the for loop to bind the data one by one with the given HTML template. We can pass any string type or data model object list and save them into a PDF file.

Below is the sample PDF file, which is generated from the above code with just a few lines by using the given template.

How to Generate PDFs from Templates, Figure 7: Generated PDF File

Generated PDF File

We can use any type of HTML tag to create template which can help the user to generate user form, receipts etc., with sample template but different data.

We can also create PDFs from HTML files. For that we can use the method RenderUrlAsPdf or RenderHtmlFileAsPdf. The former method accepts a URL to a webpage, while the latter accepts a string containing the location of an HTML file on the computer.

Read this tutorial for more information about generating PDFs from HTML.

Conclusion

Use IronPDF in production without watermark with a free trial key. IronPDF comes with SaaS and OEM Redistribution licensing for an additional cost. To know more, refer to the Licensing page.