Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Imports System.IO
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports APNSoft.WebControls

Imports iTextSharp.text
Imports iTextSharp.text.pdf

Partial Public Class DataGrid_RowExporting
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        'Apply server-side events
        AddHandler myDataGrid.ExportToExcel, AddressOf myDataGrid_ExportToExcel
        AddHandler myDataGrid.ExportToHTML, AddressOf myDataGrid_ExportToHTML
        AddHandler myDataGrid.ExportCustom, AddressOf myDataGrid_ExportCustom


        'Define SQL query
        Dim SqlQuery As String = "SELECT C.CategoryName, C.Description, Sum(OD.UnitPrice*OD.Quantity) AS InTotal " & _
            "FROM (Categories as C INNER JOIN Products AS P ON C.CategoryID = P.CategoryID) " & _
            "INNER JOIN [Order Details] AS OD ON P.ProductID = OD.ProductID " & _
            "GROUP BY C.CategoryName, C.Description ORDER BY CategoryName;"


        'Get DataTable (MS Access Database)
        Dim myDataSource As DataTable = DataBase.GetDataTableOleDb(SqlQuery, "~/DataGrid/DataBases/Nwind.mdb")

        'Set the data source
        'myDataGrid.KeyFieldName = "CustomerID";
        myDataGrid.DataSource = myDataSource
        myDataGrid.DataBind()


        'Format data
        Dim format As System.IFormatProvider = New System.Globalization.CultureInfo("en-US", True)
        myDataGrid.Columns("InTotal").FormatProvider = format
        myDataGrid.Columns("InTotal").FormatType = GetType(System.Decimal)
        myDataGrid.Columns("InTotal").FormatString = "C"
    End Sub

    'Server-side procedure for Export to Excel
    Private Sub myDataGrid_ExportToExcel(ByVal sender As Object, ByVal e As DataGridEventArgs)
        'Set file name (optional)
        e.ExportFileName = "ExportData.xls"
    End Sub


    'Server-side procedure for Export to HTML
    Private Sub myDataGrid_ExportToHTML(ByVal sender As Object, ByVal e As DataGridEventArgs)
        'Set file name (optional)
        e.ExportFileName = "ExportData.html"
    End Sub


    'Server-side procedure for Export to custom format
    Private Sub myDataGrid_ExportCustom(ByVal sender As Object, ByVal e As DataGridEventArgs)

        'Declarations
        Dim buffer() As Byte = Nothing 'Bytes to export
        Dim myMemoryStream As New MemoryStream()


        'Get Grid Data
        Dim myGrid As APNSoftDataGrid = CType(sender, APNSoftDataGrid)
        Dim myRows As GridRowCollection = myGrid.Rows
        Dim myColumns As GridColumnCollection = myGrid.Columns


        'Create PDF
        If e.Parameter = "PDF" Then

'            #Region "Create PDF document"


            'Create & open PDF document
            Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 50, 50, 50, 50)
            Dim wri As PdfWriter = PdfWriter.GetInstance(doc, myMemoryStream)
            doc.Open()


'            #Region "Add Table"

            Dim table As New PdfPTable(3)
            Dim cell As PdfPCell = Nothing

            'Specify the font
            Dim myFont As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)

            'Set column widths
            Dim widths() As Single = { 100, 300, 100 }
            table.SetWidths(widths)


            'Add column headers
            For i As Integer = 0 To myColumns.Count - 1
                cell = New PdfPCell(New Phrase(myColumns(i).ColumnName, myFont))
                cell.BackgroundColor = New BaseColor(192, 192, 192)
                cell.PaddingBottom = 4f
                table.AddCell(cell)
            Next i


            'Add rows
            For i As Integer = 0 To myRows.Count - 1
                For j As Integer = 0 To myColumns.Count - 1
                    Dim CellValue As Object = myRows(i).Cells(j).Value

                    'Format the InTotal
                    If myColumns(j).ColumnName = "InTotal" Then
                        CellValue = (CDec(CellValue)).ToString("C", New System.Globalization.CultureInfo("en-US", True))
                    End If

                    cell = New PdfPCell(New Phrase(CellValue.ToString(), myFont))
                    cell.PaddingBottom = 4f
                    table.AddCell(cell)
                Next j
            Next i


            doc.Add(table)

'            #End Region


            'Close the PDF document
            doc.Close()

            'Get Bytes
            buffer = myMemoryStream.ToArray()


'            #End Region


            'Set Bytes
            e.ExportBytes = buffer

            'Set file name
            e.ExportFileName = "ExportData.pdf"

            'Set ContentType
            e.ExportContentType = "application/pdf"

            GoTo Completed

        End If


        'Create PNG
        If e.Parameter = "Image" Then

'            #Region "Create PNG image"

            'Declarations
            Dim Angle As Integer = 0
            Dim AngleNext As Integer = 0
            Dim Offset As Integer = 20
            Dim Diameter As Integer = 160
            Dim InTotalSum As Decimal = 0
            Dim arrColor() As Object = { Color.Red, Color.Green, Color.Gold, Color.Maroon, Color.Blue, Color.Gray, Color.Violet, Color.Tan}

            'Create image
            Dim bmp As New Bitmap(420, 200, PixelFormat.Format32bppArgb)
            Dim g As Graphics = Graphics.FromImage(bmp)
            Dim fnt As New System.Drawing.Font("Arial", 8)
            Dim sb As New SolidBrush(Color.Gray)
            g.Clear(Color.White)
            g.SmoothingMode = SmoothingMode.HighQuality


            'Get InTotalSum
            For i As Integer = 0 To myRows.Count - 1
                InTotalSum += CDec(myRows(i).Cells("InTotal").Value)
            Next i


            'Draw pie with labels
            For i As Integer = 0 To myRows.Count - 1
                Dim InTotal As Decimal = CDec(myRows(i).Cells("InTotal").Value)
                Dim Percent As Integer = CInt(Fix(Math.Round(CDec(InTotal / InTotalSum) * 100)))
                Dim CategoryName As String = CStr(myRows(i).Cells("CategoryName").Value)

                AngleNext = AngleNext + Percent
                Dim Piece As Integer = (AngleNext * 360 \ 100) - Angle

                g.FillPie(New SolidBrush(CType(arrColor(i), Color)), Offset, Offset, Diameter, Diameter, Angle, Piece) 'Add piece of pie
                g.FillRectangle(New SolidBrush(CType(arrColor(i), Color)), New System.Drawing.Rectangle(Offset + Diameter + 30, Offset + i * 20, 15, 15)) 'Add label box

                'Format the InTotal
                Dim InTotalFormatted As String = InTotal.ToString("C", New System.Globalization.CultureInfo("en-US", True))
                g.DrawString(CategoryName & " - " & _
            Percent & "% (" & _
            InTotalFormatted & ")", fnt, sb, Offset + Diameter + 50, Offset + i * 20) 'Add label text

                Angle = Angle + Piece
            Next i


            'Get Bytes
            bmp.Save(myMemoryStream, ImageFormat.Png)
            buffer = myMemoryStream.ToArray()


            'Clear resources
            g.Dispose()
            bmp.Dispose()


'            #End Region


            'Set Bytes
            e.ExportBytes = buffer

            'Set file name
            e.ExportFileName = "ExportData.png"

            'Set ContentType
            e.ExportContentType = "image/png"

            GoTo Completed
        End If


    Completed:


        'Set Bytes
        e.ExportBytes = buffer

    End Sub


End Class