private static void DrawPage(PdfPageBase page, CFDIXML cfdi)
        {
            float pageWidth      = page.Canvas.ClientSize.Width;
            float y              = 0;
            float leftMargin     = 5;
            float midPage        = pageWidth / 2;
            float topWritingArea = 0;
            int   sectionSpacing = 15;
            float qrSize         = 100;

            //Fonts
            string          fontName    = "Arial Condensed";
            PdfTrueTypeFont font7Bold   = new PdfTrueTypeFont(new Font(fontName, 7f, System.Drawing.FontStyle.Bold));
            PdfTrueTypeFont font7       = new PdfTrueTypeFont(new Font(fontName, 7f, System.Drawing.FontStyle.Regular));
            PdfTrueTypeFont font6Italic = new PdfTrueTypeFont(new Font(fontName, 6f, System.Drawing.FontStyle.Italic));

            //Colors
            PdfRGBColor lightBlack = new PdfRGBColor(17, 17, 17);

            //Pen
            PdfPen penLightGray1p   = new PdfPen(System.Drawing.Color.LightGray, 1f);
            PdfPen penLightGray05p  = new PdfPen(System.Drawing.Color.LightGray, 0.5f);
            PdfPen penLightBlack10p = new PdfPen(lightBlack, 10f);

            //Brushes
            PdfBrush brushBlack     = new PdfSolidBrush(System.Drawing.Color.Black);
            PdfBrush brushLightGray = new PdfSolidBrush(System.Drawing.Color.LightGray);

            //Format Alignments
            PdfStringFormat formatRight  = new PdfStringFormat(PdfTextAlignment.Right);
            PdfStringFormat formatMiddle = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            PdfStringFormat formatLeft   = new PdfStringFormat(PdfTextAlignment.Left)
            {
                CharacterSpacing = 0.4f
            };

            //Page header
            String text = "Factura version " + cfdi.Version;

            page.Canvas.DrawString(text, font6Italic, brushLightGray, pageWidth, y, formatRight);
            SizeF size = font6Italic.MeasureString(text, formatRight);

            y = y + size.Height + 1;
            page.Canvas.DrawLine(penLightGray1p, 0, y, pageWidth, y);

            y = y + 5;
            topWritingArea = y;

            //Issuerinfo
            //Name
            DrawToPage(page, cfdi.Emisor.Nombre, font7Bold, brushBlack, formatLeft, leftMargin, y, out y);
            //RFC
            DrawToPage(page, cfdi.Emisor.Rfc, font7Bold, brushBlack, formatLeft, leftMargin, y, out y);
            //Fiscal Regime
            DrawToPage(page, cfdi.Emisor.RegimenFiscal, font7, brushBlack, formatLeft, leftMargin, y, out y);
            //Address
            text = "Calle:" + cfdi.Emisor.Domicilio.Calle + " No:" + cfdi.Emisor.Domicilio.NoExterior;
            if (cfdi.Emisor.Domicilio.NoInterior != null)
            {
                text += "-" + cfdi.Emisor.Domicilio.NoInterior;
            }
            text += " Col:" + cfdi.Emisor.Domicilio.Colonia + ", Localidad:" + cfdi.Emisor.Domicilio.Localidad + ", Municipio:" + cfdi.Emisor.Domicilio.Municipio + ", Estado:" + cfdi.Emisor.Domicilio.Estado + ", CP:" + cfdi.Emisor.Domicilio.Cp;
            RectangleF area = new RectangleF(leftMargin, y, midPage - 10, 30);

            DrawToPage(page, text, font7, brushBlack, formatLeft, area, y, out y, false);
            DrawToPage(page, "Pais:" + cfdi.Emisor.Domicilio.Pais, font7, brushBlack, formatLeft, leftMargin, y, out y);

            //Invoice data
            y = topWritingArea;
            //Invoice header
            y += 5;
            page.Canvas.DrawLine(penLightBlack10p, midPage, y, pageWidth, y);
            text = "Factura";
            size = font7Bold.MeasureString(text, formatLeft);
            y   -= 4;
            DrawToPage(page, text, font7Bold, brushLightGray, formatLeft, pageWidth - size.Width - 10, y, out y);
            //Invoice number
            DrawToPageWithHeader(page, "Folio:", cfdi.Folio, font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);
            DrawToPageWithHeader(page, "Serie:", cfdi.Serie ?? "", font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);
            DrawToPageWithHeader(page, "Folio Fiscal:", cfdi.TimbreFiscal.UUID, font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);
            DrawToPageWithHeader(page, "Serie CSD del SAT:", cfdi.TimbreFiscal.NoCertificadoSAT, font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);
            DrawToPageWithHeader(page, "No. Certificado:", cfdi.NoCertificado, font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);
            DrawToPageWithHeader(page, "Fecha emsión:", cfdi.Fecha, font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);
            DrawToPageWithHeader(page, "Fecha certificación:", cfdi.TimbreFiscal.FechaTimbrado, font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);

            //Issue place
            y += 5;
            DrawToPageWithHeader(page, "Lugar de expedición:", cfdi.LugarExpedicion, font7Bold, font7, brushBlack, formatLeft, leftMargin, y, out y);

            //Reciever data
            //Reciever header
            y += sectionSpacing;
            page.Canvas.DrawLine(penLightBlack10p, leftMargin, y, pageWidth, y);
            text = "Receptor";
            size = font7Bold.MeasureString(text, formatLeft);
            y   -= 4;
            DrawToPage(page, text, font7Bold, brushLightGray, formatLeft, midPage - (size.Width / 2), y, out y);
            //Reciever name
            DrawToPageWithHeader(page, "Receptor:  ", cfdi.Receptor.Nombre, font7Bold, font7, brushBlack, formatLeft, leftMargin, y, out y, true);
            //Reciever address
            text = "Calle:  " + cfdi.Receptor.Domicilio.Calle + " No:" + cfdi.Receptor.Domicilio.NoExterior;
            if (cfdi.Receptor.Domicilio.NoInterior != null)
            {
                text += "-" + cfdi.Receptor.Domicilio.NoInterior;
            }
            DrawToPageWithHeader(page, "Domicilio:   ", text, font7Bold, font7, brushBlack, formatLeft, midPage, y, out y);
            //RFC
            DrawToPageWithHeader(page, "R.F.C.:", cfdi.Receptor.Rfc, font7Bold, font7, brushBlack, formatLeft, leftMargin, y, out y, true);
            //Next line address
            text = " Col:" + cfdi.Receptor.Domicilio.Colonia + ", Localidad:" + cfdi.Receptor.Domicilio.Localidad + ", Municipio:" + cfdi.Receptor.Domicilio.Municipio;
            area = new RectangleF(midPage, y, midPage - 10, 20);
            DrawToPage(page, text, font7, brushBlack, formatLeft, area, y, out y, false);
            text = " Estado:" + cfdi.Receptor.Domicilio.Estado + ", CP:" + cfdi.Receptor.Domicilio.Cp;
            DrawToPage(page, text, font7, brushBlack, formatLeft, midPage, y, out y);
            DrawToPage(page, "Pais:" + cfdi.Receptor.Domicilio.Pais, font7, brushBlack, formatLeft, midPage, y, out y);

            //Products
            y += sectionSpacing;

            //Prepare data
            String[][] dataSource = new String[cfdi.Conceptos.Count + 1][];
            String     headers    = "Cant.;Unidad;Clave;Descripción;Valor unitario;Importe";
            int        i          = 0;

            dataSource[i] = headers.Split(';');
            foreach (Concepto product in cfdi.Conceptos)
            {
                i++;
                String[] content = new String[6];
                content[0]    = product.Cantidad.ToString();
                content[1]    = product.Unidad;
                content[2]    = product.NoIdentificacion;
                content[3]    = product.Descripcion;
                content[4]    = String.Format("{0:N1}", product.ValorUnitario);
                content[5]    = String.Format("{0:C2}", product.Importe);
                dataSource[i] = content;
            }

            //Generate table
            PdfTable      productsTable = new PdfTable();
            PdfTableStyle style         = new PdfTableStyle()
            {
                BorderPen      = new PdfPen(lightBlack, 0.5f),
                CellPadding    = 2,
                HeaderSource   = PdfHeaderSource.Rows,
                HeaderRowCount = 1,
                ShowHeader     = true,
                HeaderStyle    = new PdfCellStyle()
                {
                    BackgroundBrush = new PdfSolidBrush(System.Drawing.Color.Black),
                    TextBrush       = brushLightGray,
                    StringFormat    = formatMiddle
                }
            };

            productsTable.Style = style;

            productsTable.DataSource       = dataSource;
            productsTable.Columns[0].Width = 8;
            productsTable.Columns[3].Width = 30;
            foreach (PdfColumn column in productsTable.Columns)
            {
                column.StringFormat = formatLeft;
            }

            PdfLayoutResult result = productsTable.Draw(page, new PointF(leftMargin, y));

            y = y + result.Bounds.Height + 5;

            //Total in letter and number
            page.Canvas.DrawLine(penLightBlack10p, leftMargin, y, pageWidth, y);
            text = "Total con Letra";
            size = font7Bold.MeasureString(text, formatLeft);
            y   -= 4;
            DrawToPage(page, text, font7Bold, brushLightGray, formatLeft, leftMargin, y, out y);
            DrawToPage(page, Conv.Enletras(cfdi.Total.ToString()) + "M.N.", font7, brushBlack, formatLeft, leftMargin, y, out y, true);

            DrawToPageWithHeader(page, "Subtotal:", String.Format("       {0:C2}", cfdi.SubTotal), font7Bold, font7, brushBlack, formatLeft, midPage + (midPage / 2), y, out y);
            DrawToPageWithHeader(page, "Total:", String.Format("            {0:C2}", cfdi.Total), font7Bold, font7, brushBlack, formatLeft, midPage + (midPage / 2), y, out y);

            //QR Code with basic data
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(String.Format("?re={0}&rr={1}&tt={2:N1}&id={3}", cfdi.Emisor.Rfc, cfdi.Receptor.Rfc, cfdi.Total, cfdi.TimbreFiscal.UUID), QRCodeGenerator.ECCLevel.Q);
            QRCode          qrCode      = new QRCode(qrCodeData);
            Bitmap          qrCodeImage = qrCode.GetGraphic(20);

            float qrPosition = y;

            PdfImage image = PdfImage.FromImage(qrCodeImage);

            page.Canvas.DrawImage(image, leftMargin, y, qrSize, qrSize);

            //Payment info
            y = qrPosition + sectionSpacing;
            DrawToPageWithHeader(page, "Método de pago:  ", cfdi.MetodoDePago, font7Bold, font7, brushBlack, formatLeft, leftMargin + qrSize, y, out y);
            DrawToPageWithHeader(page, "Cuenta:  ", cfdi.NumCtaPago ?? "", font7Bold, font7, brushBlack, formatLeft, leftMargin + qrSize, y, out y);
            DrawToPageWithHeader(page, "Forma de pago:  ", cfdi.FormaDePago, font7Bold, font7, brushBlack, formatLeft, leftMargin + qrSize, y, out y);
            DrawToPageWithHeader(page, "Condiciones de pago:  ", cfdi.CondicionesDePago ?? "", font7Bold, font7, brushBlack, formatLeft, leftMargin + qrSize, y, out y);

            y = qrPosition + qrSize + sectionSpacing;
            page.Canvas.DrawLine(penLightBlack10p, leftMargin, y, pageWidth, y);
            text = "Cadena original del complemento de certificación del SAT";
            size = font7Bold.MeasureString(text, formatLeft);
            y   -= 4;
            DrawToPage(page, text, font7Bold, brushLightGray, formatLeft, leftMargin, y, out y);
            area = new RectangleF(leftMargin, y, pageWidth - 5, 100);
            DrawToPage(page, String.Format("||{0}|{1}|{2}|{3}|{4}", cfdi.TimbreFiscal.Version, cfdi.TimbreFiscal.UUID, cfdi.TimbreFiscal.FechaTimbrado, cfdi.Sello, cfdi.TimbreFiscal.NoCertificadoSAT), font7Bold, brushBlack, formatLeft, area, y, out y, false);

            y += sectionSpacing;
            page.Canvas.DrawLine(penLightBlack10p, leftMargin, y, pageWidth, y);
            text = "Sello digital del SAT";
            size = font7Bold.MeasureString(text, formatLeft);
            y   -= 4;
            DrawToPage(page, text, font7Bold, brushLightGray, formatLeft, leftMargin, y, out y);
            area = new RectangleF(leftMargin, y, pageWidth - 5, 100);
            DrawToPage(page, cfdi.TimbreFiscal.SelloSAT, font7Bold, brushBlack, formatLeft, area, y, out y, false);

            y += sectionSpacing;
            page.Canvas.DrawLine(penLightBlack10p, leftMargin, y, pageWidth, y);
            text = "Sello digital del contribuyente que lo expide";
            size = font7Bold.MeasureString(text, formatLeft);
            y   -= 4;
            DrawToPage(page, text, font7Bold, brushLightGray, formatLeft, leftMargin, y, out y);
            area = new RectangleF(leftMargin, y, pageWidth - 5, 100);
            DrawToPage(page, cfdi.Sello, font7Bold, brushBlack, formatLeft, area, y, out y, false);

            //Footer
            DrawToPage(page, "Este documento es una representación impresa de un CFDI", font7, brushBlack, formatLeft, midPage, page.Canvas.ClientSize.Height - 30, out y, false);
        }
