Sunday, March 23, 2014

Create PDF files in C#

Creating PDF files is a very important thing in web tech. You need to generate PDF files to show some result of user. To create you need to import few namespaces.

 using iTextSharp.text;
 using iTextSharp.text.pdf;
 using iTextSharp.text.html;
 using System.IO;
 using System.Text.RegularExpressions;
 using iTextSharp.text.html.simpleparser;

Now create a project and add  page named PdfDemo. Now copy bellow code and paste into the c# page of your created page.

<body>
    <form id="form1" runat="server">
    <div id="print" runat="server">
     This is the prining div......
     <br />
     ASP <i>With Arka</i>
    </div>
    </form>
</body>

And C# code is..

 Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment;filename=demo.pdf");
 Response.Cache.SetCacheability(HttpCacheability.NoCache);
 
 StringWriter sw = new StringWriter();
 
 HtmlTextWriter w = new HtmlTextWriter(sw);
 print.RenderControl(w);
 
 string htmWrite = sw.GetStringBuilder().ToString();
 htmWrite = Regex.Replace(htmWrite, "</?(a|A).*?>", "");
 htmWrite = htmWrite.Replace("\r\n", "")
 StringReader reader = new StringReader(htmWrite);
 
 Document doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
 string pdfFilePath = Server.MapPath(".") + "/PDFFiles";
 
 HTMLWorker htmlparser = new HTMLWorker(doc);
 PdfWriter.GetInstance(doc, Response.OutputStream);
 
 doc.Open();
 
 try
 {
     htmlparser.Parse(reader);
     doc.Close();
     Response.Write(doc);
     Response.End();
 }
 catch (Exception ex)
 {
     Response.Write("<script>alert('"+ex.Message+"');</script>");
 }
 finally
 {
     doc.Close();
 }


Now run your project and enjoy your pdf.
Download the source code here.


0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews