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 using JavaScript and jQuery 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
![Export (Convert) GridView to PDF using JavaScript and jQuery in ASP.Net](https://www.aspsnippets.com/Handlers/DownloadFile.ashx?File=f1e22b99-94ee-410e-9067-c3c3fbe4d478.png)
PDF file being downloaded when Export Button is clicked
![Export (Convert) GridView to PDF using JavaScript and jQuery in ASP.Net](https://www.aspsnippets.com/Handlers/DownloadFile.ashx?File=8caf9cc9-92b5-4f2a-8ddd-0e7a4fc19dbf.png)
The generated PDF file
![Export (Convert) GridView to PDF using JavaScript and jQuery in ASP.Net](https://www.aspsnippets.com/Handlers/DownloadFile.ashx?File=748d145e-e807-47ef-8670-e561732344f0.png)
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
![Internet Explorer](https://www.aspsnippets.com/images/browsers/IE.gif)
![FireFox](https://www.aspsnippets.com/images/browsers/FF.gif)
![Chrome](https://www.aspsnippets.com/images/browsers/CH.gif)
![Safari](https://www.aspsnippets.com/images/browsers/SF.gif)
![Opera](https://www.aspsnippets.com/images/browsers/OP.gif)
* All browser logos displayed above are property of their respective owners.
No comments:
Post a Comment