示例#2
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document
            PdfDocument doc = new PdfDocument();

            //Margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins       margin   = new PdfMargins();

            margin.Top    = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left   = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right  = margin.Left;

            //Create one page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4);
            float       y    = 10;
            float       x1   = page.Canvas.ClientSize.Width;

            //Title
            PdfBrush        brush1  = PdfBrushes.Black;
            PdfTrueTypeFont font1   = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold), true);
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);

            page.Canvas.DrawString("Vendor List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Vendor List", format1).Height;
            y = y + 5;

            String[] data
                =
                {
                "VendorName;Address1;City;State;Country",
                "Cacor Corporation;161 Southfield Rd;Southfield;OH;U.S.A.",
                "Underwater;50 N 3rd Street;Indianapolis;IN;U.S.A.",
                "J.W.  Luscher Mfg.;65 Addams Street;Berkely;MA;U.S.A.",
                "Scuba Professionals;3105 East Brace;Rancho Dominguez;CA;U.S.A.",
                "Divers'  Supply Shop;5208 University Dr;Macon;GA;U.S.A.",
                "Techniques;52 Dolphin Drive;Redwood City;CA;U.S.A.",
                "Perry Scuba;3443 James Ave;Hapeville;GA;U.S.A.",
                "Beauchat, Inc.;45900 SW 2nd Ave;Ft Lauderdale;FL;U.S.A.",
                "Amor Aqua;42 West 29th Street;New York;NY;U.S.A.",
                "Aqua Research Corp.;P.O. Box 998;Cornish;NH;U.S.A.",
                "B&K Undersea Photo;116 W 7th Street;New York;NY;U.S.A.",
                "Diving International Unlimited;1148 David Drive;San Diego;DA;U.S.A.",
                "Nautical Compressors;65 NW 167 Street;Miami;FL;U.S.A.",
                "Glen Specialties, Inc.;17663 Campbell Lane;Huntington Beach;CA;U.S.A.",
                "Dive Time;20 Miramar Ave;Long Beach;CA;U.S.A.",
                "Undersea Systems, Inc.;18112 Gotham Street;Huntington Beach;CA;U.S.A.",
                "Felix Diving;310 S Michigan Ave;Chicago;IL;U.S.A.",
                "Central Valley Skin Divers;160 Jameston Ave;Jamaica;NY;U.S.A.",
                "Parkway Dive Shop;241 Kelly Street;South Amboy;NJ;U.S.A.",
                "Marine Camera & Dive;117 South Valley Rd;San Diego;CA;U.S.A.",
                "Dive Canada;275 W Ninth Ave;Vancouver;British Columbia;Canada",
                "Dive & Surf;P.O. Box 20210;Indianapolis;IN;U.S.A.",
                "Fish Research Labs;29 Wilkins Rd Dept. SD;Los Banos;CA;U.S.A."
                };

            //Create a grid
            PdfGrid grid = new PdfGrid();

            //Set the cell padding
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

            String[] header = data[0].Split(';');
            grid.Columns.Add(header.Length);
            float width
                = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);

            grid.Columns[0].Width = width * 0.25f;
            grid.Columns[1].Width = width * 0.25f;
            grid.Columns[2].Width = width * 0.25f;
            grid.Columns[3].Width = width * 0.15f;
            grid.Columns[4].Width = width * 0.10f;
            PdfGridRow headerRow = grid.Headers.Add(1)[0];

            headerRow.Style.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold), true);
            headerRow.Style.BackgroundBrush
                = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(x1, 0), Color.Red, Color.Blue);
            for (int i = 0; i < header.Length; i++)
            {
                headerRow.Cells[i].Value = header[i];
                headerRow.Cells[i].StringFormat
                    = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
                if (i == 0)
                {
                    headerRow.Cells[i].Style.BackgroundBrush = PdfBrushes.Gray;
                }
            }

            Random random = new Random();
            Dictionary <String, int> groupByCountry = new Dictionary <String, int>();

            for (int r = 1; r < data.Length; r++)
            {
                PdfGridRow row = grid.Rows.Add();
                row.Style.Font = new PdfTrueTypeFont(new Font("Arial", 10f), true);
                byte[] buffer = new byte[6];
                random.NextBytes(buffer);
                PdfRGBColor color1 = new PdfRGBColor(buffer[0], buffer[1], buffer[2]);
                PdfRGBColor color2 = new PdfRGBColor(buffer[3], buffer[4], buffer[5]);
                row.Style.BackgroundBrush
                    = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(x1, 0), color1, color2);
                String[] rowData = data[r].Split(';');
                for (int c = 0; c < rowData.Length; c++)
                {
                    row.Cells[c].Value = rowData[c];
                    if (c == 0)
                    {
                        row.Cells[c].Style.BackgroundBrush = PdfBrushes.Gray;
                    }
                    if (c < 3)
                    {
                        row.Cells[c].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        row.Cells[c].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
                    }
                    if (c == 4)
                    {
                        if (groupByCountry.ContainsKey(rowData[c]))
                        {
                            groupByCountry[rowData[c]] = groupByCountry[rowData[c]] + 1;
                        }
                        else
                        {
                            groupByCountry[rowData[c]] = 1;
                        }
                    }
                }
            }
            StringBuilder totalAmount = new StringBuilder();

            foreach (KeyValuePair <String, int> country in groupByCountry)
            {
                totalAmount.AppendFormat("{0}:\t{1}", country.Key, country.Value);
                totalAmount.AppendLine();
            }

            //Add a row
            PdfGridRow totalAmountRow = grid.Rows.Add();

            totalAmountRow.Style.BackgroundBrush = PdfBrushes.Plum;
            totalAmountRow.Cells[0].Value        = "Total Amount";
            totalAmountRow.Cells[0].Style.Font   = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold), true);
            totalAmountRow.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
            totalAmountRow.Cells[1].ColumnSpan   = 4;
            totalAmountRow.Cells[1].Value        = totalAmount.ToString();
            totalAmountRow.Cells[1].Style.Font   = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold | FontStyle.Italic), true);
            totalAmountRow.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);

            //Append product list
            PdfGrid productList = new PdfGrid();

            productList.Style.Font = new PdfTrueTypeFont(new Font("Arial", 8f), true);

            //Fill data into the grid productList
            using (OleDbConnection conn = new OleDbConnection())
            {
                conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\..\..\Data\demo.mdb";
                OleDbCommand command = new OleDbCommand();
                command.CommandText
                    = " select p.Description "
                      + " from vendors v "
                      + "     inner join parts p "
                      + "     on v.VendorNo = p.VendorNo "
                      + " where v.VendorName = 'Cacor Corporation'";
                command.Connection = conn;
                using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
                {
                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);
                    productList.DataSource = dataTable;
                }
            }
            productList.Headers[0].Cells[0].Value             = "Cacor Corporation";
            productList.Headers[0].Cells[0].Style.Font        = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Bold), true);
            productList.Headers[0].Cells[0].Style.Borders.All = new PdfPen(new PdfTilingBrush(new SizeF(1, 1)), 0);

            //Embed the gride productList into the cell of grid
            grid.Rows[0].Cells[0].Value = productList;
            grid.Rows[0].Cells[0].StringFormat.Alignment = PdfTextAlignment.Left;

            PdfLayoutResult result = grid.Draw(page, new PointF(0, y));

            y = y + result.Bounds.Height + 5;

            PdfBrush        brush2 = PdfBrushes.Gray;
            PdfTrueTypeFont font2  = new PdfTrueTypeFont(new Font("Arial", 9f));

            result.Page.Canvas.DrawString(String.Format("* All {0} vendors in the list", grid.Rows.Count - 1),
                                          font2, brush2, 5, y);

            //Save pdf file
            doc.SaveToFile("Grid.pdf");
            doc.Close();

            //Launch the Pdf file
            PDFDocumentViewer("Grid.pdf");
        }
示例#3
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            // Create one page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape);

            float y = 10;
            float x1 = page.Canvas.ClientSize.Width;

            //title
            PdfBrush brush1 = PdfBrushes.Black;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold), true);
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Vendor List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Vendor List", format1).Height;
            y = y + 5;

            String[] data
                = {
                    "VendorName;Address1;City;State;Country",
                    "Cacor Corporation;161 Southfield Rd;Southfield;OH;U.S.A.",
                    "Underwater;50 N 3rd Street;Indianapolis;IN;U.S.A.",
                    "J.W.  Luscher Mfg.;65 Addams Street;Berkely;MA;U.S.A.",
                    "Scuba Professionals;3105 East Brace;Rancho Dominguez;CA;U.S.A.",
                    "Divers'  Supply Shop;5208 University Dr;Macon;GA;U.S.A.",
                    "Techniques;52 Dolphin Drive;Redwood City;CA;U.S.A.",
                    "Perry Scuba;3443 James Ave;Hapeville;GA;U.S.A.",
                    "Beauchat, Inc.;45900 SW 2nd Ave;Ft Lauderdale;FL;U.S.A.",
                    "Amor Aqua;42 West 29th Street;New York;NY;U.S.A.",
                    "Aqua Research Corp.;P.O. Box 998;Cornish;NH;U.S.A.",
                    "B&K Undersea Photo;116 W 7th Street;New York;NY;U.S.A.",
                    "Diving International Unlimited;1148 David Drive;San Diego;DA;U.S.A.",
                    "Nautical Compressors;65 NW 167 Street;Miami;FL;U.S.A.",
                    "Glen Specialties, Inc.;17663 Campbell Lane;Huntington Beach;CA;U.S.A.",
                    "Dive Time;20 Miramar Ave;Long Beach;CA;U.S.A.",
                    "Undersea Systems, Inc.;18112 Gotham Street;Huntington Beach;CA;U.S.A.",
                    "Felix Diving;310 S Michigan Ave;Chicago;IL;U.S.A.",
                    "Central Valley Skin Divers;160 Jameston Ave;Jamaica;NY;U.S.A.",
                    "Parkway Dive Shop;241 Kelly Street;South Amboy;NJ;U.S.A.",
                    "Marine Camera & Dive;117 South Valley Rd;San Diego;CA;U.S.A.",
                    "Dive Canada;275 W Ninth Ave;Vancouver;British Columbia;Canada",
                    "Dive & Surf;P.O. Box 20210;Indianapolis;IN;U.S.A.",
                    "Fish Research Labs;29 Wilkins Rd Dept. SD;Los Banos;CA;U.S.A."
                };
            PdfGrid grid = new PdfGrid();
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

            String[] header = data[0].Split(';');
            grid.Columns.Add(header.Length);
            float width
                = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);
            grid.Columns[0].Width = width * 0.25f;
            grid.Columns[1].Width = width * 0.25f;
            grid.Columns[2].Width = width * 0.25f;
            grid.Columns[3].Width = width * 0.15f;
            grid.Columns[4].Width = width * 0.10f;
            PdfGridRow headerRow = grid.Headers.Add(1)[0];
            headerRow.Style.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold), true);
            headerRow.Style.BackgroundBrush
                = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(x1, 0), Color.Red, Color.Blue);
            for (int i = 0; i < header.Length; i++)
            {
                headerRow.Cells[i].Value = header[i];
                headerRow.Cells[i].StringFormat
                    = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
                if (i == 0)
                {
                    headerRow.Cells[i].Style.BackgroundBrush = PdfBrushes.Gray;
                }
            }

            Random random = new Random();
            Dictionary<String, int> groupByCountry = new Dictionary<String, int>();
            for (int r = 1; r < data.Length; r++)
            {
                PdfGridRow row = grid.Rows.Add();
                row.Style.Font = new PdfTrueTypeFont(new Font("Arial", 10f), true);
                byte[] buffer = new byte[6];
                random.NextBytes(buffer);
                PdfRGBColor color1 = new PdfRGBColor(buffer[0], buffer[1], buffer[2]);
                PdfRGBColor color2 = new PdfRGBColor(buffer[3], buffer[4], buffer[5]);
                row.Style.BackgroundBrush
                    = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(x1, 0), color1, color2);
                String[] rowData = data[r].Split(';');
                for (int c = 0; c < rowData.Length; c++)
                {
                    row.Cells[c].Value = rowData[c];
                    if (c == 0)
                    {
                        row.Cells[c].Style.BackgroundBrush = PdfBrushes.Gray;
                    }
                    if(c < 3)
                    {
                        row.Cells[c].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        row.Cells[c].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
                    }
                    if (c == 4)
                    {
                        if (groupByCountry.ContainsKey(rowData[c]))
                        {
                            groupByCountry[rowData[c]] = groupByCountry[rowData[c]] + 1;
                        }
                        else
                        {
                            groupByCountry[rowData[c]] = 1;
                        }
                    }
                }
            }
            StringBuilder totalAmount = new StringBuilder();
            foreach (KeyValuePair<String, int> country in groupByCountry)
            {
                totalAmount.AppendFormat("{0}:\t{1}", country.Key, country.Value);
                totalAmount.AppendLine();
            }

            PdfGridRow totalAmountRow = grid.Rows.Add();
            totalAmountRow.Style.BackgroundBrush = PdfBrushes.Plum;
            totalAmountRow.Cells[0].Value = "Total Amount";
            totalAmountRow.Cells[0].Style.Font = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold), true);
            totalAmountRow.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
            totalAmountRow.Cells[1].ColumnSpan = 4;
            totalAmountRow.Cells[1].Value = totalAmount.ToString();
            totalAmountRow.Cells[1].Style.Font = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold | FontStyle.Italic), true);
            totalAmountRow.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);

            //append product list
            PdfGrid productList = new PdfGrid();
            productList.Style.Font = new PdfTrueTypeFont(new Font("Arial", 8f), true);
            using (OleDbConnection conn = new OleDbConnection())
            {
                conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\..\..\Data\demo.mdb";
                OleDbCommand command = new OleDbCommand();
                command.CommandText
                    = " select p.Description "
                    + " from vendors v "
                    + "     inner join parts p "
                    + "     on v.VendorNo = p.VendorNo "
                    + " where v.VendorName = 'Cacor Corporation'";
                command.Connection = conn;
                using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
                {
                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);
                    productList.DataSource = dataTable;
                }
            }
            productList.Headers[0].Cells[0].Value = "Cacor Corporation";
            productList.Headers[0].Cells[0].Style.Font = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Bold), true);
            productList.Headers[0].Cells[0].Style.Borders.All = new PdfPen(new PdfTilingBrush(new SizeF(1, 1)), 0);
            grid.Rows[0].Cells[0].Value = productList;
            grid.Rows[0].Cells[0].StringFormat.Alignment = PdfTextAlignment.Left;

            PdfLayoutResult result = grid.Draw(page, new PointF(0, y));
            y = y + result.Bounds.Height + 5;

            PdfBrush brush2 = PdfBrushes.Gray;
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f));
            result.Page.Canvas.DrawString(String.Format("* All {0} vendors in the list", grid.Rows.Count - 1),
                font2, brush2, 5, y);

            //Save pdf file.
            doc.SaveToFile("Grid.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Grid.pdf");
        }