Generate PDF Using iTextSharp In ASP.NET MVC

Firstly install a package called iTextSharp through Nuget Package .

Add following namespaces.

  1. using iTextSharp.text;  
  2. using iTextSharp.text.html.simpleparser;  
  3. using iTextSharp.text.pdf;  
  4.   
  5. public class PdfController : Controller  
  6.     {  
  7.   
  8.        
  9.         public void DownloadPDF()  
  10.         {  
  11.             string HTMLContent = "Hello <b>World</b>";  
  12.             Response.Clear();  
  13.             Response.ContentType = "application/pdf";  
  14.             Response.AddHeader("content-disposition""attachment;filename=" + "PDFfile.pdf");  
  15.             Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  16.             Response.BinaryWrite(GetPDF(HTMLContent));  
  17.             Response.End();  
  18.         }  
  19.   
  20.         public byte[] GetPDF(string pHTML)  
  21.         {  
  22.             byte[] bPDF = null;  
  23.   
  24.             MemoryStream ms = new MemoryStream();  
  25.             TextReader txtReader = new StringReader(pHTML);  
  26.   
  27.             // 1: create object of a itextsharp document class  
  28.             Document doc = new Document(PageSize.A4, 25, 25, 25, 25);  
  29.   
  30.             // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file  
  31.             PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);  
  32.   
  33.             // 3: we create a worker parse the document  
  34.             HTMLWorker htmlWorker = new HTMLWorker(doc);  
  35.   
  36.             // 4: we open document and start the worker on the document  
  37.             doc.Open();  
  38.             htmlWorker.StartDocument();  
  39.   
  40.              
  41.             // 5: parse the html into the document  
  42.             htmlWorker.Parse(txtReader);  
  43.   
  44.             // 6: close the document and the worker  
  45.             htmlWorker.EndDocument();  
  46.             htmlWorker.Close();  
  47.             doc.Close();  
  48.   
  49.             bPDF = ms.ToArray();  
  50.   
  51.             return bPDF;  
  52.         }  
  53.     }  
Run the application localhost/pdf/downloadpdf.