In the GrapeCity Documents v3.1 release, we are pleased to offer a new Documents for PDF (GcPdf) enhancement. Users can now generate data-bound PDF reports through an HTML template.

Generating documents through a template saves not only time but also avoids possible errors. In the previous release, GcExcel introduced Excel templates. Excel templates offer the ability to create dynamic Excel & PDF reports. In this article, we'll describe how to generate PDF reports from HTML templates.

Before digging deeper into the implementation, let’s first understand how HTML templates differ from standard HTML files.

HTML vs HTML Templates

While HyperText Markup Language (HTML) is a standard markup language for pages designed to display in a web browser, HTML templates also define placeholders for containing upcoming data fields using {{mustache}} syntax. Using this syntax allows binding data fields to the database and shows the data value in these placeholders.

This article demonstrates how to generate data-bound PDF files using C# .NET. Here, we'll learn how to create a valid HTML template, collect data, and make PDF documents based on the HTML template.

How Does Templating Work?

Data bound PDF report generation is a 3-step process.

Step 1:

The first step further involves the following two sub-steps:

A.) Creating an HTML Template

To generate data-bound PDF reports dynamically, GcPdf requires an HTML template. This HTML template following template syntax defines the layout which the final PDF report is rendered.

B.) Accessing Data

We can use data from various data sources like DataTable etc. The data obtained will be used to bind the HTML template created above.

Step 2:

Once the template is ready and data is accessed, bind the template to the accessed data. This is done through ‘Stubble.Core’ package.

Step 3:

Completion of step 2 outputs a bound HTML. This HTML is converted to a final PDF report through ‘GcHtmlRenderer’ class. Now that we understand how the dynamic report generation process works let’s take a real scenario.

Use Cases – Dynamically Generating a Product Price List

Essentially, a price sheet is a list of costs for all the price-able components. A product price list serves many benefits, from informing the salesperson, to product sales cost, to product benefits.

Let’s say a retail corporation wants to prepare the price list for all the products sold by the outlet. However, since the product prices can fluctuate, new products can be added, existing products can fall out of stock.

It can be cumbersome for the corporation to track and keep the product price list updated continuously. This is where dynamic report generation, through templates, can help.

Once you design the HTML template, apply simple code to bind the template with the database. GcPdf will quickly generate a separate PDF report and listing pricing for the products.

Below you can see how the final product PDF price list (in a PDF report) would look:

Product list template PDF

To generate a product price list PDF report, you need first to create an HTML template. The HTML template creation is crucial (as to whether the final PDF report shows all data values correctly) depends on the HTML template.

Let’s familiarize ourselves with creating valid HTML templates.

Creating HTML Template for GcPdf

Any HTML can be a valid HTML template for GcPdf if it follows the Mustache template system. The syntax used in the system is straightforward, requiring no complicated logic for getting object values.

To understand better, let's see how to create an HTML template for our use case: generating a product price list. The most crucial portion for the HTML template is the portion that includes placeholders for data. The data placeholders are where you want to show dynamically generated field values (like Product name, Supplier name).

To understand precisely how to define data fields, let's see how to show a product's ID as displayed in the final PDF report image above.

According to the report image, the values are in tabular format, where each record contains product ID value. Therefore, we should define the table cell as:

<tr>
  <td></td>
</tr>

Similarly, we'll define other table cells. The following is the complete code for the body in HTML template:

<body>
    <h1>Product Price List</h1>
    <table id='products'>
      <thead>
        <th>Product ID</th>
        <th>Description</th>
        <th>Supplier</th>
        <th>Quantity Per Unit</th>
        <th>Unit Price</th>
      </thead>
    </table>
  </body>

ProductListTemplate.html

The above HTML with styles appended should give the output as shown in below image:

Creating Data-Bound PDF from HTML Template

Once the HTML template with placeholders for data is built, further implementation can be broadly categorized into:

  1. Data access
  2. Bind the HTML template with data
  3. Convert the bound HTML to PDF format
  4. Customize the PDF

To implement these, let’s create a class ‘ProductListTemplate’ with a ‘CreatePdf’ method. Since, we need to import HTML template and generate a PDF report, let’s declare this method to take two arguments:

public class ProductListTemplate
{
    public void CreatePDF(string TemplatePath, string PdfPath)
    {}
}
1. Accessing Data

For this example, we will fetch data from the shared database ‘GcNwind.xml’ that contains multiple tables like Categories, Products, Orders.

As we see in the final PDF image above, data fields like ProductName, Supplier, QuantityPerUnit are present in the final expected report. We will access the Products & Suppliers tables and join them to show only the relevant data w.r.t showing information about the product and its details, like UnitPrice, and Supplier.

The following code demonstrates the implementation of accessing the data.

// Fetch data
DataSet ds = new DataSet();
ds.ReadXml(Path.Combine("Resources", "data", "GcNWind.xml"));

DataTable dtProds = ds.Tables["Products"];
DataTable dtSupps = ds.Tables["Suppliers"];

