In this article I will explain with an example, how to export GridView to PDF without using iTextSharp in ASP.Net.
This article will illustrate how to export GridView to PDF using jQuery in ASP.Net.
The GridView’s HTML Table will be first converted into a HTML5 Canvas using html2canvas plugin and then the HTML5 Canvas will be exported to PDF file using the pdfmake plugin in jQuery.
HTML Markup
The following HTML Markup consists of an ASP.Net GridView and an HTML Button.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="80" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
</Columns>
</asp:GridView>
<br />
<input type="button" id="btnExport" value="Export" />
Exporting (Converting) GridView to PDF without using iTextSharp in ASP.Net
The Export Button has been assigned a jQuery click event handler.
When the Export Button is clicked, the GridView’s HTML Table is converted into a HTML5 Canvas using html2canvas plugin and then the HTML5 Canvas will be exported to PDF file using the pdfmake plugin.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.22/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script type="text/javascript">
$("body").on("click", "#btnExport", function () {
html2canvas($('[id*=GridView1]')[0], {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var docDefinition = {
content: [{
image: data,
width: 500
}]
};
pdfMake.createPdf(docDefinition).download("Table.pdf");
}
});
});
</script>
Screenshots
The GridView
PDF file being downloaded when Export Button is clicked
The generated PDF file
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
* All browser logos displayed above are property of their respective owners.
No comments:
Post a Comment