Firstly install a package called iTextSharp through Nuget Package .
Add following namespaces.
- using iTextSharp.text;
- using iTextSharp.text.html.simpleparser;
- using iTextSharp.text.pdf;
-
- public class PdfController : Controller
- {
-
-
- public void DownloadPDF()
- {
- string HTMLContent = "Hello <b>World</b>";
- Response.Clear();
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- Response.BinaryWrite(GetPDF(HTMLContent));
- Response.End();
- }
-
- public byte[] GetPDF(string pHTML)
- {
- byte[] bPDF = null;
-
- MemoryStream ms = new MemoryStream();
- TextReader txtReader = new StringReader(pHTML);
-
-
- Document doc = new Document(PageSize.A4, 25, 25, 25, 25);
-
-
- PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);
-
-
- HTMLWorker htmlWorker = new HTMLWorker(doc);
-
-
- doc.Open();
- htmlWorker.StartDocument();
-
-
-
- htmlWorker.Parse(txtReader);
-
-
- htmlWorker.EndDocument();
- htmlWorker.Close();
- doc.Close();
-
- bPDF = ms.ToArray();
-
- return bPDF;
- }
- }
Run the application localhost/pdf/downloadpdf.