var products = from prod in dtProds.Select()
               join supp in dtSupps.Select()
               on prod["SupplierID"] equals supp["SupplierID"]
               orderby prod["ProductName"]
               select new
               {
                   ProductID = prod["ProductID"],
                   ProductName = prod["ProductName"],
                   CompanyName = supp["CompanyName"],
                   QuantityPerUnit = prod["QuantityPerUnit"],
                   UnitPrice = $"{prod["UnitPrice"]:C}"
               };
2. Binding HTML Template with Data

As the HTML template and the product related data are available now, we need to bind the HTML template to the data accessed. For binding the template, we'lll use Stubble.Core package and its StubbleBuilder class.

// Bind the template to data:
var builder = new Stubble.Core.Builders.StubbleBuilder();
var boundTemplate = builder.Build().Render(TemplatePath, new { Query = products });
3. Converting Bound HTML to PDF

The final step is to generate the product price list. To convert the bound HTML that was returned through the render method in the StubbleBuilder class, we'll use the GcHtmlRenderer class with the bound HTML template string as its parameter.

However, to use the GcHtmlRenderer class, we first need to import the following namespace

using GrapeCity.Documents.Html;

GcHtmlRenderer exposes a method ‘RenderToPdf’ that converts the HTML string and creates a corresponding pdf file. With the help of this method, we will convert the bound HTML to PDF format.

// Render the bound HTML
using (var re = new GcHtmlRenderer(boundTemplate))
{
    re.RenderToPdf(PdfPath};
}

Note: Using GcHtmlRenderer requires a GcPdf license to convert HTML to PDF. Without a valid license, only a PDF up to five pages can be created. GcHtml allows licensing either single instance of GcHtmlRenderer (using ApplyGcPdfLicenseKey method) or licensing all cases of GcHtmlRenderer (using SetGcPdfLicenseKey method).

4. Customizing the PDF

Additionally, while creating the PDF file, we can customize it. Margins, header, and footer can all be added to the PDF file while converting the bound HTML template with GcHtmlRenderer.

Example: We can add the page numbers in a page header and the corporate brand name in the page footer.

This can be done through the PdfSettings class in the namespace GrapeCity.Documents.HTML. The PdfSettings can be passed to the RenderToPdf method used above.

// Render the bound HTML
using (var re = new GcHtmlRenderer(boundTemplate))
{
    // PdfSettings allow to provide options for HTML to PDF conversion:
    var pdfSettings = new PdfSettings()
    {
        Margins = new Margins(0.2f, 1, 0.2f, 1),
        IgnoreCSSPageSize = true,
        DisplayHeaderFooter = true,
        HeaderTemplate = "<div style='color:#1a5276; font-size:12px; width:1000px; margin-left:0.2in; margin-right:0.2in'>"+"<span style='float:left;'>Product Price List</span>"+"<span style='float:right'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></span>"+"</div>",
        FooterTemplate = "<div style='color: #1a5276; font-size:12em; width:1000px; margin-left:0.2in; margin-right:0.2in;'>"+"<span>(c) GrapeCity, Inc. All Rights Reserved.</span>"+"<span style='float:right'>Generated on <span class='date'></span></span></div>" 
    };
    // Render the generated HTML to the pdf file path:
    re.RenderToPdf(PdfPath, pdfSettings);
}

With this, we complete the ‘ProductListTemplate’ class that shows how an HTML template can generate a PDF report for listing product prices.

ProductListTemplate.cs

Now, let’s see how to use the class created above in a .NetCore application to generate a price list of the products in PDF format using an HTML template.

Setting up the Application

1. Installation

  • 1.1 Create a .Net Core Console application.
  • 1.2 To add GcPdf assemblies, right-click ‘Dependencies," and select ‘Manage NuGet Packages."
  • 1.3 Under the ‘Browse’ tab search for GrapeCity.Documents.Pdf and click Install.
  • 1.4 While installing, you’ll receive two confirmation dialogs: ‘Preview Changes’ and ‘License Acceptance.' click ‘Ok’ , and ‘I Agree’ respectively to continue.

2. Setup your project

  • 2.1 Add namespace

In the Program file, import following namespace:

using GrapeCity.Documents.Pdf;

  • 2.2 Creating PDF from HTML template To get the price list of products in PDF from the HTML template, create an object of the class ‘ProductListTemplate’ we created above:

var sample = new ProductListTemplate();

Now, using the ‘ProductListTemplate’ object, invoke its ‘CreatePdf’ method with the template path and expected PDF report name:

string templatePath = File.ReadAllText(Path.Combine("Resources", "Misc", "ProductListTemplate.html"));
string pdfPath = "ProductListTemplate.pdf";
sample.CreatePdf(templatePath, pdfPath);

The code above will generate a PDF listing down the prices for all the products.

Attached is the complete Visual Studio application along with the HTML template. Feel free to download and experiment!

You can also check the full implementation and other features of GcPdf here.

We discussed what HTML templates are, how to create them, and how these templates can be used to dynamically generate data-bound PDF reports.

If you want to generate data-bound reports in PDF, try using this feature. If you have any suggestions, feel free to leave a comment below.

Try a GcPdf free trial for 30 days

Download the latest version of GrapeCity Documents for PDF

Download Now!