Thursday, April 25, 2024
HomeC#Generate Dynamic PDF Studies from an HTML Template Utilizing C#

Generate Dynamic PDF Studies from an HTML Template Utilizing C#


Producing PDF paperwork from the scratch is at all times a troublesome course of and has the next disadvantages:

  • It’s time-consuming.
  • It’s difficult to design a fancy PDF.
  • It’s vulnerable to errors.

It’s at all times advisable to generate PDF paperwork from well-designed HTML templates. On this weblog submit, we’ll see easy methods to generate PDF stories from HTML templates utilizing Syncfusion’s HTML-to-PDF converter in C#.

The HTML-to-PDF converter helps all fashionable options akin to HTML5, CSS3, SVG, and internet fonts. So, you may simply type your PDF stories by updating the CSS file along with your pictures and fonts in C#.

To reveal this, we’re going to generate a PDF bill from an HTML template utilizing C# with the next steps:

  1. Create an HTML template.
  2. Entry the information and bind it with an HTML template.
  3. Convert the HTML string to PDF.

Create an HTML template

An HTML template incorporates placeholders with {{mustache}} syntax. It’s used to bind the precise information to the HTML template. For this instance, we’ll use the Scriban scripting language to create the placeholders. It’s a light-weight scripting language and engine for .NET.

Notice: To study extra in regards to the Scriban scripting language, seek advice from the documentation.

The next code instance exhibits the information mannequin for the bill.

public class Bill
{
  public string InvoiceNumber { get; set; }
  public string IssueDate { get; set; }
  public string DueDate { get; set; }

  public UserDetails CompanyDetails { get; set; }
  public UserDetails CustomerDetails { get; set; }

  public Listing<Merchandise> Gadgets { get; set; }

  public decimal SubTotal
  {
    get
    {
      return Gadgets.Sum(x => x.Worth * x.Amount);
    }
  }

  public float Tax
  {
    get
    {
       return (float)SubTotal * (25f / 100f);
    }
  }

  public float GrandTotal
  {
    get
    {
      return (float)SubTotal + Tax;
    }
  }
}

Primarily based on this mannequin, we design the template as follows. By default, the properties and strategies of .NET objects are mechanically uncovered with lowercase and _ names. Which means a property like Bill.CompanyDetails.Title will probably be uncovered as bill.company_details.title. That is the default conference.

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Bill</title>
    <hyperlink rel="stylesheet" href="https://www.syncfusion.com/blogs/submit/type.css" media="all" />
  </head>
  <physique>
    <header class="clearfix">
      <div id="brand">
        <img src="brand.png">
      </div>
      <div id="firm">
        <h2 class="title">{{bill.company_details.title}}</h2>
        <div>{{bill.company_details.handle}}</div>
        <div>{{bill.company_details.telephone}}</div>
        <div>{{bill.company_details.e-mail}}</div>
      </div>
      </div>
    </header>
    <fundamental>
      <div id="particulars" class="clearfix">
        <div id="shopper">
          <div class="to">INVOICE TO:</div>
          <h2 class="title">{{bill.customer_details.title}}</h2>
          <div class="handle">{{bill.customer_details.handle}}</div>
          <div class="e-mail">{{bill.customer_details.e-mail}}</div>
        </div>
        <div id="bill">
          <h1>{{bill.invoice_number}}</h1>
          <div class="date">Date of Bill: {{bill.issue_date}}</div>
          <div class="date">Due Date: {{bill.due_date}}</div>
        </div>
      </div>
      <desk border="0" cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <th class="no">#</th>
            <th class="desc">DESCRIPTION</th>
            <th class="unit">UNIT PRICE</th>
            <th class="qty">QUANTITY</th>
            <th class="complete">TOTAL</th>
          </tr>
        </thead>
        <tbody id="invoiceItems">
		  {{- index = 1 -}}
		  {{ for merchandise in bill.gadgets }}
          <tr>
            <td class="no">{{index}}</td>
            <td class="desc"><h3>{{merchandise.title}}</h3>{{merchandise.description}}</td>
            <td class="unit">${{merchandise.value}}</td>
            <td class="qty">{{merchandise.amount}}</td>
            <td class="complete">${{merchandise.total_price}}</td>
          </tr>
		  {{index = index + 1}}
		  {{finish}}
        </tbody>
        <tfoot>
          <tr>
            <td colspan="2"></td>
            <td colspan="2">SUBTOTAL</td>
            <td>${{bill.sub_total}}</td>
          </tr>
          <tr>
            <td colspan="2"></td>
            <td colspan="2">TAX 25%</td>
            <td>${{bill.tax}}</td>
          </tr>
          <tr>
            <td colspan="2"></td>
            <td colspan="2">GRAND TOTAL</td>
            <td>${{bill.grand_total}}</td>
          </tr>
        </tfoot>
      </desk>
      <div id="thanks">Thanks!</div>
      <div id="notices">
        <div>NOTICE:</div>
        <div class="discover">A finance cost of 1.5% will probably be made on unpaid balances after 30 days.</div>
      </div>
    </fundamental>
  </physique>
</html>

You may get this HTML template with CSS and fonts from this GitHub repository.

The next screenshot exhibits the output of the HTML template with styled CSS.

Invoice HTML template
Bill HTML template

Entry the information and bind it with the HTML template

To simplify this text, we now have used a customized JSON file to retailer and retrieve the information. The next code snippet is used to create the bill mannequin.

Bill bill= JsonConvert.DeserializeObject<Bill>(File.ReadAllText("../../../InvoiceData.json"));

Now, we use Scriban to bind the information from the mannequin to the HTML template, as defined within the following code instance.

//Load html HTML template.
var invoiceTemplate = File.ReadAllText("../../../Template/index.html");
var template = Template.Parse(invoiceTemplate);
var templateData = new { bill };
//Fill template with actual bill information.
var pageContent = template.Render(templateData);

Convert HTML string to PDF

The final step is to generate the bill PDF from the certain HTML created within the earlier part.

We use the HtmlToPdfConverter to transform the HTML string to a PDF doc. Seek advice from the next code instance.

//Initialize HTML to PDF converter with Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

//Convert HTML string to PDF. 
PdfDocument doc = htmlConverter.Convert(pageContent , Path.GetFullPath("Template"));

FileStream fs = new FileStream("Output.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and shut the PDF doc.
doc.Save(fs);

doc.Shut(true);

After the conversion, you’ll get a PDF doc like within the following screenshot.

Invoice PDF document
Bill PDF doc

GitHub samples

For higher understanding, we now have dedicated the supply for this challenge within the PDF technology from HTML template GitHub repository.

Conclusion

On this weblog submit, we now have discovered easy methods to generate PDF stories from an HTML template utilizing Syncfusion’s C# HTML-to-PDF converter.

Take a second to take a look at the documentation, the place you will discover different choices and options, all with accompanying code samples.

Please tell us within the feedback beneath in case you have any questions on these options. You too can contact us via our help discussion board, help portal or suggestions portal. We’re completely happy to help you!

Associated blogs

When you appreciated this text, we predict you’d additionally like the next articles about PDF Library:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments