Topics
How to Export HTML string to PDF file using iTextSharp DLL in C#
Introduction
In this article, I will explain you how to export HTML table student details to PDF file. For this demo purpose I am using iTextSharp XMLWorkerHelper library.
Step 1: Download iTextSharp XMLWorkerHelper library
Click here to download iTextSharp XMLWorkerHelper library.
Once you download the library file. Extract the file and import those 2 DLL file in your project
Step 2: Create new asp.net empty application.
Step 3: Add index.html file into your project and add following code in between body tag.
<form id="form1" runat="server"> <div id = "Studenttable"> <table style="border:solid 1px;"> <tr> <th>Student Id</th> <th>Student Name</th> <th>Student Branch</th> </tr> <tr> <td>1</td> <td>John Smith</td> <td>Computer Engineering</td> </tr> <tr> <td>2</td> <td>David Jones</td> <td>Civil Engineering</td> </tr> <tr> <td>3</td> <td>Michael Johnson</td> <td>Chemical Engineering</td> </tr> <tr> <td>4</td> <td>Chris Lee</td> <td>Electrical Engineering</td> </tr> <tr> <td>5</td> <td>Mike Brown</td> <td>Computer Engineering</td> </tr> </table></div> <br /> <asp:HiddenField ID="hfGridHtml1" runat="server" OnValueChanged="hfGridHtml_ValueChanged" /> <asp:Button ID="btnExport" runat="server" Text="Export To PDF File" OnClick="ExportToPDF" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("[id*=btnExport]").click(function () { $("[id*=hfGridHtml1]").val($("#Studenttable").html()); }); }); </script> </form>
Step 4: Add follwing code to export to pdf file button click
StringReader sr = new StringReader(Request.Form[hfGridHtml1.UniqueID]); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr); pdfDoc.Close(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=StudentDetails.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Write(pdfDoc); Response.End();
Step: 5 Result