Click here to Skip to main content
15,896,456 members
Articles / Programming Languages / Visual Basic

How to Print Invoice using VB.NET?

Rate me:
Please Sign up or sign in to vote.
4.89/5 (24 votes)
14 May 2011CPOL1 min read 176.4K   22.9K   44  
This is a trial to print Invoice with VB.NET
Imports System.Data
Imports System.Data.OleDb

Namespace PrintInvoice

    Public Class frmOrder
        Inherits System.Windows.Forms.Form

        ' for PrintDialog, PrintPreviewDialog and PrintDocument:
        Private prnDialog As System.Windows.Forms.PrintDialog
        Private prnPreview As System.Windows.Forms.PrintPreviewDialog
        Private prnDocument As System.Drawing.Printing.PrintDocument

        ' for Invoice Head:
        Private InvTitle As String
        Private InvSubTitle1 As String
        Private InvSubTitle2 As String
        Private InvSubTitle3 As String
        Private InvImage As String

        ' for Database:
        Private cnn As OleDbConnection
        Private cmd As OleDbCommand
        Private rdrInvoice As OleDbDataReader
        Private strCon As String
        Private InvSql As String

        ' for Report:
        Private CurrentY As Integer
        Private CurrentX As Integer
        Private leftMargin As Integer
        Private rightMargin As Integer
        Private topMargin As Integer
        Private bottomMargin As Integer
        Private InvoiceWidth As Integer
        Private InvoiceHeight As Integer
        Private CustomerName As String
        Private CustomerCity As String
        Private SellerName As String
        Private SaleID As String
        Private SaleDate As String
        Private SaleFreight As Decimal
        Private SubTotal As Decimal
        Private InvoiceTotal As Decimal
        Private ReadInvoice As Boolean
        Private AmountPosition As Integer

        ' Font and Color:------------------
        ' Title Font
        Private InvTitleFont As Font = New Font("Arial", 24, FontStyle.Regular)
        ' Title Font height
        Private InvTitleHeight As Integer
        ' SubTitle Font
        Private InvSubTitleFont As Font = New Font("Arial", 14, FontStyle.Regular)
        ' SubTitle Font height
        Private InvSubTitleHeight As Integer
        ' Invoice Font
        Private InvoiceFont As Font = New Font("Arial", 12, FontStyle.Regular)
        ' Invoice Font height
        Private InvoiceFontHeight As Integer
        ' Blue Color
        Private BlueBrush As SolidBrush = New SolidBrush(Color.Blue)
        ' Red Color
        Private RedBrush As SolidBrush = New SolidBrush(Color.Red)
        ' Black Color
        Private BlackBrush As SolidBrush = New SolidBrush(Color.Black)


