Saturday 3 August 2019

Export (Convert) GridView to PDF using JavaScript and jQuery in ASP.Net


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
 
PDF file being downloaded when Export Button is clicked
Export (Convert) GridView to PDF using JavaScript and jQuery in ASP.Net
 
The generated PDF file
Export (Convert) GridView to PDF using JavaScript and jQuery in ASP.Net
 
 
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 
* All browser logos displayed above are property of their respective owners.

No comments:

Post a Comment