Problem Statement

This is a very regular requirement especially for online education or E-commerce applications, a user will be given an option to download the payment receipts or certificates on demand.

Solution

In this article will discuss how can we generate a new PDF file and allowing to download on demand. Let’s we initiate with a requirement of printing a payment receipt on demand using ASP.NET and C# language for this example. Don’t worry will discuss how can we achieve the same using MVC too.

Following are the steps to code and fulfill our requirement

Step-1: Need to generate a payment receipt with existing data from the database using any tools like PDFsharp. Currently, I am referring PDFsharp tool to convert my HTML to PDF and store on my server. 

using sharpPDF; 

    public void CreatePDFFromHtml(string htmlContent, string filePath) 
    { 
        PdfSharp.Pdf.PdfDocument pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(htmlContent, PdfSharp.PageSize.A4); 
        pdf.Save(filePath);       
    }

 Step-2: Now we need to call this common helper method by sending the generated HTML content along with temporary file path on the server. For generating HTML content, need to maintain a separate page with placeholders such that you can replace these with valid content/data from database as below 

string htmlContent = File.ReadAllText(Path.Combine(Server.MapPath("~"), "PaymentTemplate.html")); 
htmlContent = htmlContent.Replace("$$licensee", dsReceiptdata.Tables[0].Rows[0]["Licensee"].ToString()); 
htmlContent = htmlContent.Replace("$$paymentdate", dsReceiptdata.Tables[0].Rows[0]["PaymentDate"].ToString()); 
htmlContent = htmlContent.Replace("$$streetaddress", dsReceiptdata.Tables[0].Rows[0]["LicenseNumber"].ToString()); 
htmlContent = htmlContent.Replace("$$city", dsReceiptdata.Tables[0].Rows[0]["City"].ToString()); 
htmlContent = htmlContent.Replace("$$state", dsReceiptdata.Tables[0].Rows[0]["State"].ToString()); 
htmlContent = htmlContent.Replace("$$zipcode", dsReceiptdata.Tables[0].Rows[0]["ZipCode"].ToString()); 
htmlContent = htmlContent.Replace("$$paymenttype", dsReceiptdata.Tables[0].Rows[0]["PaymentType"].ToString()); 
htmlContent = htmlContent.Replace("$$ccnumber", dsReceiptdata.Tables[0].Rows[0]["CCNumber"].ToString()); 
htmlContent = htmlContent.Replace("$$orderid", dsReceiptdata.Tables[0].Rows[0]["OrderID"].ToString());

 Step-3: Once we have the valid HTML content, we need to call the PDF helper method which we created in step 1. 

string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "Temp", "GeneratedPayment_" + Guid.NewGuid().ToString() + ".pdf"); 

PdfClass pdfcls = new PdfClass(); 
pdfcls.CreatePDFFromHtml(htmlContent, filePath);

Step-4: Now we are done with generating the PDF file, now the time to send this PDF file as a content to the client and downloads it.  Following is the straightforward set of code used to feed the generated PDF file into the response stream and flushing the complete data to the client as a stream. The file type will be identified by the client browser based on the given file name. 

HttpResponse res = HttpContext.Current.Response; 
res.Clear(); 
res.AppendHeader("content-disposition", "attachment; filename=PaymentReceipt.pdf"); 
res.ContentType = "application/octet-stream"; 
res.WriteFile(filePath); 
res.Flush(); 
res.End();

In MVC, to achieve the same functionality we have built-in File return type as below 

return File("PaymentReceipt.pdf", "application/pdf", filePath);

Hope you got enough information about how we need to generate a PDF file on demand using existing HTML template and downloading at the client side.

Happy Coding 🙂