#Region " Windows Form Designer generated code "

        Public Sub New()
            MyBase.New()

            InitializeComponent()

            Me.prnDialog = New System.Windows.Forms.PrintDialog
            Me.prnPreview = New System.Windows.Forms.PrintPreviewDialog
            Me.prnDocument = New System.Drawing.Printing.PrintDocument
            ' The Event of 'PrintPage'
            AddHandler prnDocument.PrintPage, AddressOf prnDocument_PrintPage
        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents lblID As System.Windows.Forms.Label
        Friend WithEvents lblCity As System.Windows.Forms.Label
        Friend WithEvents lblSeller As System.Windows.Forms.Label
        Friend WithEvents lblCustomer As System.Windows.Forms.Label
        Friend WithEvents lblDate As System.Windows.Forms.Label
        Friend WithEvents label5 As System.Windows.Forms.Label
        Friend WithEvents label4 As System.Windows.Forms.Label
        Friend WithEvents label3 As System.Windows.Forms.Label
        Friend WithEvents label2 As System.Windows.Forms.Label
        Friend WithEvents label1 As System.Windows.Forms.Label
        Friend WithEvents btnDialog As System.Windows.Forms.Button
        Friend WithEvents btnClose As System.Windows.Forms.Button
        Friend WithEvents btnPrint As System.Windows.Forms.Button
        Friend WithEvents btnPreview As System.Windows.Forms.Button
        Friend WithEvents ordGrid As System.Windows.Forms.DataGrid
        Friend WithEvents lblFreight As System.Windows.Forms.Label
        Friend WithEvents lblInvoiceTotal As System.Windows.Forms.Label
        Friend WithEvents lblSubTotal As System.Windows.Forms.Label
        Friend WithEvents label9 As System.Windows.Forms.Label
        Friend WithEvents label8 As System.Windows.Forms.Label
        Friend WithEvents label7 As System.Windows.Forms.Label
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.lblID = New System.Windows.Forms.Label
            Me.lblCity = New System.Windows.Forms.Label
            Me.lblSeller = New System.Windows.Forms.Label
            Me.lblCustomer = New System.Windows.Forms.Label
            Me.lblDate = New System.Windows.Forms.Label
            Me.label5 = New System.Windows.Forms.Label
            Me.label4 = New System.Windows.Forms.Label
            Me.label3 = New System.Windows.Forms.Label
            Me.label2 = New System.Windows.Forms.Label
            Me.label1 = New System.Windows.Forms.Label
            Me.btnDialog = New System.Windows.Forms.Button
            Me.btnClose = New System.Windows.Forms.Button
            Me.btnPrint = New System.Windows.Forms.Button
            Me.btnPreview = New System.Windows.Forms.Button
            Me.ordGrid = New System.Windows.Forms.DataGrid
            Me.lblFreight = New System.Windows.Forms.Label
            Me.lblInvoiceTotal = New System.Windows.Forms.Label
            Me.lblSubTotal = New System.Windows.Forms.Label
            Me.label9 = New System.Windows.Forms.Label
            Me.label8 = New System.Windows.Forms.Label
            Me.label7 = New System.Windows.Forms.Label
            CType(Me.ordGrid, System.ComponentModel.ISupportInitialize).BeginInit()
            Me.SuspendLayout()
            '
            'lblID
            '
            Me.lblID.BackColor = System.Drawing.Color.White
            Me.lblID.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblID.Location = New System.Drawing.Point(72, 56)
            Me.lblID.Name = "lblID"
            Me.lblID.Size = New System.Drawing.Size(96, 20)
            Me.lblID.TabIndex = 72
            '
            'lblCity
            '
            Me.lblCity.BackColor = System.Drawing.Color.White
            Me.lblCity.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblCity.Location = New System.Drawing.Point(368, 8)
            Me.lblCity.Name = "lblCity"
            Me.lblCity.Size = New System.Drawing.Size(128, 20)
            Me.lblCity.TabIndex = 71
            '
            'lblSeller
            '
            Me.lblSeller.BackColor = System.Drawing.Color.White
            Me.lblSeller.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblSeller.Location = New System.Drawing.Point(112, 32)
            Me.lblSeller.Name = "lblSeller"
            Me.lblSeller.Size = New System.Drawing.Size(216, 20)
            Me.lblSeller.TabIndex = 70
            '
            'lblCustomer
            '
            Me.lblCustomer.BackColor = System.Drawing.Color.White
            Me.lblCustomer.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblCustomer.Location = New System.Drawing.Point(112, 8)
            Me.lblCustomer.Name = "lblCustomer"
            Me.lblCustomer.Size = New System.Drawing.Size(216, 20)
            Me.lblCustomer.TabIndex = 69
            '
            'lblDate
            '
            Me.lblDate.BackColor = System.Drawing.Color.White
            Me.lblDate.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblDate.Location = New System.Drawing.Point(400, 56)
            Me.lblDate.Name = "lblDate"
            Me.lblDate.Size = New System.Drawing.Size(96, 20)
            Me.lblDate.TabIndex = 68
            '
            'label5
            '
            Me.label5.ForeColor = System.Drawing.Color.Navy
            Me.label5.Location = New System.Drawing.Point(336, 56)
            Me.label5.Name = "label5"
            Me.label5.Size = New System.Drawing.Size(64, 20)
            Me.label5.TabIndex = 67
            Me.label5.Text = "Order Date:"
            '
            'label4
            '
            Me.label4.ForeColor = System.Drawing.Color.Navy
            Me.label4.Location = New System.Drawing.Point(16, 32)
            Me.label4.Name = "label4"
            Me.label4.Size = New System.Drawing.Size(96, 20)
            Me.label4.TabIndex = 66
            Me.label4.Text = "Salesperson:"
            '
            'label3
            '
            Me.label3.ForeColor = System.Drawing.Color.Navy
            Me.label3.Location = New System.Drawing.Point(16, 56)
            Me.label3.Name = "label3"
            Me.label3.Size = New System.Drawing.Size(56, 20)
            Me.label3.TabIndex = 65
            Me.label3.Text = "Order ID:"
            '
            'label2
            '
            Me.label2.ForeColor = System.Drawing.Color.Navy
            Me.label2.Location = New System.Drawing.Point(336, 8)
            Me.label2.Name = "label2"
            Me.label2.Size = New System.Drawing.Size(32, 20)
            Me.label2.TabIndex = 64
            Me.label2.Text = "City:"
            '
            'label1
            '
            Me.label1.ForeColor = System.Drawing.Color.Navy
            Me.label1.Location = New System.Drawing.Point(16, 8)
            Me.label1.Name = "label1"
            Me.label1.Size = New System.Drawing.Size(96, 20)
            Me.label1.TabIndex = 63
            Me.label1.Text = "Company Name:"
            '
            'btnDialog
            '
            Me.btnDialog.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.btnDialog.ImeMode = System.Windows.Forms.ImeMode.NoControl
            Me.btnDialog.Location = New System.Drawing.Point(312, 320)
            Me.btnDialog.Name = "btnDialog"
            Me.btnDialog.Size = New System.Drawing.Size(88, 20)
            Me.btnDialog.TabIndex = 62
            Me.btnDialog.Text = "Print Dialog"
            '
            'btnClose
            '
            Me.btnClose.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl
            Me.btnClose.Location = New System.Drawing.Point(408, 320)
            Me.btnClose.Name = "btnClose"
            Me.btnClose.Size = New System.Drawing.Size(88, 20)
            Me.btnClose.TabIndex = 61
            Me.btnClose.Text = "Close"
            '
            'btnPrint
            '
            Me.btnPrint.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.btnPrint.ImeMode = System.Windows.Forms.ImeMode.NoControl
            Me.btnPrint.Location = New System.Drawing.Point(112, 320)
            Me.btnPrint.Name = "btnPrint"
            Me.btnPrint.Size = New System.Drawing.Size(88, 20)
            Me.btnPrint.TabIndex = 60
            Me.btnPrint.Text = "Print"
            '
            'btnPreview
            '
            Me.btnPreview.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.btnPreview.ImeMode = System.Windows.Forms.ImeMode.NoControl
            Me.btnPreview.Location = New System.Drawing.Point(16, 320)
            Me.btnPreview.Name = "btnPreview"
            Me.btnPreview.Size = New System.Drawing.Size(88, 20)
            Me.btnPreview.TabIndex = 59
            Me.btnPreview.Text = "Print Preview"
            '
            'ordGrid
            '
            Me.ordGrid.DataMember = ""
            Me.ordGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText
            Me.ordGrid.Location = New System.Drawing.Point(16, 88)
            Me.ordGrid.Name = "ordGrid"
            Me.ordGrid.Size = New System.Drawing.Size(480, 200)
            Me.ordGrid.TabIndex = 58
            '
            'lblFreight
            '
            Me.lblFreight.BackColor = System.Drawing.Color.White
            Me.lblFreight.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblFreight.Location = New System.Drawing.Point(240, 292)
            Me.lblFreight.Name = "lblFreight"
            Me.lblFreight.Size = New System.Drawing.Size(88, 20)
            Me.lblFreight.TabIndex = 78
            Me.lblFreight.TextAlign = System.Drawing.ContentAlignment.MiddleRight
            '
            'lblInvoiceTotal
            '
            Me.lblInvoiceTotal.BackColor = System.Drawing.Color.White
            Me.lblInvoiceTotal.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblInvoiceTotal.Location = New System.Drawing.Point(408, 292)
            Me.lblInvoiceTotal.Name = "lblInvoiceTotal"
            Me.lblInvoiceTotal.Size = New System.Drawing.Size(88, 20)
            Me.lblInvoiceTotal.TabIndex = 77
            Me.lblInvoiceTotal.TextAlign = System.Drawing.ContentAlignment.MiddleRight
            '
            'lblSubTotal
            '
            Me.lblSubTotal.BackColor = System.Drawing.Color.White
            Me.lblSubTotal.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.lblSubTotal.Location = New System.Drawing.Point(72, 292)
            Me.lblSubTotal.Name = "lblSubTotal"
            Me.lblSubTotal.Size = New System.Drawing.Size(88, 20)
            Me.lblSubTotal.TabIndex = 76
            Me.lblSubTotal.TextAlign = System.Drawing.ContentAlignment.MiddleRight
            '
            'label9
            '
            Me.label9.ForeColor = System.Drawing.Color.Navy
            Me.label9.Location = New System.Drawing.Point(368, 292)
            Me.label9.Name = "label9"
            Me.label9.Size = New System.Drawing.Size(40, 20)
            Me.label9.TabIndex = 75
            Me.label9.Text = "Total:"
            '
            'label8
            '
            Me.label8.ForeColor = System.Drawing.Color.Navy
            Me.label8.Location = New System.Drawing.Point(192, 292)
            Me.label8.Name = "label8"
            Me.label8.Size = New System.Drawing.Size(48, 20)
            Me.label8.TabIndex = 74
            Me.label8.Text = "Freight:"
            '
            'label7
            '
            Me.label7.ForeColor = System.Drawing.Color.Navy
            Me.label7.Location = New System.Drawing.Point(16, 292)
            Me.label7.Name = "label7"
            Me.label7.Size = New System.Drawing.Size(56, 20)
            Me.label7.TabIndex = 73
            Me.label7.Text = "Subtotal:"
            '
            'frmOrder
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(508, 347)
            Me.Controls.Add(Me.lblFreight)
            Me.Controls.Add(Me.lblInvoiceTotal)
            Me.Controls.Add(Me.lblSubTotal)
            Me.Controls.Add(Me.label9)
            Me.Controls.Add(Me.label8)
            Me.Controls.Add(Me.label7)
            Me.Controls.Add(Me.lblID)
            Me.Controls.Add(Me.lblCity)
            Me.Controls.Add(Me.lblSeller)
            Me.Controls.Add(Me.lblCustomer)
            Me.Controls.Add(Me.lblDate)
            Me.Controls.Add(Me.label5)
            Me.Controls.Add(Me.label4)
            Me.Controls.Add(Me.label3)
            Me.Controls.Add(Me.label2)
            Me.Controls.Add(Me.label1)
            Me.Controls.Add(Me.btnDialog)
            Me.Controls.Add(Me.btnClose)
            Me.Controls.Add(Me.btnPrint)
            Me.Controls.Add(Me.btnPreview)
            Me.Controls.Add(Me.ordGrid)
            Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D
            Me.MaximizeBox = False
            Me.Name = "frmOrder"
            Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
            Me.Text = "Invoice"
            CType(Me.ordGrid, System.ComponentModel.ISupportInitialize).EndInit()
            Me.ResumeLayout(False)

        End Sub

#End Region

        Private Sub LoadOrder()
            Dim intOrder As Integer = Int32.Parse(InvoiceOrder)

            ' following lines to connect with access database file 'Northwind.mdb' 
            Dim MyDataFile As String = Application.StartupPath & "\DataFile\Northwind.mdb"
            Dim MyPass As String = ""
            strCon = "provider=microsoft.jet.oledb.4.0;data source=" _
             & MyDataFile & ";" & "Jet OLEDB:Database Password=" & MyPass & ";"

            ' If you are using SQL Server, please replace previous lines with following
            ' strCon = "provider=sqloledb;Data Source=PC;Initial Catalog=" _
            ' & "Northwind;Integrated Security=SSPI" & ";"
            ' and replace 'Data Source=PC' with the name of your system 

            Try
                ' Get Invoice Data:
                InvSql = "SELECT [Order Details].ProductID, " _
                 & "Products.ProductName, [Order Details].UnitPrice, " _
                 & "[Order Details].Quantity, [Order Details].Discount, " _
                 & "CCur([Order Details].UnitPrice*[Quantity]*(1-[Discount])/100)*100 " _
                 & "AS ExtendedPrice " _
                 & "FROM Products INNER JOIN [Order Details] " _
                 & "ON Products.ProductID=[Order Details].ProductID " _
                 & "WHERE [Order Details].OrderID = " & intOrder

                ' create an OleDbDataAdapter
                Dim datAdp As OleDbDataAdapter = New OleDbDataAdapter(InvSql, strCon)

                ' create a command builder
                Dim cBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(datAdp)

                ' create a DataTable to hold the query results
                Dim dTable As DataTable = New DataTable

                ' fill the DataTable
                datAdp.Fill(dTable)

                If (dTable.Rows.Count = 0) Then
                    MessageBox.Show("This Order not found, Please enter another order.")
                    Me.Close()
                End If

                ' Create a TableStyle to format Datagrid columns.
                ordGrid.TableStyles.Clear()
                Dim tableStyle As DataGridTableStyle = New DataGridTableStyle

                For Each dc As DataColumn In dTable.Columns
                    Dim txtColumn As DataGridTextBoxColumn = New DataGridTextBoxColumn
                    txtColumn.MappingName = dc.ColumnName
                    txtColumn.HeaderText = dc.Caption
                    Select Case (dc.ColumnName.ToString())
                        Case "ProductID" ' Product ID 
                            txtColumn.HeaderText = "Product ID"
                            txtColumn.Width = 60
                        Case "ProductName" ' Product Name 
                            txtColumn.HeaderText = "Product Name"
                            txtColumn.Width = 110
                        Case "UnitPrice" ' Unit Price 
                            txtColumn.HeaderText = "Unit Price"
                            txtColumn.Format = "0.00"
                            txtColumn.Alignment = HorizontalAlignment.Right
                            txtColumn.Width = 60
                        Case "Discount" ' Discount 
                            txtColumn.HeaderText = "Discount"
                            txtColumn.Format = "p" ' Percent
                            txtColumn.Alignment = HorizontalAlignment.Right
                            txtColumn.Width = 60
                        Case "Quantity" ' Quantity 
                            txtColumn.HeaderText = "Quantity"
                            txtColumn.Alignment = HorizontalAlignment.Right
                            txtColumn.Width = 50
                        Case "ExtendedPrice" ' Extended Price 
                            txtColumn.HeaderText = "Extended Price"
                            txtColumn.Format = "0.00"
                            txtColumn.Alignment = HorizontalAlignment.Right
                            txtColumn.Width = 90
                    End Select
                    tableStyle.GridColumnStyles.Add(txtColumn)
                Next

                tableStyle.MappingName = dTable.TableName
                ordGrid.TableStyles.Add(tableStyle)
                ' set DataSource of DataGrid 
                ordGrid.DataSource = dTable.DefaultView
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub

        Private Sub FindOrderData()
            Dim intOrder As Integer = Int32.Parse(InvoiceOrder)

            Dim InvSql As String = "SELECT Orders.OrderID, Orders.OrderDate, Orders.Freight," _
             & "Customers.CompanyName, Customers.City, " _
                         & "(Employees.FirstName + Space(1) + Employees.LastName) As Salesperson " _
             & "FROM ((Orders " _
             & "INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID) " _
             & "INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID) " _
             & "WHERE Orders.OrderID = " & intOrder

            Dim cnn As OleDbConnection = New OleDbConnection(strCon)
            Dim cmdOrder As OleDbCommand = New OleDbCommand(InvSql, cnn)
            cnn.Open()
            Dim rdrOrder As OleDbDataReader = cmdOrder.ExecuteReader()

            ' Get CompanyName, City, Salesperson, OrderID, OrderDate and Freight
            rdrOrder.Read()
            CustomerName = rdrOrder("CompanyName").ToString()
            CustomerCity = rdrOrder("City").ToString()
            SellerName = rdrOrder("Salesperson").ToString()
            SaleID = rdrOrder("OrderID").ToString()
            Dim dtOrder As System.DateTime = Convert.ToDateTime(rdrOrder("OrderDate"))
            SaleDate = dtOrder.ToShortDateString()
            SaleFreight = Convert.ToDecimal(rdrOrder("Freight"))
            ' Get invoice total
            GetInvoiceTotal()

            rdrOrder.Close()
            cnn.Close()
        End Sub

        Private Sub ReadInvoiceHead()
            'Titles and Image of invoice:
            InvTitle = "International Food Company"
            InvSubTitle1 = "23 Abo Naga street"
            InvSubTitle2 = "Cairo, Egypt"
            InvSubTitle3 = "Phone 2233445566"
            InvImage = Application.StartupPath & "\Images\" + "InvPic.jpg"
        End Sub

        Private Sub GetInvoiceTotal()
            SubTotal = 0

            cnn = New OleDbConnection(strCon)
            cmd = New OleDbCommand(InvSql, cnn)
            cnn.Open()
            rdrInvoice = cmd.ExecuteReader()

            While (rdrInvoice.Read())
                SubTotal = SubTotal + Convert.ToDecimal(rdrInvoice("ExtendedPrice"))
            End While

            rdrInvoice.Close()
            cnn.Close()

            ' Get Order Freight
            InvoiceTotal = SubTotal + SaleFreight
            ' Set Total
            lblSubTotal.Text = SubTotal.ToString()
            lblFreight.Text = SaleFreight.ToString()
            lblInvoiceTotal.Text = InvoiceTotal.ToString()
        End Sub

        Private Sub ReadInvoiceData()
            cnn.Open()
            rdrInvoice = cmd.ExecuteReader()
            rdrInvoice.Read()
        End Sub

        Private Sub SetInvoiceHead(ByVal g As Graphics)
            ReadInvoiceHead()

            CurrentY = topMargin
            CurrentX = leftMargin
            Dim ImageHeight As Integer = 0

            ' Draw Invoice image:
            If (System.IO.File.Exists(InvImage)) Then
                Dim oInvImage As Bitmap = New Bitmap(InvImage)
                ' Set Image Left to center Image:
                Dim xImage As Integer = CurrentX + (InvoiceWidth - oInvImage.Width) / 2
                ImageHeight = oInvImage.Height ' Get Image Height
                g.DrawImage(oInvImage, xImage, CurrentY)
            End If

            InvTitleHeight = Convert.ToInt32(InvTitleFont.GetHeight(g))
            InvSubTitleHeight = Convert.ToInt32(InvSubTitleFont.GetHeight(g))
            ' Get Titles Length:
            Dim lenInvTitle As Integer = Convert.ToInt32(g.MeasureString(InvTitle, InvTitleFont).Width)
            Dim lenInvSubTitle1 As Integer = Convert.ToInt32(g.MeasureString(InvSubTitle1, InvSubTitleFont).Width)
            Dim lenInvSubTitle2 As Integer = Convert.ToInt32(g.MeasureString(InvSubTitle2, InvSubTitleFont).Width)
            Dim lenInvSubTitle3 As Integer = Convert.ToInt32(g.MeasureString(InvSubTitle3, InvSubTitleFont).Width)
            ' Set Titles Left:
            Dim xInvTitle As Integer = CurrentX + (InvoiceWidth - lenInvTitle) / 2
            Dim xInvSubTitle1 As Integer = CurrentX + (InvoiceWidth - lenInvSubTitle1) / 2
            Dim xInvSubTitle2 As Integer = CurrentX + (InvoiceWidth - lenInvSubTitle2) / 2
            Dim xInvSubTitle3 As Integer = CurrentX + (InvoiceWidth - lenInvSubTitle3) / 2

            ' Draw Invoice Head:
            If (InvTitle <> "") Then
                CurrentY = CurrentY + ImageHeight
                g.DrawString(InvTitle, InvTitleFont, BlueBrush, xInvTitle, CurrentY)
            End If
            If (InvSubTitle1 <> "") Then
                CurrentY = CurrentY + InvTitleHeight
                g.DrawString(InvSubTitle1, InvSubTitleFont, BlueBrush, xInvSubTitle1, CurrentY)
            End If
            If (InvSubTitle2 <> "") Then
                CurrentY = CurrentY + InvSubTitleHeight
                g.DrawString(InvSubTitle2, InvSubTitleFont, BlueBrush, xInvSubTitle2, CurrentY)
            End If
            If (InvSubTitle3 <> "") Then
                CurrentY = CurrentY + InvSubTitleHeight
                g.DrawString(InvSubTitle3, InvSubTitleFont, BlueBrush, xInvSubTitle3, CurrentY)
            End If

            ' Draw line:
            CurrentY = CurrentY + InvSubTitleHeight + 8
            g.DrawLine(New Pen(Brushes.Black, 2), CurrentX, CurrentY, rightMargin, CurrentY)
        End Sub

        Private Sub SetOrderData(ByVal g As Graphics)
            ' Set Company Name, City, Salesperson, Order ID and Order Date
            Dim FieldValue As String = ""
            InvoiceFontHeight = Convert.ToInt32(InvoiceFont.GetHeight(g))

            ' Set Company Name:
            CurrentX = leftMargin
            CurrentY = CurrentY + 8
            FieldValue = "Company Name: " & CustomerName
            g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX, CurrentY)
            ' Set City:
            CurrentX = CurrentX + Convert.ToInt32(g.MeasureString(FieldValue, InvoiceFont).Width) + 16
            FieldValue = "City: " & CustomerCity
            g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX, CurrentY)
            ' Set Salesperson:
            CurrentX = leftMargin
            CurrentY = CurrentY + InvoiceFontHeight
            FieldValue = "Salesperson: " & SellerName
            g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX, CurrentY)
            ' Set Order ID:
            CurrentX = leftMargin
            CurrentY = CurrentY + InvoiceFontHeight
            FieldValue = "Order ID: " & SaleID
            g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX, CurrentY)
            ' Set Order Date:
            CurrentX = CurrentX + Convert.ToInt32(g.MeasureString(FieldValue, InvoiceFont).Width) + 16
            FieldValue = "Order Date: " & SaleDate
            g.DrawString(FieldValue, InvoiceFont, BlackBrush, CurrentX, CurrentY)

            ' Draw line:
            CurrentY = CurrentY + InvoiceFontHeight + 8
            g.DrawLine(New Pen(Brushes.Black), leftMargin, CurrentY, rightMargin, CurrentY)
        End Sub

        Private Sub SetInvoiceData(ByVal g As Graphics, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
            ' Set Invoice Table:
            Dim FieldValue As String = ""
            Dim CurrentRecord = 0
            Dim RecordsPerPage = 20
            Dim Amount As Decimal = 0
            Dim StopReading As Boolean = False

            InvoiceFontHeight = Convert.ToInt32(InvoiceFont.GetHeight(g))

            ' Set Table Head:
            Dim xProductID As Integer = leftMargin
            CurrentY = CurrentY + InvoiceFontHeight
            g.DrawString("Product ID", InvoiceFont, BlueBrush, xProductID, CurrentY)

            Dim xProductName As Integer = xProductID + Convert.ToInt32(g.MeasureString("Product ID", InvoiceFont).Width) + 4
            g.DrawString("Product Name", InvoiceFont, BlueBrush, xProductName, CurrentY)

            Dim xUnitPrice As Integer = xProductName + Convert.ToInt32(g.MeasureString("Product Name", InvoiceFont).Width) + 72
            g.DrawString("Unit Price", InvoiceFont, BlueBrush, xUnitPrice, CurrentY)

            Dim xQuantity As Integer = xUnitPrice + Convert.ToInt32(g.MeasureString("Unit Price", InvoiceFont).Width) + 4
            g.DrawString("Quantity", InvoiceFont, BlueBrush, xQuantity, CurrentY)

            Dim xDiscount As Integer = xQuantity + Convert.ToInt32(g.MeasureString("Quantity", InvoiceFont).Width) + 4
            g.DrawString("Discount", InvoiceFont, BlueBrush, xDiscount, CurrentY)

            AmountPosition = xDiscount + Convert.ToInt32(g.MeasureString("Discount", InvoiceFont).Width) + 4
            g.DrawString("Extended Price", InvoiceFont, BlueBrush, AmountPosition, CurrentY)

            ' Set Invoice Table:
            CurrentY = CurrentY + InvoiceFontHeight + 8

            While (CurrentRecord < RecordsPerPage)
                FieldValue = rdrInvoice("ProductID").ToString()
                g.DrawString(FieldValue, InvoiceFont, BlackBrush, xProductID, CurrentY)
                FieldValue = rdrInvoice("ProductName").ToString()
                ' if Length of (Product Name) > 20, Draw 20 character only
                If (FieldValue.Length > 20) Then
                    FieldValue = FieldValue.Remove(20, FieldValue.Length - 20)
                End If
                g.DrawString(FieldValue, InvoiceFont, BlackBrush, xProductName, CurrentY)
                FieldValue = String.Format("{0:0.00}", rdrInvoice("UnitPrice"))
                g.DrawString(FieldValue, InvoiceFont, BlackBrush, xUnitPrice, CurrentY)
                FieldValue = rdrInvoice("Quantity").ToString()
                g.DrawString(FieldValue, InvoiceFont, BlackBrush, xQuantity, CurrentY)
                FieldValue = String.Format("{0:0.00%}", rdrInvoice("Discount"))
                g.DrawString(FieldValue, InvoiceFont, BlackBrush, xDiscount, CurrentY)

                Amount = Convert.ToDecimal(rdrInvoice("ExtendedPrice"))
                ' Format Extended Price and Align to Right:
                FieldValue = String.Format("{0:0.00}", Amount)
                Dim xAmount As Integer = AmountPosition + Convert.ToInt32(g.MeasureString("Extended Price", InvoiceFont).Width)
                xAmount = xAmount - Convert.ToInt32(g.MeasureString(FieldValue, InvoiceFont).Width)
                g.DrawString(FieldValue, InvoiceFont, BlackBrush, xAmount, CurrentY)
                CurrentY = CurrentY + InvoiceFontHeight

                If (Not rdrInvoice.Read()) Then
                    StopReading = True
                    Exit While
                End If

                CurrentRecord += 1
            End While

            If (CurrentRecord < RecordsPerPage) Then
                e.HasMorePages = False
            Else
                e.HasMorePages = True
            End If

            If (StopReading) Then
                rdrInvoice.Close()
                cnn.Close()
                SetInvoiceTotal(g)
            End If

            g.Dispose()
        End Sub

        Private Sub SetInvoiceTotal(ByVal g As Graphics)
            ' Set Invoice Total:
            ' Draw line:
            CurrentY = CurrentY + 8
            g.DrawLine(New Pen(Brushes.Black), leftMargin, CurrentY, rightMargin, CurrentY)
            ' Get Right Edge of Invoice:
            Dim xRightEdg As Integer = AmountPosition + Convert.ToInt32(g.MeasureString("Extended Price", InvoiceFont).Width)

            ' Write Sub Total:
            Dim xSubTotal As Integer = AmountPosition - Convert.ToInt32(g.MeasureString("Sub Total", InvoiceFont).Width)
            CurrentY = CurrentY + 8
            g.DrawString("Sub Total", InvoiceFont, RedBrush, xSubTotal, CurrentY)
            Dim TotalValue As String = String.Format("{0:0.00}", SubTotal)
            Dim xTotalValue As Integer = xRightEdg - Convert.ToInt32(g.MeasureString(TotalValue, InvoiceFont).Width)
            g.DrawString(TotalValue, InvoiceFont, BlackBrush, xTotalValue, CurrentY)

            ' Write Order Freight:
            Dim xOrderFreight As Integer = AmountPosition - Convert.ToInt32(g.MeasureString("Order Freight", InvoiceFont).Width)
            CurrentY = CurrentY + InvoiceFontHeight
            g.DrawString("Order Freight", InvoiceFont, RedBrush, xOrderFreight, CurrentY)
            Dim FreightValue As String = String.Format("{0:0.00}", SaleFreight)
            Dim xFreight As Integer = xRightEdg - Convert.ToInt32(g.MeasureString(FreightValue, InvoiceFont).Width)
            g.DrawString(FreightValue, InvoiceFont, BlackBrush, xFreight, CurrentY)

            ' Write Invoice Total:
            Dim xInvoiceTotal As Integer = AmountPosition - Convert.ToInt32(g.MeasureString("Invoice Total", InvoiceFont).Width)
            CurrentY = CurrentY + InvoiceFontHeight
            g.DrawString("Invoice Total", InvoiceFont, RedBrush, xInvoiceTotal, CurrentY)
            Dim InvoiceValue As String = String.Format("{0:0.00}", InvoiceTotal)
            Dim xInvoiceValue As Integer = xRightEdg - Convert.ToInt32(g.MeasureString(InvoiceValue, InvoiceFont).Width)
            g.DrawString(InvoiceValue, InvoiceFont, BlackBrush, xInvoiceValue, CurrentY)

        End Sub
        Private Sub DisplayDialog()
            Try
                prnDialog.Document = Me.prnDocument
                Dim ButtonPressed As DialogResult = prnDialog.ShowDialog()
                ' If user Click 'OK', Print Invoice
                If (ButtonPressed = DialogResult.OK) Then
                    prnDocument.Print()
                End If
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub

        Private Sub DisplayInvoice()
            prnPreview.Document = Me.prnDocument
            Try
                prnPreview.ShowDialog()
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub

        Private Sub PrintReport()
            Try
                prnDocument.Print()
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub

        Private Sub frmOrder_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            ordGrid.CaptionText = "Invoice..."
            LoadOrder()
            FindOrderData()

            lblCustomer.Text = CustomerName
            lblCity.Text = CustomerCity
            lblSeller.Text = SellerName
            lblID.Text = SaleID
            lblDate.Text = SaleDate
        End Sub

        ' Result of the Event 'PrintPage'
        Private Sub prnDocument_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
            leftMargin = Convert.ToInt32(e.MarginBounds.Left)
            rightMargin = Convert.ToInt32(e.MarginBounds.Right)
            topMargin = Convert.ToInt32(e.MarginBounds.Top)
            bottomMargin = Convert.ToInt32(e.MarginBounds.Bottom)
            InvoiceWidth = Convert.ToInt32(e.MarginBounds.Width)
            InvoiceHeight = Convert.ToInt32(e.MarginBounds.Height)

            If (Not ReadInvoice) Then ReadInvoiceData()

            SetInvoiceHead(e.Graphics) ' Draw Invoice Head
            SetOrderData(e.Graphics) ' Draw Order Data
            SetInvoiceData(e.Graphics, e) ' Draw Invoice Data

            ReadInvoice = True
        End Sub

        Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click
            ReadInvoice = False
            DisplayInvoice() ' Print Preview
        End Sub

        Private Sub btnDialog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDialog.Click
            ReadInvoice = False
            DisplayDialog() ' Print Dialog
        End Sub

        Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
            ReadInvoice = False
            PrintReport() ' Print Invoice
        End Sub

        Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
            Me.Close()
        End Sub
    End Class

End Namespace

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions