Example #1
0
        /// <summary>
        /// The write plot.
        /// </summary>
        /// <param name="plot">
        /// The plot.
        /// </param>
        public void WritePlot(PlotFigure plot)
        {
            if (this.FileName == null)
            {
                return;
            }

            var directory = Path.GetDirectoryName(this.FileName);

            if (directory == null)
            {
                return;
            }

            var source = string.Format(
                "{0}_Plot{1}.pdf", Path.GetFileNameWithoutExtension(this.FileName), plot.FigureNumber);
            var sourceFullPath = Path.Combine(directory, source);

            PdfExporter.Export(plot.PlotModel, sourceFullPath, plot.Width, plot.Height);

            var p = this.WriteStartFigure(plot);

            MigraDoc.DocumentObjectModel.Shapes.Image pi = p.AddImage(sourceFullPath);
            pi.Width = Unit.FromCentimeter(15);

            this.WriteEndFigure(plot, p);
        }
        public static MigraDoc.DocumentObjectModel.Document CreateDocument(string input)
        {
            MigraDoc.DocumentObjectModel.Document document = new MigraDoc.DocumentObjectModel.Document();
            document.DefaultPageSetup.Orientation    = MigraDoc.DocumentObjectModel.Orientation.Portrait;
            document.DefaultPageSetup.HeaderDistance = 1;
            Section section = document.AddSection();

            section.PageSetup.TopMargin    = 90;
            section.PageSetup.BottomMargin = 20;
            section.PageSetup.RightMargin  = 5;
            section.PageSetup.LeftMargin   = 50;
            Paragraph header = section.Headers.Primary.AddParagraph();

            MigraDoc.DocumentObjectModel.Shapes.Image img = new MigraDoc.DocumentObjectModel.Shapes.Image();
            header.AddImage(@"\\192.168.201.6\Telex\white.png");
            Paragraph paragraph = section.AddParagraph();

            MigraDoc.DocumentObjectModel.Shapes.Image img2 = new MigraDoc.DocumentObjectModel.Shapes.Image();
            header.AddImage(@"\\192.168.201.6\Telex\logo.png");
            Paragraph paragraph2 = section.AddParagraph();

            paragraph.Format.Font.Color = MigraDoc.DocumentObjectModel.Color.FromCmyk(0, 0, 0, 100);
            paragraph.Format.Font.Name  = "Courier New";
            paragraph.Format.Font.Size  = 9;
            paragraph.AddText(input.Replace(" ", " "));
            return(document);
        }//--------------------------------------
Example #3
0
        /// <summary>Creates the graph page.</summary>
        /// <param name="section">The section to write to.</param>
        /// <param name="graphPage">The graph and table to convert to html.</param>
        private void CreateGraphPage(Section section, GraphPage graphPage)
        {
            int numGraphsToPrint = graphPage.graphs.FindAll(g => g.IncludeInDocumentation).Count;

            if (numGraphsToPrint > 0)
            {
                int numColumns = 2;
                int numRows    = (numGraphsToPrint + 1) / numColumns;

                // Export graph to bitmap file.
                Bitmap image = new Bitmap(1800, numRows * 600);
                using (Graphics gfx = Graphics.FromImage(image))
                    using (SolidBrush brush = new SolidBrush(System.Drawing.Color.White))
                    {
                        gfx.FillRectangle(brush, 0, 0, image.Width, image.Height);
                    }
                GraphPresenter graphPresenter = new GraphPresenter();
                explorerPresenter.ApsimXFile.Links.Resolve(graphPresenter);
                GraphView graphView = new GraphView();
                graphView.BackColor        = OxyPlot.OxyColors.White;
                graphView.ForegroundColour = OxyPlot.OxyColors.Black;
                graphView.FontSize         = 22;
                graphView.MarkerSize       = MarkerSizeType.Normal;
                graphView.Width            = image.Width / numColumns;
                graphView.Height           = image.Height / numRows;
                graphView.LeftRightPadding = 0;

                int col = 0;
                int row = 0;
                for (int i = 0; i < graphPage.graphs.Count; i++)
                {
                    if (graphPage.graphs[i].IncludeInDocumentation)
                    {
                        graphPresenter.Attach(graphPage.graphs[i], graphView, explorerPresenter);
                        Rectangle r = new Rectangle(col * graphView.Width, row * graphView.Height,
                                                    graphView.Width, graphView.Height);
                        graphView.Export(ref image, r, false);
                        graphPresenter.Detach();
                        col++;
                        if (col >= numColumns)
                        {
                            col = 0;
                            row++;
                        }
                    }
                }

                string basePngFileName = Apsim.FullPath(graphPage.graphs[0].Parent) + "." +
                                         graphPage.name + ".png";
                basePngFileName = basePngFileName.TrimStart('.');
                string pngFileName = Path.Combine(WorkingDirectory, basePngFileName);
                image.Save(pngFileName, System.Drawing.Imaging.ImageFormat.Png);

                MigraDoc.DocumentObjectModel.Shapes.Image sectionImage = section.AddImage(pngFileName);
                sectionImage.LockAspectRatio = true;
                sectionImage.Width           = "19cm";
            }
        }
Example #4
0
        private void печатьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (!webControl1.IsLive)
                {
                    return;
                }

                Graphics g = webControl1.CreateGraphics();
                File.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\temp.png");
                int bmpHeight;
                int bmpWidth;
                using (Bitmap bmp = new Bitmap(webControl1.Width, webControl1.Height))
                {
                    webControl1.DrawToBitmap(bmp, new Rectangle(0, 0, webControl1.Width, webControl1.Height));
                    bmp.Save(AppDomain.CurrentDomain.BaseDirectory + @"\temp.png", System.Drawing.Imaging.ImageFormat.Png);
                    bmpHeight = bmp.Height;
                    bmpWidth  = bmp.Width;
                }
                document = new Document();
                Style style = document.Styles["Normal"];
                style.Font.Name = "Times New Roman";
                style.Font.Size = 10;
                Section   page = document.AddSection();
                PageSetup p    = new PageSetup();
                p.OddAndEvenPagesHeaderFooter = true;
                p.StartingNumber = 1;
                p.BottomMargin   = "5mm";
                p.LeftMargin     = "5mm";
                p.RightMargin    = "5mm";
                p.TopMargin      = "5mm";
                p.PageFormat     = PageFormat.A4;
                if (bmpHeight > 700 | bmpWidth > 1070 && bmpHeight <= 1050 && bmpWidth <= 1530)
                {
                    p.PageFormat = PageFormat.A3;
                }
                else if (bmpHeight > 1050 | bmpWidth > 1530 && bmpHeight <= 1530 && bmpWidth <= 2100)
                {
                    p.PageFormat = PageFormat.A2;
                }
                p.Orientation  = MigraDoc.DocumentObjectModel.Orientation.Landscape;
                page.PageSetup = p;
                Paragraph paragraph = page.AddParagraph(this.Text);
                paragraph.Style = "Normal";
                paragraph       = page.AddParagraph("");
                paragraph.Style = "Normal";
                MigraDoc.DocumentObjectModel.Shapes.Image map = paragraph.AddImage(@"temp.png");
                paragraph.Style   = "Normal";
                paragraph         = page.AddParagraph(toolStripStatusLabel1.Text);
                renderer          = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
                renderer.Document = document;
                renderer.RenderDocument();
                renderer.Save(saveFileDialog1.FileName);
                Process.Start(saveFileDialog1.FileName);
            }
        }
        public static MigraDoc.DocumentObjectModel.Paragraph  ExportToPDF(string imagefulpathname)
        {
            // Add a paragraph to the section
            MigraDoc.DocumentObjectModel.Paragraph paragraph = new MigraDoc.DocumentObjectModel.Paragraph();

            MigraDoc.DocumentObjectModel.Shapes.Image img1 = paragraph.AddImage(imagefulpathname);
            img1.LockAspectRatio = true;
            return(paragraph);
        }
Example #6
0
        private void AddImage(string src)
        {
            //string imageFilename = LoadImage(string.Format(@"{0}",home.MainPhoto));
            string imageFilename = LoadImage(string.Format(@"{0}", src));

            MigraDoc.DocumentObjectModel.Shapes.Image image = Migradoc.LastSection.AddImage(imageFilename);
            image.Width           = "6cm";
            image.LockAspectRatio = true;
        }
Example #7
0
        /// <summary>
        /// Render this component into a section
        /// </summary>
        public void RenderInto(Cell cell)
        {
            MigraDoc.DocumentObjectModel.Shapes.Image image = new MigraDoc.DocumentObjectModel.Shapes.Image();

            image.Name   = this.path;
            image.Height = Unit.FromMillimeter(this.height);
            image.Width  = Unit.FromMillimeter(this.width);

            cell.Add(image);
        }
Example #8
0
        /// <summary>
        /// Writes the specified image.
        /// </summary>
        /// <param name="i">The image.</param>
        void IReportWriter.WriteImage(Image i)
        {
            var p = this.WriteStartFigure(i);

            if (i.Source != null)
            {
                MigraDoc.DocumentObjectModel.Shapes.Image pi = p.AddImage(Path.GetFullPath(i.Source));
                pi.Width = Unit.FromCentimeter(15);
            }

            this.WriteEndFigure(i, p);
        }
Example #9
0
        /// <summary>
        /// Writes the specified plot.
        /// </summary>
        /// <param name="plot">The plot.</param>
        void IReportWriter.WritePlot(PlotFigure plot)
        {
            var temporaryPlotFileName = Guid.NewGuid() + ".pdf";

            this.temporaryPlotFiles.Add(temporaryPlotFileName);
            PdfExporter.Export(plot.PlotModel, temporaryPlotFileName, plot.Width, plot.Height);

            var p = this.WriteStartFigure(plot);

            MigraDoc.DocumentObjectModel.Shapes.Image pi = p.AddImage(temporaryPlotFileName);
            pi.Width = Unit.FromCentimeter(15);

            this.WriteEndFigure(plot, p);
        }
Example #10
0
        public Document CreateTreningDOC()
        {
            Section section = document.AddSection();

            PageSettings(section);

            for (int i = 0; i < Ustawienia.ilosc_rozdan; i++)
            {
                if (i != 0)
                {
                    document.AddSection();
                }
                CreateBoard(i, game.rozklady[i + 1]);
                CreateBidding(i);
                //      WriteLineKontrakt(game.ContractList[i]);
                WriteCommentTitle();
            }


            MigraDoc.DocumentObjectModel.Shapes.Image reklama = new MigraDoc.DocumentObjectModel.Shapes.Image("images\\reklama.png");

            reklama.Height = Unit.FromCentimeter(6.5);
            reklama.Width  = Unit.FromCentimeter(12.0);

            reklama.WrapFormat.DistanceTop  = Unit.FromCentimeter(1.0);
            reklama.WrapFormat.DistanceLeft = Unit.FromCentimeter(2.0);

            document.LastSection.Add(reklama);
            document.UseCmykColor = true;


            string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document);


            RtfDocumentRenderer renderer = new RtfDocumentRenderer();

            renderer.Render(document, "Test.doc", null);

            Process.Start("Test.doc");

            return(document);
        }
Example #11
0
        public static void printPicture(Picture p)
        {
            Document doc      = new Document();
            Section  section1 = doc.AddSection();

            MigraDoc.DocumentObjectModel.Shapes.Image image = section1.AddImage(Conversion.MigrDocFilenameFromBase64(p.Image));
            image.Width           = "16cm";
            image.LockAspectRatio = true;
            Paragraph paragraph1 = section1.AddParagraph();

            paragraph1.AddFormattedText("Photographer: ", TextFormat.Bold);
            if (p.Photographer != null)
            {
                paragraph1.AddText(p.Photographer.ToString() + "\n\n");
            }
            else
            {
                paragraph1.AddText("-" + "\n\n");
            }
            Paragraph paragraph2 = section1.AddParagraph();

            paragraph2.AddFormattedText("EXIF Properties:\n", TextFormat.Bold);
            paragraph2.AddText(PrintableExifProperties(p));
            paragraph2.AddFormattedText("IPTC Properties:\n", TextFormat.Bold);
            paragraph2.AddText(PrintableIptcProperties(p));
            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false);

            pdfRenderer.Document = doc;
            pdfRenderer.RenderDocument();

            OpenFileDialog dialog = new OpenFileDialog();

            dialog.CheckFileExists = false;
            var result = dialog.ShowDialog();

            if (result == false)
            {
                return;
            }
            pdfRenderer.PdfDocument.Save(dialog.FileName);
        }
        private void addImageToFollowupTable(string rowTitle, ImageSource imageData, double imageHeight)
        {
            Paragraph currentParagraph;
            Row       currentRow = followupTable.AddRow();

            currentParagraph = currentRow.Cells[0].AddParagraph();
            currentParagraph.AddText(rowTitle);
            currentParagraph.Style = "sectionHeader";

            currentParagraph = currentRow.Cells[1].AddParagraph();

            if (imageData != null)
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                var bitmapSource         = imageData as BitmapSource;
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

                byte[] bytes = null;

                using (var stream = new MemoryStream())
                {
                    encoder.Save(stream);
                    bytes = stream.ToArray();
                }

                //Change the selected image to a string
                string imageStr = "base64:" + Convert.ToBase64String(bytes);

                MigraDoc.DocumentObjectModel.Shapes.Image imageAdded = currentParagraph.AddImage(imageStr);
                imageAdded.LockAspectRatio = true;
                imageAdded.Height          = new Unit(imageHeight, UnitType.Centimeter);
                imageAdded.Left            = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Left;
            }
            currentParagraph.Style            = "Normal";
            currentRow.Cells[0].Shading.Color = entryHeaderGrey;
        }
Example #13
0
        public Document CreateTreningDOC()
        {
            Section section = document.AddSection();

            PageSettings(section);
            if (Ustawienia.deepfin)
            {
                lewy = InfoBridge.wylicz_DF(vugraph1.rozklady);
            }
            imps1 = new int[Ustawienia.ilosc_rozdan];
            imps2 = new int[Ustawienia.ilosc_rozdan];
            imps1 = wyliczimpy(vugraph1.Vu_ContractList_Open, vugraph1.Vu_ContractList_Closed);
            imps2 = wyliczimpy(vugraph2.Vu_ContractList_Open, vugraph2.Vu_ContractList_Closed);
            for (int i = 0; i < Ustawienia.ilosc_rozdan; i++)
            {
                if (i != 0)
                {
                    document.AddSection();
                }

                CreateBoard(i, vugraph1.rozklady[i]);
                if (Ustawienia.deepfin)
                {
                    CreateDF(i);
                }

                //pierwsza tabela licytacji
                CreateBidding(i, vugraph1);
                WriteLineKontrakt(vugraph1.Vu_ContractList_Open[i], vugraph1.Vu_ContractList_Closed[i]);
                if (imps1[i] != 0)
                {
                    Paragraph p = new Paragraph();
                    p.AddLineBreak();
                    p.AddFormattedText("Wynik : ");
                    p.AddFormattedText(imps1[i].ToString());
                    if (imps1[i] > 0)
                    {
                        p.AddFormattedText(imps1[i].ToString());
                        p.AddFormattedText(" imp dla " + vugraph1.team1Name);
                    }
                    if (imps1[i] < 0)
                    {
                        p.AddFormattedText((-imps1[i]).ToString());
                        p.AddFormattedText(" imp dla " + vugraph1.team2Name);
                    }
                    p.AddLineBreak();
                    document.LastSection.Add(p);
                }
                // druga tabela licytacji
                CreateBidding(i, vugraph2);
                WriteLineKontrakt(vugraph2.Vu_ContractList_Open[i], vugraph2.Vu_ContractList_Closed[i]);
                if (imps2[i] != 0)
                {
                    Paragraph p = new Paragraph();
                    p.AddLineBreak();
                    p.AddFormattedText("Wynik : ");
                    p.AddFormattedText(imps2[i].ToString());
                    if (imps2[i] > 0)
                    {
                        p.AddFormattedText(imps2[i].ToString());
                        p.AddFormattedText(" imp dla " + vugraph2.team1Name);
                    }
                    if (imps2[i] < 0)
                    {
                        p.AddFormattedText((-imps2[i]).ToString());
                        p.AddFormattedText(" imp dla " + vugraph2.team2Name);
                    }
                    p.AddLineBreak();
                    document.LastSection.Add(p);
                }
            }
            MakeTable33(vugraph1);
            MakeTable33(vugraph2);


            MigraDoc.DocumentObjectModel.Shapes.Image reklama = new MigraDoc.DocumentObjectModel.Shapes.Image("images\\reklama.png");

            reklama.Height = Unit.FromCentimeter(6.5);
            reklama.Width  = Unit.FromCentimeter(12.0);

            reklama.WrapFormat.DistanceTop  = Unit.FromCentimeter(1.0);
            reklama.WrapFormat.DistanceLeft = Unit.FromCentimeter(2.0);

            document.LastSection.Add(reklama);
            document.UseCmykColor = true;


            string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document);


            // RtfDocumentRenderer renderer = new RtfDocumentRenderer();
            // renderer.Render(document, "Test.doc", null);

            // Process.Start("Test.doc");

            return(document);
        }
Example #14
0
        /// <summary>Creates the graph.</summary>
        /// <param name="writer">The writer.</param>
        /// <param name="graphAndTable">The graph and table to convert to html.</param>
        private void CreateGraphPDF(Section section, AutoDocumentation.GraphAndTable graphAndTable)
        {
            // Create a 2 column, 1 row table. Image in first cell, X/Y data in second cell.
            var table = section.AddTable();

            table.Style           = "GraphAndTable";
            table.Rows.LeftIndent = graphAndTable.indent + "cm";

            var column1 = table.AddColumn();

            column1.Width = "8cm";
            //column1.Format.Alignment = ParagraphAlignment.Right;
            var column2 = table.AddColumn();

            column2.Width = "8cm";
            //column2.Format.Alignment = ParagraphAlignment.Right;
            var row = table.AddRow();

            // Ensure graphs directory exists.
            string graphDirectory = Path.Combine(WorkingDirectory, "Graphs");

            Directory.CreateDirectory(graphDirectory);

            // Determine the name of the .png file to write.
            string pngFileName = Path.Combine(graphDirectory,
                                              graphAndTable.xyPairs.Parent.Parent.Name + graphAndTable.xyPairs.Parent.Name + ".png");
            int count = 0;

            // If there are multiple graphs with the same name, they may overwrite each other.
            // Therefore, we attempt to generate a unique name. After 20 attempts, we give up.
            while (File.Exists(pngFileName) && count < 20)
            {
                count++;
                pngFileName = Path.Combine(graphDirectory, graphAndTable.xyPairs.Parent.Parent.Name + graphAndTable.xyPairs.Parent.Name + Guid.NewGuid() + ".png");
            }
            // Setup graph.
            GraphView graph = new GraphView();

            graph.Clear();
            graph.Width  = 400;
            graph.Height = 250;

            // Create a line series.
            graph.DrawLineAndMarkers("", graphAndTable.xyPairs.X, graphAndTable.xyPairs.Y, null, null, null,
                                     Models.Axis.AxisType.Bottom, Models.Axis.AxisType.Left,
                                     System.Drawing.Color.Blue, Models.LineType.Solid, Models.MarkerType.None,
                                     Models.LineThicknessType.Normal, Models.MarkerSizeType.Normal, 1, true);

            graph.ForegroundColour = OxyPlot.OxyColors.Black;
            graph.BackColor        = OxyPlot.OxyColors.White;
            // Format the axes.
            graph.FormatAxis(Models.Axis.AxisType.Bottom, graphAndTable.xName, false, double.NaN, double.NaN, double.NaN, false);
            graph.FormatAxis(Models.Axis.AxisType.Left, graphAndTable.yName, false, double.NaN, double.NaN, double.NaN, false);
            graph.FontSize = 10;
            graph.Refresh();

            // Export graph to bitmap file.
            Bitmap image = new Bitmap(graph.Width, graph.Height);

            using (Graphics gfx = Graphics.FromImage(image))
                using (SolidBrush brush = new SolidBrush(System.Drawing.Color.White))
                {
                    gfx.FillRectangle(brush, 0, 0, image.Width, image.Height);
                }
            graph.Export(ref image, new Rectangle(0, 0, image.Width, image.Height), false);
            graph.MainWidget.Destroy();
            image.Save(pngFileName, System.Drawing.Imaging.ImageFormat.Png);
            MigraDoc.DocumentObjectModel.Shapes.Image sectionImage = row.Cells[0].AddImage(pngFileName);
            sectionImage.LockAspectRatio = true;
            sectionImage.Width           = "8cm";

            // Add x/y data.
            Paragraph xyParagraph = row.Cells[1].AddParagraph();

            xyParagraph.Style = "xyStyle";
            AddFixedWidthText(xyParagraph, "X", 10);
            AddFixedWidthText(xyParagraph, "Y", 10);
            xyParagraph.AddLineBreak();
            for (int i = 0; i < graphAndTable.xyPairs.X.Length; i++)
            {
                AddFixedWidthText(xyParagraph, graphAndTable.xyPairs.X[i].ToString(), 10);
                AddFixedWidthText(xyParagraph, graphAndTable.xyPairs.Y[i].ToString(), 10);
                xyParagraph.AddLineBreak();
            }

            // Add an empty paragraph for spacing.
            section.AddParagraph();
        }
Example #15
0
        public Document CriaRelatorio()
        {
            Document relatorio = new Document();
            Section  section   = relatorio.AddSection();

            MigraDoc.DocumentObjectModel.Shapes.Image img = section.Headers.Primary.AddImage("gustavo2.png");
            img.Height             = "15cm";
            img.LockAspectRatio    = true;
            img.RelativeVertical   = MigraDoc.DocumentObjectModel.Shapes.RelativeVertical.Page;
            img.RelativeHorizontal = MigraDoc.DocumentObjectModel.Shapes.RelativeHorizontal.Page;
            img.Top              = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Center;
            img.Left             = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Center;
            img.WrapFormat.Style = MigraDoc.DocumentObjectModel.Shapes.WrapStyle.Through;

            section.PageSetup.TopMargin    = 25;
            section.PageSetup.LeftMargin   = 25;
            section.PageSetup.RightMargin  = 25;
            section.PageSetup.BottomMargin = 25;
            section.PageSetup.PageFormat   = PageFormat.A4;

            #region HeaderRelatorio
            Paragraph primeira_linha = section.AddParagraph("RELATÓRIO DE ENTRADA DÍZIMOS E OFERTAS - IGREJA BATISTA RENOVO");
            primeira_linha.Format.Alignment = ParagraphAlignment.Center;

            MigraDoc.DocumentObjectModel.Tables.Table tabela_header = new MigraDoc.DocumentObjectModel.Tables.Table();
            MigraDoc.DocumentObjectModel.Tables.Row   linha_header;
            tabela_header.Borders.Width = 0.5;

            MigraDoc.DocumentObjectModel.Tables.Column coluna_header = tabela_header.AddColumn("18cm");
            coluna_header.Format.Font.Name = "Calibri";
            coluna_header.Shading.Color    = Colors.WhiteSmoke;
            linha_header = tabela_header.AddRow();
            linha_header.Format.Alignment = ParagraphAlignment.Center;
            linha_header.Format.Font.Bold = true;
            linha_header.Cells[0].AddParagraph(System.DateTime.Now.ToString("dd/MM/yyyy") + " - " + Util.Funcoes.RetornaDia() + "(" + Util.Funcoes.RetornaPeriodo() + ")");
            tabela_header.SetEdge(0, 0, 0, 1, MigraDoc.DocumentObjectModel.Tables.Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1, Colors.Black);
            relatorio.LastSection.Add(tabela_header);
            #endregion
            Paragraph quebra_linha_headerReport = section.AddParagraph("");

            #region HeaderTabela
            MigraDoc.DocumentObjectModel.Tables.Table tabela_dizimistas;
            MigraDoc.DocumentObjectModel.Tables.Row   linha_dizimistas;

            tabela_dizimistas = new MigraDoc.DocumentObjectModel.Tables.Table();
            tabela_dizimistas.Borders.Width = 0.5;

            MigraDoc.DocumentObjectModel.Tables.Column coluna1 = tabela_dizimistas.AddColumn("14cm");
            coluna1.Format.Font.Name = "Calibri";

            MigraDoc.DocumentObjectModel.Tables.Column coluna2 = tabela_dizimistas.AddColumn("4cm");
            coluna2.Format.Font.Name = "Calibri";

            linha_dizimistas = tabela_dizimistas.AddRow();
            linha_dizimistas.Shading.Color     = Colors.Black;
            linha_dizimistas.Format.Font.Color = Colors.White;
            linha_dizimistas.Format.Font.Bold  = true;
            linha_dizimistas.Format.Alignment  = ParagraphAlignment.Center;
            linha_dizimistas.Cells[0].AddParagraph("DIZIMISTA");
            linha_dizimistas.Cells[1].AddParagraph("VALOR");
            #endregion

            #region ItensTabela
            decimal total_dizimos = 0;

            var listaDetalhes = _unitOfWork.CabecalhosEntradas.ListaDetalhes(Convert.ToInt32(Util.DataCript.Decriptar(HttpContext.Session.GetString("_hash"))));

            EntradaResponse total = new EntradaResponse
            {
                VlTotalDizimo  = listaDetalhes[0].ItensCategoria.Where(w => w.IdCategoria == 1).Sum(s => s.Valor),
                VlTotalOferta  = listaDetalhes[0].ItensCategoria.Where(w => w.IdCategoria == 2).Sum(s => s.Valor),
                VlTotalMissoes = listaDetalhes[0].ItensCategoria.Where(w => w.IdCategoria == 3).Sum(s => s.Valor),
                VlTotalReforma = listaDetalhes[0].ItensCategoria.Where(w => w.IdCategoria == 4).Sum(s => s.Valor),

                VlTotalNotas   = listaDetalhes[0].ItensTipo.Where(w => w.IdTipo == 1).Sum(s => s.Valor),
                VlTotalMoedas  = listaDetalhes[0].ItensTipo.Where(w => w.IdTipo == 2).Sum(s => s.Valor),
                VlTotalCheque  = listaDetalhes[0].ItensTipo.Where(w => w.IdTipo == 3).Sum(s => s.Valor),
                VlTotalDebito  = listaDetalhes[0].ItensTipo.Where(w => w.IdTipo == 4).Sum(s => s.Valor),
                VlTotalCredito = listaDetalhes[0].ItensTipo.Where(w => w.IdTipo == 5).Sum(s => s.Valor),
                VlTotalTransf  = listaDetalhes[0].ItensTipo.Where(w => w.IdTipo == 6).Sum(s => s.Valor),
            };
            total.VlTotalCategoria = total.VlTotalDizimo + total.VlTotalOferta + total.VlTotalMissoes + total.VlTotalReforma;
            total.VlTotalTipo      = total.VlTotalNotas + total.VlTotalMoedas + total.VlTotalCheque + total.VlTotalDebito + total.VlTotalCredito + total.VlTotalTransf;

            var lista = _unitOfWork.CabecalhosEntradas.ListarResponse(Convert.ToInt32(Util.DataCript.Decriptar(HttpContext.Session.GetString("_hash"))));

            RetornoResponse retorno = new RetornoResponse
            {
                retornoTotais = total,
                retornoLista  = lista
            };

            foreach (var linha in retorno.retornoLista.Where(w => w.Dizimo > 0))
            {
                linha_dizimistas = tabela_dizimistas.AddRow();
                linha_dizimistas.Format.Font.Size = 9;
                //linha_dizimistas.Cells[0].AddParagraph(Util.DataCript.Decriptar(linha.Pessoa.Nome).ToUpper());
                linha_dizimistas.Cells[0].AddParagraph(linha.Pessoa.Nome.ToUpper());
                linha_dizimistas.Cells[1].AddParagraph(linha.Dizimo.ToString());
                total_dizimos += linha.Dizimo;
            }

            tabela_dizimistas.SetEdge(0, 0, 0, 1, MigraDoc.DocumentObjectModel.Tables.Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1, Colors.Black);
            relatorio.LastSection.Add(tabela_dizimistas);
            #endregion

            Paragraph quebra_linha_totalizadores  = section.AddParagraph("");
            Paragraph quebra_linha_totalizadores2 = section.AddParagraph("");
            #region Totalizadores
            decimal total_ofertas  = 0;
            decimal total_missoes  = 0;
            decimal total_infantil = 0;
            decimal total_reforma  = 0;

            total_ofertas  = retorno.retornoTotais.VlTotalOferta;
            total_missoes  = retorno.retornoTotais.VlTotalMissoes;
            total_infantil = 0;
            total_reforma  = retorno.retornoTotais.VlTotalReforma;

            MigraDoc.DocumentObjectModel.Tables.Table tabela_total;
            MigraDoc.DocumentObjectModel.Tables.Row   linha_total;

            tabela_total = new MigraDoc.DocumentObjectModel.Tables.Table();
            tabela_total.Borders.Width = 0.5;
            MigraDoc.DocumentObjectModel.Tables.Column coluna_total1 = tabela_total.AddColumn("14cm");
            coluna_total1.Format.Font.Name = "Calibri";

            MigraDoc.DocumentObjectModel.Tables.Column coluna_total2 = tabela_total.AddColumn("4cm");
            coluna_total2.Format.Font.Name = "Calibri";

            linha_total = tabela_total.AddRow();
            linha_total.Shading.Color    = Colors.Gray;
            linha_total.Format.Alignment = ParagraphAlignment.Center;
            linha_total.Cells[0].AddParagraph("TOTAL DIZIMOS");
            linha_total.Cells[1].AddParagraph(total_dizimos.ToString());

            linha_total = tabela_total.AddRow();
            linha_total.Shading.Color    = Colors.Gray;
            linha_total.Format.Alignment = ParagraphAlignment.Center;
            linha_total.Cells[0].AddParagraph("TOTAL OFERTAS");
            linha_total.Cells[1].AddParagraph(total_ofertas.ToString());

            linha_total = tabela_total.AddRow();
            linha_total.Shading.Color    = Colors.Gray;
            linha_total.Format.Alignment = ParagraphAlignment.Center;
            linha_total.Cells[0].AddParagraph("TOTAL MISSÕES");
            linha_total.Cells[1].AddParagraph(total_missoes.ToString());

            linha_total = tabela_total.AddRow();
            linha_total.Shading.Color    = Colors.Gray;
            linha_total.Format.Alignment = ParagraphAlignment.Center;
            linha_total.Cells[0].AddParagraph("TOTAL REFORMA");
            linha_total.Cells[1].AddParagraph(total_reforma.ToString());

            linha_total = tabela_total.AddRow();
            linha_total.Shading.Color    = Colors.Gray;
            linha_total.Format.Alignment = ParagraphAlignment.Center;
            linha_total.Cells[0].AddParagraph("TOTAL INFANTIL");
            linha_total.Cells[1].AddParagraph(total_infantil.ToString());

            linha_total = tabela_total.AddRow();
            linha_total.Shading.Color    = Colors.DarkGray;
            linha_total.Format.Font.Bold = true;
            linha_total.Format.Alignment = ParagraphAlignment.Center;
            linha_total.Cells[0].AddParagraph("TOTAL");
            var totalCateg = total_dizimos + total_ofertas + total_missoes + total_reforma + total_infantil;
            linha_total.Cells[1].AddParagraph(totalCateg.ToString());

            tabela_total.SetEdge(0, 0, 0, 1, MigraDoc.DocumentObjectModel.Tables.Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1, Colors.Black);
            relatorio.LastSection.Add(tabela_total);
            #endregion

            Paragraph quebra_linha_tipo  = section.AddParagraph("");
            Paragraph quebra_linha_tipo2 = section.AddParagraph("");
            #region RelatorioTipo
            MigraDoc.DocumentObjectModel.Tables.Table tabela_tipo;
            MigraDoc.DocumentObjectModel.Tables.Row   linha_tipo;

            tabela_tipo = new MigraDoc.DocumentObjectModel.Tables.Table();
            tabela_tipo.Borders.Width = 0.5;
            MigraDoc.DocumentObjectModel.Tables.Column coluna_nota    = tabela_tipo.AddColumn("3cm");
            MigraDoc.DocumentObjectModel.Tables.Column coluna_moeda   = tabela_tipo.AddColumn("3cm");
            MigraDoc.DocumentObjectModel.Tables.Column coluna_cheque  = tabela_tipo.AddColumn("3cm");
            MigraDoc.DocumentObjectModel.Tables.Column coluna_debito  = tabela_tipo.AddColumn("3cm");
            MigraDoc.DocumentObjectModel.Tables.Column coluna_credito = tabela_tipo.AddColumn("3cm");
            MigraDoc.DocumentObjectModel.Tables.Column coluna_transf  = tabela_tipo.AddColumn("3cm");

            coluna_nota.Format.Font.Name    = "Calibri";
            coluna_moeda.Format.Font.Name   = "Calibri";
            coluna_cheque.Format.Font.Name  = "Calibri";
            coluna_debito.Format.Font.Name  = "Calibri";
            coluna_credito.Format.Font.Name = "Calibri";
            coluna_transf.Format.Font.Name  = "Calibri";

            linha_tipo = tabela_tipo.AddRow();
            linha_tipo.Shading.Color     = Colors.Black;
            linha_tipo.Format.Font.Color = Colors.White;
            linha_tipo.Format.Font.Bold  = true;
            linha_tipo.Cells[0].AddParagraph("Notas");
            linha_tipo.Cells[1].AddParagraph("Moedas");
            linha_tipo.Cells[2].AddParagraph("Cheques");
            linha_tipo.Cells[3].AddParagraph("C. Déb.");
            linha_tipo.Cells[4].AddParagraph("C. Créd.");
            linha_tipo.Cells[5].AddParagraph("Transf.");

            decimal total_notas   = 0;
            decimal total_moedas  = 0;
            decimal total_cheques = 0;
            decimal total_debito  = 0;
            decimal total_credito = 0;
            decimal total_transf  = 0;

            total_notas   = retorno.retornoTotais.VlTotalNotas;
            total_moedas  = retorno.retornoTotais.VlTotalMoedas;
            total_cheques = retorno.retornoTotais.VlTotalCheque;
            total_debito  = retorno.retornoTotais.VlTotalDebito;
            total_credito = retorno.retornoTotais.VlTotalCredito;
            total_transf  = retorno.retornoTotais.VlTotalTransf;

            linha_tipo = tabela_tipo.AddRow();
            linha_tipo.Cells[0].AddParagraph(total_notas.ToString());
            linha_tipo.Cells[1].AddParagraph(total_moedas.ToString());
            linha_tipo.Cells[2].AddParagraph(total_cheques.ToString());
            linha_tipo.Cells[3].AddParagraph(total_debito.ToString());
            linha_tipo.Cells[4].AddParagraph(total_credito.ToString());
            linha_tipo.Cells[5].AddParagraph(total_transf.ToString());
            Paragraph quebra_linha5 = section.AddParagraph("");

            tabela_tipo.SetEdge(0, 0, 0, 1, MigraDoc.DocumentObjectModel.Tables.Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1, Colors.Black);
            relatorio.LastSection.Add(tabela_tipo);

            #endregion

            Paragraph quebra_linha_conferidoPor  = section.AddParagraph("");
            Paragraph quebra_linha_conferidoPor2 = section.AddParagraph("");
            Paragraph quebra_linha_conferidoPor3 = section.AddParagraph("");
            #region ConferidoPor
            MigraDoc.DocumentObjectModel.Tables.Table tabela_conferidoPor;
            MigraDoc.DocumentObjectModel.Tables.Row   linha_conferidoPor;

            tabela_conferidoPor = new MigraDoc.DocumentObjectModel.Tables.Table();
            tabela_conferidoPor.Borders.Width = 0;
            MigraDoc.DocumentObjectModel.Tables.Column coluna_conferidoPor = tabela_conferidoPor.AddColumn("3cm");
            coluna_conferidoPor.Format.Font.Name = "Calibri";

            MigraDoc.DocumentObjectModel.Tables.Column coluna_conferidoPor1 = tabela_conferidoPor.AddColumn("7cm");
            coluna_conferidoPor1.Format.Font.Name = "Calibri";

            MigraDoc.DocumentObjectModel.Tables.Column coluna_conferidoPor2 = tabela_conferidoPor.AddColumn("7cm");
            coluna_conferidoPor2.Format.Font.Name = "Calibri";

            linha_conferidoPor = tabela_conferidoPor.AddRow();
            linha_conferidoPor.Format.Alignment = ParagraphAlignment.Center;
            linha_conferidoPor.Cells[0].AddParagraph("CONFERIDO POR:");
            linha_conferidoPor.Cells[1].AddParagraph(Util.DataCript.Decriptar(HttpContext.Session.GetString("_header1")));
            linha_conferidoPor.Cells[1].Format.Borders.Top.Width = 0.5;
            linha_conferidoPor.Cells[2].AddParagraph(Util.DataCript.Decriptar(HttpContext.Session.GetString("_header2")));
            linha_conferidoPor.Cells[2].Format.Borders.Top.Width = 0.5;

            tabela_conferidoPor.SetEdge(0, 0, 0, 1, MigraDoc.DocumentObjectModel.Tables.Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1, Colors.Black);
            relatorio.LastSection.Add(tabela_conferidoPor);
            #endregion

            return(relatorio);
        }
        private void BtnPrintVouchersAndTickets_Click(object sender, EventArgs e)
        {
            Button button    = sender as Button;
            bool   closeForm = true;

            if ((button == BtnPrintHotelVouchers) || (button == BtnPrintBoth))
            {
                //MessageBox.Show("Button pressed = " + button.Text, "PRINTING HOTEL VOUCHERS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                /* open connection */
                try
                {
                    mySqlConnection.Open();
                }
                catch (Exception errConnOpen)
                {
                    MessageBox.Show("Error in opening mysql connection because : " + errConnOpen.Message);
                    return;
                }

                /* now execute query to obtain data from hotel booking table
                 * and fill t in dataset
                 */
                string           mySqlQueryString = "SELECT DISTINCT `idhotelinfo` FROM `hotelbookinginfo` WHERE `queryid` = '" + queryId + "' ORDER BY `idhotelinfo`";
                DataSet          dataset          = new DataSet();
                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlQueryString, mySqlConnection);
                mySqlDataAdapter.Fill(dataset, "TABLE_HOTEL_ID");
                if ((dataset == null) || (dataset.Tables["TABLE_HOTEL_ID"].Rows.Count < 1))
                {
                    MessageBox.Show("No Hotel information present for QueryId = " + queryId, "No Data Present", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    try
                    {
                        mySqlConnection.Close();
                    }
                    catch (Exception errConnClose)
                    {
                        MessageBox.Show("Error in opening mysql connection because : " + errConnClose.Message);
                    }
                    return;
                }
                saveFileDialogItinerary.Title = "HOTEL VOUCHER FILE NAME";
                if (saveFileDialogItinerary.ShowDialog() == DialogResult.OK)
                {
                    /* file selected */
                    Debug.WriteLine("OUT FILE SELECTED : " + saveFileDialogItinerary.FileName);
                }
                else
                {
                    Debug.WriteLine("File not selected thus returning");
                    try
                    {
                        mySqlConnection.Close();
                    }
                    catch (Exception errConnClose)
                    {
                        MessageBox.Show("Error in opening mysql connection because : " + errConnClose.Message);
                    }
                    return;
                }
                string imagePath = saveFileDialogItinerary.FileName + "logo.png";
                Properties.Resources.ExcursionHolidaysSmallLogo.Save(imagePath);

                Document document = new Document();
                document.Info.Title = "HOTEL VOUCHER FOR " + queryId;

                /* now cange the style of the document */
                MyPdfDocuments.DefineStyles(document);

                /* add section to document */
                Section section = document.AddSection();

                /* add hotel booking details.
                 * add different page for different hotel
                 */
                for (int pageNumber = 0; pageNumber < dataset.Tables["TABLE_HOTEL_ID"].Rows.Count; pageNumber++)
                {
                    mySqlQueryString = "SELECT * FROM `hotelbookinginfo` WHERE `queryid` = '" + queryId + "' AND idhotelinfo = " + dataset.Tables["TABLE_HOTEL_ID"].Rows[pageNumber]["idhotelinfo"].ToString();
                    mySqlDataAdapter = new MySqlDataAdapter(mySqlQueryString, mySqlConnection);
                    string tableNameHotelRates = "TABLE_HOTEL_ID_" + pageNumber.ToString();
                    mySqlDataAdapter.Fill(dataset, tableNameHotelRates);
                    mySqlQueryString = "SELECT `hoteladdress`, `hotelname` FROM `hotelinfo` WHERE `idhotelinfo` = " + dataset.Tables["TABLE_HOTEL_ID"].Rows[pageNumber]["idhotelinfo"].ToString();
                    mySqlDataAdapter = new MySqlDataAdapter(mySqlQueryString, mySqlConnection);
                    string tableNameHotelAddress = "HOTEL_ADDRESS_" + pageNumber.ToString();
                    mySqlDataAdapter.Fill(dataset, tableNameHotelAddress);
                    if (dataset.Tables[tableNameHotelRates].Rows.Count < 1)
                    {
                        continue;
                    }
                    if (pageNumber > 0)
                    {
                        section.AddPageBreak();
                    }
                    Paragraph paragraph = section.AddParagraph("HOTEL VOUCHER", "Heading1");
                    /* enter reference details in tabular form */
                    Table  table       = null;
                    Column column      = null;
                    int    columnCount = 0; // 1;
                    double columnWidth = 0; // (21.0 - 2.0) / columnCount;
                    Row    row         = null;
                    int    rowsCount   = 0;

                    table = section.AddTable();
                    table.Borders.Visible = true;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 3;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    for (int index = 0; index < columnCount; index++)
                    {
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                        column.Format.Alignment = ParagraphAlignment.Center;
                    }
                    row = table.AddRow();
                    rowsCount++;
                    paragraph = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Reference No", "Heading2");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText("Confirmed By", "Heading2");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Hotel Confirmation No", "Heading2");

                    row = table.AddRow();
                    rowsCount++;
                    paragraph = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText(queryId, "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[0]["confirmby"].ToString(), "Heading3");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[0]["idconfirmation"].ToString(), "Heading3");
                    /* Add contant for the table information */
                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    section.AddParagraph("\n", "Normal");
                    /* add hotel address and agency address in table */
                    table = section.AddTable();
                    table.Borders.Visible = false;
                    table.Borders.Width   = 0.75;
                    columnCount           = 2;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    column = table.AddColumn(Unit.FromCentimeter(1.2));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    columnCount++;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth - 1.2));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    row = table.AddRow();
                    rowsCount++;
                    paragraph = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Hotel Address Details", "Heading2");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText("Agency Address Details", "Heading2");
                    row.Cells[1].MergeRight = 1;

                    row = table.AddRow();
                    rowsCount++;
                    //MyPdfDocuments.WriteHdrContentParagraph(row.Cells[0], dataset.Tables[tableNameHotelAddress].Rows[0]["hotelname"].ToString(), dataset.Tables[tableNameHotelAddress].Rows[0]["hoteladdress"].ToString());
                    paragraph = row.Cells[0].AddParagraph();
                    paragraph.Format.RightIndent = "1.5cm";
                    paragraph.AddFormattedText(dataset.Tables[tableNameHotelAddress].Rows[0]["hotelname"].ToString() + "\n", "Heading3");
                    paragraph.AddFormattedText(dataset.Tables[tableNameHotelAddress].Rows[0]["hoteladdress"].ToString());

                    MigraDoc.DocumentObjectModel.Shapes.Image image = row.Cells[1].AddImage(imagePath);
                    image.Width = "1cm";
                    //image.Left = "-2.4cm";

                    MyPdfDocuments.WriteAgencyAddressDetails(row.Cells[2]);
                    /* Add contant for the table information */
                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    section.AddParagraph("\n", "Normal");

                    table = section.AddTable();
                    table.Borders.Visible = true;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 6;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    for (int index = 1; index < columnCount; index++)
                    {
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth + 0.45));
                        column.Format.Alignment = ParagraphAlignment.Left;
                    }
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth - (0.45 * 5)));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Lead Passenger Name", "Heading2");
                    row.Cells[0].MergeRight = 1;
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[0]["leadpassangername"].ToString(), "Heading3");
                    row.Cells[2].MergeRight = 3;
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Check In Date", "Heading2");
                    paragraph = row.Cells[1].AddParagraph();
                    //paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[0]["checkindate"].ToString(), "Heading3");
                    paragraph.AddFormattedText(DateTime.Parse(dataset.Tables[tableNameHotelRates].Rows[0]["checkindate"].ToString()).ToString("yyyy - MM - dd"), "Heading3");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Check Out Date", "Heading2");
                    paragraph = row.Cells[3].AddParagraph();
                    //paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[0]["checkoutdate"].ToString(), "Heading3");
                    paragraph.AddFormattedText(DateTime.Parse(dataset.Tables[tableNameHotelRates].Rows[0]["checkoutdate"].ToString()).ToString("yyyy - MM - dd"), "Heading3");
                    paragraph = row.Cells[4].AddParagraph();
                    paragraph.AddFormattedText("No of Nights", "Heading2");
                    paragraph = row.Cells[5].AddParagraph();
                    double noOfnights = (DateTime.Parse(dataset.Tables[tableNameHotelRates].Rows[0]["checkoutdate"].ToString()) -
                                         DateTime.Parse(dataset.Tables[tableNameHotelRates].Rows[0]["checkindate"].ToString())).TotalDays;
                    paragraph.AddFormattedText(Convert.ToInt32(noOfnights).ToString(), "Heading3");
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Pick Time", "Heading2");
                    paragraph = row.Cells[1].AddParagraph();
                    //paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[0]["checkindate"].ToString(), "Heading3");
                    paragraph.AddFormattedText(DateTime.Parse(dataset.Tables[tableNameHotelRates].Rows[0]["checkindate"].ToString()).ToString("HH:mm"), "Heading3");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Drop Time", "Heading2");
                    paragraph = row.Cells[3].AddParagraph();
                    //paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[0]["checkoutdate"].ToString(), "Heading3");
                    paragraph.AddFormattedText(DateTime.Parse(dataset.Tables[tableNameHotelRates].Rows[0]["checkoutdate"].ToString()).ToString("HH:mm"), "Heading3");
                    row.Cells[4].MergeRight = 1;


                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    section.AddParagraph("\n", "Normal");

                    table = section.AddTable();
                    table.Borders.Visible = true;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 6;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    column = table.AddColumn(Unit.FromCentimeter(1.5));
                    column.Format.Alignment = ParagraphAlignment.Center;
                    column = table.AddColumn(Unit.FromCentimeter(2 * columnWidth - 1.5));
                    column.Format.Alignment = ParagraphAlignment.Center;
                    for (int index = 2; index < columnCount; index++)
                    {
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                        column.Format.Alignment = ParagraphAlignment.Center;
                    }
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    //row.Shading.Color = Colors.LightSlateGray;
                    paragraph = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("S. No", "Heading2");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText("Room Type", "Heading2");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Meal Plan", "Heading2");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText("No of Rooms", "Heading2");
                    paragraph = row.Cells[4].AddParagraph();
                    paragraph.AddFormattedText("No of Guests", "Heading2");
                    paragraph = row.Cells[5].AddParagraph();
                    paragraph.AddFormattedText("Guests Type", "Heading2");
                    for (int roomCounter = 0; roomCounter < dataset.Tables[tableNameHotelRates].Rows.Count; roomCounter++)
                    {
                        row = table.AddRow();
                        rowsCount++;
                        row.VerticalAlignment = VerticalAlignment.Center;
                        paragraph             = row.Cells[0].AddParagraph();
                        paragraph.AddFormattedText((roomCounter + 1).ToString(), "Heading3");
                        paragraph = row.Cells[1].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[roomCounter]["roomtype"].ToString(), "Heading3");
                        paragraph = row.Cells[2].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[roomCounter]["mealplan"].ToString(), "Heading3");
                        paragraph = row.Cells[3].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countroom"].ToString(), "Heading3");
                        paragraph = row.Cells[4].AddParagraph();
                        int numberOfGuest = Convert.ToInt32(dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countadults"]) + Convert.ToInt32(dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countchildren"]);
                        paragraph.AddFormattedText(numberOfGuest.ToString(), "Heading3");
                        paragraph = row.Cells[5].AddParagraph();
                        string guestType = "Adults(" + dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countadults"].ToString() + ")";
                        if (Convert.ToInt32(dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countchildren"]) > 0)
                        {
                            guestType = guestType + "\nChildren(" + dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countchildren"].ToString() + ")";
                        }
                        if (Convert.ToInt32(dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countinfants"]) > 0)
                        {
                            guestType = guestType + "\nBabies(" + dataset.Tables[tableNameHotelRates].Rows[roomCounter]["countinfants"].ToString() + ")";
                        }
                        paragraph.AddFormattedText(guestType, "Heading3");
                    }

                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    section.AddParagraph("\n", "Normal");

                    MyPdfDocuments.WriteHotelVoucherStaticDetails(section);
                }

                PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
                try
                {
                    /* try to save file */
                    renderer.Document = document;
                    renderer.RenderDocument();
                    renderer.PdfDocument.Save(saveFileDialogItinerary.FileName);
                    renderer.PdfDocument.Close();
                    Process.Start(saveFileDialogItinerary.FileName);
                }
                catch (Exception errSave)
                {
                    MessageBox.Show("Error in saving file " + saveFileDialogItinerary.FileName + " because " + errSave.Message);
                    Debug.WriteLine("Error in saving file " + saveFileDialogItinerary.FileName + " because " + errSave.Message);
                    closeForm = false;
                }
                finally
                {
                    System.IO.File.Delete(imagePath);
                }
                /* now close connection */
                try
                {
                    mySqlConnection.Close();
                }
                catch (Exception errConnClose)
                {
                    MessageBox.Show("Error in opening mysql connection because : " + errConnClose.Message);
                }

                if (closeForm)
                {
                    Debug.WriteLine("File saved: " + saveFileDialogItinerary.FileName);
                }
                else
                {
                    return;
                }
            }

            if ((button == BtnPrintFlightTickets) || (button == BtnPrintBoth))
            {
                //MessageBox.Show("Button pressed = " + button.Text, "PRINTING FLIGHT TICKETS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                /* open connection */
                try
                {
                    mySqlConnection.Open();
                }
                catch (Exception errConnOpen)
                {
                    MessageBox.Show("Error in opening mysql connection because : " + errConnOpen.Message);
                    return;
                }

                /* now execute query to obtain data from hotel booking table
                 * and fill t in dataset
                 */
                string           mySqlQueryString = "SELECT DISTINCT `pnr` FROM `flightbookinginfo` WHERE `queryid` = '" + queryId + "' ORDER BY `pnr`";
                DataSet          dataset          = new DataSet();
                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlQueryString, mySqlConnection);
                mySqlDataAdapter.Fill(dataset, "TABLE_FLIGHT_PNR");
                if ((dataset == null) || (dataset.Tables["TABLE_FLIGHT_PNR"].Rows.Count < 1))
                {
                    MessageBox.Show("No Flight information present for QueryId = " + queryId, "No Data Present", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    try
                    {
                        mySqlConnection.Close();
                    }
                    catch (Exception errConnClose)
                    {
                        MessageBox.Show("Error in opening mysql connection because : " + errConnClose.Message);
                    }
                    return;
                }
                saveFileDialogItinerary.Title = "FLIGHT TICKET FILE NAME";
                if (saveFileDialogItinerary.ShowDialog() == DialogResult.OK)
                {
                    /* file selected */
                    Debug.WriteLine("OUT FILE SELECTED : " + saveFileDialogItinerary.FileName);
                }
                else
                {
                    Debug.WriteLine("File not selected thus returning");
                    try
                    {
                        mySqlConnection.Close();
                    }
                    catch (Exception errConnClose)
                    {
                        MessageBox.Show("Error in opening mysql connection because : " + errConnClose.Message);
                    }
                    return;
                }
                string imagePath = saveFileDialogItinerary.FileName + "logo.png";
                Properties.Resources.ExcursionHolidaysSmallLogo.Save(imagePath);

                Document document = new Document();
                document.Info.Title = "FLIGHT TICKET FOR " + queryId;

                /* Ask for printing price on ticket */
                bool         printPrice   = false;
                DialogResult dialogResult = MessageBox.Show("Flight price details needs to be printed in the flight voucher?", "PRINT PRICE ON VOUCHER", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    printPrice = true;
                }
                else
                {
                    Debug.WriteLine("Price not printing in the ticket");
                }

                /* now cange the style of the document */
                MyPdfDocuments.DefineStyles(document);

                /* add section to document */
                Section section = document.AddSection();
                for (int pageNumber = 0; pageNumber < dataset.Tables["TABLE_FLIGHT_PNR"].Rows.Count; pageNumber++)
                {
                    mySqlQueryString = "SELECT * FROM `flightbookinginfo` WHERE `queryid` = '" + queryId + "' AND `pnr` = '" + dataset.Tables["TABLE_FLIGHT_PNR"].Rows[pageNumber]["pnr"].ToString() + "'";
                    mySqlDataAdapter = new MySqlDataAdapter(mySqlQueryString, mySqlConnection);
                    string tableFlightInfo = "TABLE_FLIGHT_ID_" + pageNumber.ToString();
                    mySqlDataAdapter.Fill(dataset, tableFlightInfo);
                    if (dataset.Tables[tableFlightInfo].Rows.Count < 1)
                    {
                        continue;
                    }
                    if (pageNumber > 0)
                    {
                        section.AddPageBreak();
                    }
                    Paragraph paragraph;
                    Table     table       = null;
                    Column    column      = null;
                    int       columnCount = 0; // 1;
                    double    columnWidth = 0; // (21.0 - 2.0) / columnCount;
                    Row       row         = null;
                    int       rowsCount   = 0;

                    table = section.AddTable();
                    table.Borders.Visible = false;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 3;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    column = table.AddColumn(Unit.FromCentimeter(1.2));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    columnCount++;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth - 1.2));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                    column.Format.Alignment = ParagraphAlignment.Center;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                    column.Format.Alignment = ParagraphAlignment.Right;
                    row = table.AddRow();
                    rowsCount++;
                    MigraDoc.DocumentObjectModel.Shapes.Image image = row.Cells[0].AddImage(imagePath);
                    image.Width = "1cm";
                    MyPdfDocuments.WriteAgencyAddressDetails(row.Cells[1]);
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("E - Ticket\nTICKETED", "Heading2");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText("PNR: " + dataset.Tables[tableFlightInfo].Rows[0]["pnr"].ToString() +
                                               " \nIssued Date: " + DateTime.Parse(dataset.Tables[tableFlightInfo].Rows[0]["issuedate"].ToString()).ToString("ddd dd MM yyyy") +
                                               "", "Normal");

                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.None, 0, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    section.AddParagraph("\n", "Normal");

                    table = section.AddTable();
                    table.Borders.Visible = false;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 3;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                    column.Format.Alignment = ParagraphAlignment.Center;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                    column.Format.Alignment = ParagraphAlignment.Right;
                    row = table.AddRow();
                    rowsCount++;
                    row.Shading.Color = Colors.AliceBlue;
                    paragraph         = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Passanger Name", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText("Ticket Number", "Heading3");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Frequent flyer no.", "Heading3");
                    string[] persons = dataset.Tables[tableFlightInfo].Rows[0]["passangername"].ToString().Split(',');
                    string[] tickets = dataset.Tables[tableFlightInfo].Rows[0]["ticketnumber"].ToString().Split(',');
                    string[] ffys    = dataset.Tables[tableFlightInfo].Rows[0]["ffy"].ToString().Split(',');
                    for (int index = 0; index < persons.Length; index++)
                    {
                        if (string.Equals(persons[index], ""))
                        {
                            continue;
                        }
                        row = table.AddRow();
                        rowsCount++;
                        paragraph = row.Cells[0].AddParagraph();
                        paragraph.AddFormattedText(persons[index]);
                        paragraph = row.Cells[1].AddParagraph();
                        try
                        {
                            paragraph.AddFormattedText(tickets[index]);
                        }
                        catch (Exception errindex)
                        {
                            MessageBox.Show("Error : " + errindex.Message, "Error in index", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            paragraph.AddFormattedText("");
                        }
                        paragraph = row.Cells[2].AddParagraph();
                        try
                        {
                            paragraph.AddFormattedText(ffys[index]);
                        }
                        catch (Exception errindex)
                        {
                            MessageBox.Show("Error : " + errindex.Message, "Error in index", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            paragraph.AddFormattedText("-");
                        }
                    }

                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.None, 0.75, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    section.AddParagraph("\n", "Normal");

                    table = section.AddTable();
                    table.Borders.Visible = false;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 4;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    for (int index = 0; index < columnCount; index++)
                    {
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                        column.Format.Alignment = ParagraphAlignment.Left;
                    }
                    row = table.AddRow();
                    row.Shading.Color = Colors.AliceBlue;
                    rowsCount++;
                    paragraph = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Flight", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText("Departure", "Heading3");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Arrival", "Heading3");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText("Status", "Heading3");
                    for (int flightCounter = 0; flightCounter < dataset.Tables[tableFlightInfo].Rows.Count; flightCounter++)
                    {
                        row = table.AddRow();
                        rowsCount++;
                        paragraph = row.Cells[0].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableFlightInfo].Rows[flightCounter]["flightinfo"].ToString());
                        paragraph = row.Cells[1].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableFlightInfo].Rows[flightCounter]["departureinfo"].ToString());
                        paragraph = row.Cells[2].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableFlightInfo].Rows[flightCounter]["arrivalinfo"].ToString());
                        paragraph = row.Cells[3].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableFlightInfo].Rows[flightCounter]["statusinfo"].ToString());
                    }
                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.None, 0.75, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    section.AddParagraph("\n", "Normal");

                    table = section.AddTable();
                    table.Borders.Visible = false;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 4;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    for (int index = 0; index < 2; index++)
                    {
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth + 1.0));
                        column.Format.Alignment = ParagraphAlignment.Left;
                    }
                    for (int index = 2; index < 4; index++)
                    {
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth - 1.0));
                        column.Format.Alignment = ParagraphAlignment.Right;
                    }
                    if (printPrice)
                    {
                        row = table.AddRow();
                        rowsCount++;
                        row.Shading.Color = Colors.AliceBlue;
                        paragraph         = row.Cells[0].AddParagraph();
                        paragraph.AddFormattedText("Payment Details", "Heading3");
                        row.Cells[0].MergeRight = 3;
                    }
                    row = table.AddRow();
                    rowsCount++;
                    paragraph = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("This is an Electronic ticket. Please carry a positive identification for Check in.");
                    paragraph.Format.Font.Bold = true;
                    row.Cells[0].MergeRight    = 1;
                    if (printPrice)
                    {
                        int totalPrice = Convert.ToInt32(dataset.Tables[tableFlightInfo].Rows[0]["amountfare"]) +
                                         Convert.ToInt32(dataset.Tables[tableFlightInfo].Rows[0]["amountgst"]) +
                                         Convert.ToInt32(dataset.Tables[tableFlightInfo].Rows[0]["amountsurcharge"]);
                        row.Cells[0].MergeDown = 3;
                        paragraph = row.Cells[2].AddParagraph();
                        paragraph.AddFormattedText("Fare", "Normal");
                        paragraph = row.Cells[3].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableFlightInfo].Rows[0]["amountfare"].ToString(), "Normal");
                        row = table.AddRow();
                        rowsCount++;
                        paragraph = row.Cells[2].AddParagraph();
                        paragraph.AddFormattedText("K3/GST", "Normal");
                        paragraph = row.Cells[3].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableFlightInfo].Rows[0]["amountgst"].ToString(), "Normal");
                        row = table.AddRow();
                        rowsCount++;
                        paragraph = row.Cells[2].AddParagraph();
                        paragraph.AddFormattedText("Fee & Surcharge", "Normal");
                        paragraph = row.Cells[3].AddParagraph();
                        paragraph.AddFormattedText(dataset.Tables[tableFlightInfo].Rows[0]["amountsurcharge"].ToString(), "Normal");
                        row = table.AddRow();
                        rowsCount++;
                        paragraph = row.Cells[2].AddParagraph();
                        paragraph.AddFormattedText("Total Amount");
                        paragraph.Format.Font.Bold = true;
                        paragraph = row.Cells[3].AddParagraph();
                        paragraph.AddFormattedText(totalPrice.ToString());
                        paragraph.Format.Font.Bold = true;
                    }
                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.None, 0.5, Colors.SkyBlue);
                    rowsCount = columnCount = 0;
                    paragraph = section.AddParagraph("\n\n\n", "Normal");

                    /* ADD TERMINAL DETAILS HERE */
                    //paragraph = section.AddParagraph("<TERMINAL DETAILS TYPED HERE XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX>");
                    //paragraph.Format.Font.Color = Colors.Red;
                    table = section.AddTable();
                    table.Borders.Visible = false;
                    table.Borders.Width   = 0.75;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 1;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    row = table.AddRow();
                    rowsCount++;
                    MyPdfDocuments.WriteFlightVoucherNote(row.Cells[0]);

                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0, Colors.SkyBlue);
                }

                PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);

                try
                {
                    /* try to save file */
                    renderer.Document = document;
                    renderer.RenderDocument();
                    renderer.PdfDocument.Save(saveFileDialogItinerary.FileName);
                    renderer.PdfDocument.Close();
                    Process.Start(saveFileDialogItinerary.FileName);
                    Debug.WriteLine("File saved: " + saveFileDialogItinerary.FileName);
                }
                catch (Exception errSave)
                {
                    MessageBox.Show("Error in saving file " + saveFileDialogItinerary.FileName + " because " + errSave.Message);
                    Debug.WriteLine("Error in saving file " + saveFileDialogItinerary.FileName + " because " + errSave.Message);
                    closeForm = false;
                }
                finally
                {
                    System.IO.File.Delete(imagePath);
                }
                try
                {
                    mySqlConnection.Close();
                }
                catch (Exception errConnClose)
                {
                    MessageBox.Show("Error in opening mysql connection because : " + errConnClose.Message);
                }
            }
            if (closeForm)
            {
                Close();
            }
        }
        private void DataGrdVuAdminQueries_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DataGrdVuAdminQueries.Rows.Count > 0)
            {
                /* Open new Form of Working and pass queryId to the working */
                try
                {
                    Debug.WriteLine("Generating VOUCHERS FOR : \n" +
                                    DataGrdVuAdminQueries.SelectedRows[0].Cells["AssignedDate"].Value.ToString() + "\n" +
                                    DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "\n" +
                                    DataGrdVuAdminQueries.SelectedRows[0].Cells["Location"].Value.ToString() + "\n" +
                                    DataGrdVuAdminQueries.SelectedRows[0].Cells["fromDate"].Value.ToString() + "\n" +
                                    DataGrdVuAdminQueries.SelectedRows[0].Cells["toDate"].Value.ToString() + "\n");
                }
                catch (Exception errSelectedIndex)
                {
                    Debug.WriteLine("No rows selected because : " + errSelectedIndex.Message);
                    return;
                }

                if (string.Equals(frmArgStr, "VOUCHERS"))
                {
                    FrmVouchersOptionsPage newFrmPage = new FrmVouchersOptionsPage(DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString());
                    Hide();
                    newFrmPage.ShowDialog();
                    Show();
                }
                else if (string.Equals(frmArgStr, "FINALIZE OFFER"))
                {
                    FrmFinalizeQueryPage newFrmPage = new FrmFinalizeQueryPage(DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString());
                    Hide();
                    newFrmPage.ShowDialog();
                    Show();
                }
                else if (string.Equals(frmArgStr, "UPDATE ACCEPTED OFFER"))
                {
                    FrmFinalizeQueryPage newFrmPage = new FrmFinalizeQueryPage(DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString());
                    Hide();
                    newFrmPage.ShowDialog();
                    Show();
                }
                else if (string.Equals(frmArgStr, "VIEW ALL"))
                {
                    Debug.WriteLine("VIEW ALL QUERY SELECTED Thus nothing to do\n");
                }
                else if (string.Equals(frmArgStr, "PAYMENT UPDATE"))
                {
                    //MessageBox.Show("UPDATING PAYMENT FOR : "+ DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "\n");
                    FrmPaymentUpdatePage newFrmPage = new FrmPaymentUpdatePage(DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString());
                    Hide();
                    newFrmPage.ShowDialog();
                    Show();
                }
                else if (string.Equals(frmArgStr, "ITINERARY"))
                {
                    if (saveFileDialogItinerary.ShowDialog() == DialogResult.OK)
                    {
                        /* file selected */
                        Debug.WriteLine("OUT FILE SELECTED : " + saveFileDialogItinerary.FileName);
                    }
                    else
                    {
                        Debug.WriteLine("File not selected thus returning");
                        return;
                    }

                    /* get all information from database regarding this queryid*/
                    string mysqlQueryString = "SELECT * FROM `queries` WHERE `queryid` = '" + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "'";
                    try
                    {
                        frmMysqlConnection.Open();
                    }
                    catch (Exception errConnOpen)
                    {
                        MessageBox.Show("Error in opening mysql connection because : " + errConnOpen.Message);
                        return;
                    }

                    DataSet          queryDataset     = new DataSet();
                    MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mysqlQueryString, frmMysqlConnection);
                    mySqlDataAdapter.Fill(queryDataset, "SELECTED_QUERY");
                    mysqlQueryString = "SELECT * FROM `queryworkingday` WHERE `queryid` = '" + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "'";
                    mySqlDataAdapter.SelectCommand.CommandText = mysqlQueryString;
                    mySqlDataAdapter.Fill(queryDataset, "QUERY_DAY_INFO");
                    mysqlQueryString = "SELECT * FROM `queryworkinghotel` WHERE `queryid` = '" + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "'";
                    mySqlDataAdapter.SelectCommand.CommandText = mysqlQueryString;
                    mySqlDataAdapter.Fill(queryDataset, "QUERY_HOTEL_INFO");
                    mysqlQueryString = "SELECT * FROM `queryworkingflight` WHERE `queryid` = '" + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "'";
                    mySqlDataAdapter.SelectCommand.CommandText = mysqlQueryString;
                    mySqlDataAdapter.Fill(queryDataset, "QUERY_FLIGHT_INFO");
                    mysqlQueryString = "SELECT * FROM `queryworkingtravel` WHERE `queryid` = '" + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "'";
                    mySqlDataAdapter.SelectCommand.CommandText = mysqlQueryString;
                    mySqlDataAdapter.Fill(queryDataset, "QUERY_TRAVEL_INFO");
                    mysqlQueryString = "select `T1`.idhotelinfo, `T2`.hotelrating, `T1`.hotelcity , `T1`.hotelname, `T2`.roomtype " +
                                       "from `hotelinfo` as `T1` inner join `queryworkinghotel` as `T2` on `T1`.`idhotelinfo` = `T2`.`idhotelinfo` " +
                                       "WHERE `T2`.`queryid` = '" + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "' " +
                                       "order by `T1`.hotelcity";
                    mySqlDataAdapter.SelectCommand.CommandText = mysqlQueryString;
                    mySqlDataAdapter.Fill(queryDataset, "HOTEL_USED_INFO");

                    /* GENERATE PDF ITINERARY OF THE SELECTED QUERY */
                    double gstRate = Convert.ToDouble(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["gstrate"]);
                    gstRate = gstRate / 100;
                    double profitMargin = Convert.ToDouble(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["profitmargin"]);
                    profitMargin = profitMargin / 100;
                    double usdRate        = Convert.ToDouble(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["usdrate"]);
                    double multiplyFactor = (1.0 + gstRate) * (1.0 + profitMargin);
                    string currency       = "";
                    if (usdRate > 0)
                    {
                        currency = "(USD)";
                    }
                    else
                    {
                        currency = "(INR)";
                        usdRate  = 1;
                    }
                    multiplyFactor = multiplyFactor / usdRate;
                    Debug.WriteLine("GST RATE = " + gstRate.ToString() + " and PROFIT MARGIN = " + profitMargin.ToString() + " and USD rate = " + usdRate.ToString() + "AND MULTIPLY FACTOR = " + multiplyFactor.ToString());
                    Document document = new Document();
                    document.Info.Title  = "ITINERARY FOR " + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString();
                    document.Info.Author = "PANJADOTCOM";

                    /* now cange the style of the document */
                    MyPdfDocuments.DefineStyles(document);

                    /* add section to document */
                    Section section = document.AddSection();

                    /* now add image at the top of the page */
                    Table  table  = null;
                    Column column = null;
                    double columnWidth;
                    int    columnCount = 2;
                    Row    row         = null;
                    int    rowsCount   = 0;
                    int    personCount = 0;
                    string imagePath   = saveFileDialogItinerary.FileName + "logo.png";
                    Properties.Resources.ExcursionHolidaysLogo.Save(imagePath);
                    table = section.AddTable();
                    table.Borders.Visible = false;
                    table.Borders.Width   = 0.75;
                    column = table.AddColumn(Unit.FromCentimeter(3));
                    column.Format.Alignment = ParagraphAlignment.Left;
                    column = table.AddColumn(Unit.FromCentimeter(16));
                    column.Format.Alignment = ParagraphAlignment.Right;
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    MigraDoc.DocumentObjectModel.Shapes.Image image = row.Cells[0].AddImage(imagePath);
                    image.Width = "3cm";
                    MyPdfDocuments.WriteAgencyAddressDetails(row.Cells[1], 22, 10);
                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Transparent);
                    rowsCount = columnCount = 0;

                    /* now add summary of the tour in tabular form */
                    string fileContent;

                    fileContent = "SUMMARY";
                    Paragraph paragraph = section.AddParagraph(fileContent, "Heading2");

                    table = section.AddTable();
                    table.Borders.Visible = true;
                    table.Borders.Width   = 0.5;
                    table.Borders.Color   = Colors.SkyBlue;
                    columnCount           = 4;
                    columnWidth           = (21.0 - 2.0) / columnCount;
                    for (int index = 0; index < columnCount; index += 2)
                    {
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth - 1));
                        column.Format.Alignment = ParagraphAlignment.Left;
                        column = table.AddColumn(Unit.FromCentimeter(columnWidth + 1));
                        column.Format.Alignment = ParagraphAlignment.Left;
                    }
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Tour Reference", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString());
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Customer Name", "Heading3");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["name"].ToString());
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Tour Name", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["place"].ToString());
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("No of Days", "Heading3");
                    int noOfnights = Convert.ToInt32((DateTime.Parse(DataGrdVuAdminQueries.SelectedRows[0].Cells["toDate"].Value.ToString()) -
                                                      DateTime.Parse(DataGrdVuAdminQueries.SelectedRows[0].Cells["fromDate"].Value.ToString())).TotalDays);
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText(noOfnights.ToString() + " Nights and " + (noOfnights + 1).ToString() + " Days");
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("No of Person", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["adults"].ToString() + " Adult, " +
                                               queryDataset.Tables["SELECTED_QUERY"].Rows[0]["children"].ToString() + " Child and " +
                                               queryDataset.Tables["SELECTED_QUERY"].Rows[0]["babies"].ToString() + " Infant");
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("No of Room", "Heading3");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["roomcount"].ToString());
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Meals", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["meal"].ToString());
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Our Courtesy", "Heading3");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText("1 Water botel per day");
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Vehicle", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["vehicalcategory"].ToString());
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Train/Flight", "Heading3");
                    paragraph = row.Cells[3].AddParagraph();
                    if (queryDataset.Tables["QUERY_FLIGHT_INFO"].Rows.Count > 0)
                    {
                        paragraph.AddFormattedText("YES");
                    }
                    else
                    {
                        paragraph.AddFormattedText("NO");
                    }
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Arrive", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["arrivalcity"].ToString());
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Departure", "Heading3");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["departurecity"].ToString());
                    row = table.AddRow();
                    rowsCount++;
                    row.VerticalAlignment = VerticalAlignment.Center;
                    paragraph             = row.Cells[0].AddParagraph();
                    paragraph.AddFormattedText("Tour Start", "Heading3");
                    paragraph = row.Cells[1].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["fromdate"].ToString());
                    paragraph = row.Cells[2].AddParagraph();
                    paragraph.AddFormattedText("Tour End", "Heading3");
                    paragraph = row.Cells[3].AddParagraph();
                    paragraph.AddFormattedText(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["todate"].ToString());

                    /*row = table.AddRow();
                     * rowsCount++;
                     * row.VerticalAlignment = VerticalAlignment.Center;
                     * paragraph = row.Cells[0].AddParagraph();
                     * paragraph.AddFormattedText("Guide", "Heading3");
                     * paragraph = row.Cells[1].AddParagraph();
                     * paragraph.AddFormattedText("As per itinerary");
                     * paragraph = row.Cells[2].AddParagraph();
                     * paragraph.AddFormattedText("Validity", "Heading3");
                     * paragraph = row.Cells[3].AddParagraph();
                     * paragraph.AddFormattedText("One month before tour start date");*/
                    table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.5, Colors.SkyBlue);
                    rowsCount = columnCount = 0;

                    /* Add itinerary in the section below */
                    fileContent = "ITINERARY";
                    paragraph   = section.AddParagraph(fileContent, "Heading2");
                    double amount       = 0;
                    double monumentCost = 0;
                    /* add day wise narration */
                    string tourIncContent  = "";
                    string tourNoteContent = "";
                    foreach (DataRow item in queryDataset.Tables["QUERY_DAY_INFO"].Rows)
                    {
                        string hdr     = "Day " + item["dayno"].ToString() + ": " + item["narrationhdr"].ToString() + "";
                        string content = item["narration"].ToString() + "";
                        if (!string.Equals(item["tourinclusions"].ToString(), ""))
                        {
                            tourIncContent = item["tourinclusions"].ToString();
                        }
                        if (!string.Equals(item["notes"].ToString(), ""))
                        {
                            tourNoteContent = item["notes"].ToString();
                        }

                        MyPdfDocuments.WriteHdrContentParagraph(section, hdr, content);
                        amount       = amount + Convert.ToDouble(item["additionalcost"]);
                        amount       = amount + Convert.ToDouble(item["guidecost"]);
                        monumentCost = monumentCost + Convert.ToDouble(item["monumentcost"]);
                    }

                    foreach (DataRow item in queryDataset.Tables["QUERY_TRAVEL_INFO"].Rows)
                    {
                        amount = amount + (Convert.ToDouble(item["pricepercar"]) * Convert.ToDouble(item["carcount"]));
                    }

                    personCount = Convert.ToInt32(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["adults"].ToString())
                                  + Convert.ToInt32(queryDataset.Tables["SELECTED_QUERY"].Rows[0]["children"].ToString());

                    /* add gst rate and profitmargin in amount first. */

                    Int32 extraAmountPerPerson = Convert.ToInt32(amount / personCount);
                    extraAmountPerPerson = extraAmountPerPerson + Convert.ToInt32(monumentCost);

                    if (personCount == 1)
                    {
                        columnCount = 2;
                    }
                    else if (personCount == 2)
                    {
                        columnCount = 3;
                    }
                    else if (personCount > 2)
                    {
                        columnCount = 5;
                    }
                    else
                    {
                        columnCount = 0;
                    }
                    rowsCount = 0;
                    if (columnCount > 0)
                    {
                        paragraph             = section.AddParagraph("PER PERSON RATES " + currency, "Heading3");
                        columnWidth           = (21.0 - 2.0) / columnCount;
                        table                 = section.AddTable();
                        table.Borders.Visible = true;
                        table.Borders.Width   = 0.75;
                        for (int index = 0; index < columnCount; index++)
                        {
                            column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                            column.Format.Alignment = ParagraphAlignment.Center;
                        }
                        row = table.AddRow();
                        rowsCount++;
                        row.Shading.Color = Colors.RoyalBlue;
                        paragraph         = row.Cells[0].AddParagraph();
                        paragraph.AddFormattedText("CATEGORY", "CellHeading3");
                        paragraph = row.Cells[1].AddParagraph();
                        paragraph.AddFormattedText("SINGLE", "CellHeading3");
                        if (columnCount > 2)
                        {
                            paragraph = row.Cells[2].AddParagraph();
                            paragraph.AddFormattedText("DOUBLE SHARING", "CellHeading3");
                        }
                        if (columnCount > 3)
                        {
                            paragraph = row.Cells[3].AddParagraph();
                            paragraph.AddFormattedText("EXT ADULT/CWB", "CellHeading3");
                            paragraph = row.Cells[4].AddParagraph();
                            paragraph.AddFormattedText("CNB", "Heading3");
                        }

                        var hotelRateMatrix = new Int32[4, 4] {
                            { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }
                        };
                        foreach (DataRow item in queryDataset.Tables["QUERY_HOTEL_INFO"].Rows)
                        {
                            if (string.Equals(item["hotelrating"].ToString(), "STANDARD"))
                            {
                                hotelRateMatrix[0, 0]++;
                                hotelRateMatrix[0, 1] += Convert.ToInt32(item["singlebedprice"]);
                                hotelRateMatrix[0, 2] += (Convert.ToInt32(item["doublebedprice"]) / 2);
                                hotelRateMatrix[0, 3] += Convert.ToInt32(item["extrabedprice"]);
                            }
                            else if (string.Equals(item["hotelrating"].ToString(), "DELUXE"))
                            {
                                hotelRateMatrix[1, 0]++;
                                hotelRateMatrix[1, 1] += Convert.ToInt32(item["singlebedprice"]);
                                hotelRateMatrix[1, 2] += (Convert.ToInt32(item["doublebedprice"]) / 2);
                                hotelRateMatrix[1, 3] += Convert.ToInt32(item["extrabedprice"]);
                            }
                            else if (string.Equals(item["hotelrating"].ToString(), "SUPERIOR"))
                            {
                                hotelRateMatrix[2, 0]++;
                                hotelRateMatrix[2, 1] += Convert.ToInt32(item["singlebedprice"]);
                                hotelRateMatrix[2, 2] += (Convert.ToInt32(item["doublebedprice"]) / 2);
                                hotelRateMatrix[2, 3] += Convert.ToInt32(item["extrabedprice"]);
                            }
                            else if (string.Equals(item["hotelrating"].ToString(), "LUXORY"))
                            {
                                hotelRateMatrix[3, 0]++;
                                hotelRateMatrix[3, 1] += Convert.ToInt32(item["singlebedprice"]);
                                hotelRateMatrix[3, 2] += (Convert.ToInt32(item["doublebedprice"]) / 2);
                                hotelRateMatrix[3, 3] += Convert.ToInt32(item["extrabedprice"]);
                            }
                        }

                        for (int index = 0; index < 4; index++)
                        {
                            if (hotelRateMatrix[index, 0] > 0)
                            {
                                string hotelRating = "";
                                switch (index)
                                {
                                case 0:
                                    hotelRating = "STANDARD";
                                    break;

                                case 1:
                                    hotelRating = "DELUXE";
                                    break;

                                case 2:
                                    hotelRating = "SUPERIOR";
                                    break;

                                case 3:
                                    hotelRating = "LUXORY";
                                    break;

                                default:
                                    hotelRating = "UNKNOWN";
                                    break;
                                }
                                row = table.AddRow();
                                rowsCount++;

                                /*if ((rowsCount % 2) == 0)
                                 * {
                                 *  row.Shading.Color = Colors.PaleTurquoise;
                                 * }
                                 * else
                                 * {
                                 *  row.Shading.Color = Colors.PapayaWhip;
                                 * }*/
                                row.Cells[0].AddParagraph(hotelRating);
                                hotelRateMatrix[index, 1] += Convert.ToInt32(extraAmountPerPerson);
                                amount = Convert.ToDouble(hotelRateMatrix[index, 1]) * multiplyFactor;
                                row.Cells[1].AddParagraph(Convert.ToInt32(amount).ToString());
                                if (columnCount > 2)
                                {
                                    hotelRateMatrix[index, 2] += Convert.ToInt32(extraAmountPerPerson);
                                    amount = Convert.ToDouble(hotelRateMatrix[index, 2]) * multiplyFactor;
                                    row.Cells[2].AddParagraph(Convert.ToInt32(amount).ToString());
                                }
                                if (columnCount > 3)
                                {
                                    hotelRateMatrix[index, 3] += Convert.ToInt32(extraAmountPerPerson);
                                    amount = Convert.ToDouble(hotelRateMatrix[index, 3]) * multiplyFactor;
                                    row.Cells[3].AddParagraph(Convert.ToInt32(amount).ToString());
                                    amount = Convert.ToDouble(extraAmountPerPerson) * multiplyFactor;
                                    row.Cells[4].AddParagraph(Convert.ToInt32(amount).ToString());
                                }
                            }
                        }
                        table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Black);
                    }
                    /* add hotel rates in tabular form */
                    int hotelRowsCount = rowsCount;
                    /* now change cloumn count to rows count;*/
                    var hotelusedMatrix = new int[4, 4] {
                        { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }
                    };

                    foreach (DataRow item in queryDataset.Tables["HOTEL_USED_INFO"].Rows)
                    {
                        if (string.Equals(item["hotelrating"].ToString(), "STANDARD"))
                        {
                            hotelusedMatrix[0, 0]++;
                        }
                        else if (string.Equals(item["hotelrating"].ToString(), "DELUXE"))
                        {
                            hotelusedMatrix[1, 0]++;
                        }
                        else if (string.Equals(item["hotelrating"].ToString(), "SUPERIOR"))
                        {
                            hotelusedMatrix[2, 0]++;
                        }
                        else if (string.Equals(item["hotelrating"].ToString(), "LUXORY"))
                        {
                            hotelusedMatrix[3, 0]++;
                        }
                    }
                    if (hotelRowsCount > 0)
                    {
                        columnCount = hotelRowsCount;
                        rowsCount   = 0;
                        int       columnIndex = 0;
                        string    lastCity    = "";
                        DataTable dataTable   = new DataTable();
                        dataTable.Clear();
                        DataColumn dataColumn = dataTable.Columns.Add("ZERO");
                        DataRow    dataRow    = null;//dataTable.NewRow();
                        //dataRow["ZERO"] = "";
                        foreach (DataRow item in queryDataset.Tables["HOTEL_USED_INFO"].Rows)
                        {
                            if (rowsCount == 0)
                            {
                                paragraph   = section.AddParagraph("HOTEL INFORMATION", "Heading3");
                                columnWidth = (21.0 - 2.0) / columnCount;

                                table = section.AddTable();
                                table.Borders.Visible = true;
                                table.Borders.Width   = 0.75;
                                for (int index = 0; index < columnCount; index++)
                                {
                                    column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                                    column.Format.Alignment = ParagraphAlignment.Center;
                                }
                                row = table.AddRow();
                                rowsCount++;
                                columnIndex       = 1;
                                row.Shading.Color = Colors.RoyalBlue;
                                paragraph         = row.Cells[0].AddParagraph();
                                paragraph.AddFormattedText("HOTEL USED", "CellHeading3");
                                if (hotelusedMatrix[0, 0] > 0)
                                {
                                    paragraph = row.Cells[columnIndex].AddParagraph();
                                    paragraph.AddFormattedText("STANDARD", "CellHeading3");
                                    hotelusedMatrix[0, 1] = columnIndex;
                                    columnIndex++;
                                }
                                if (hotelusedMatrix[1, 0] > 0)
                                {
                                    paragraph = row.Cells[columnIndex].AddParagraph();
                                    paragraph.AddFormattedText("DELUXE", "CellHeading3");
                                    hotelusedMatrix[1, 1] = columnIndex;
                                    columnIndex++;
                                }
                                if (hotelusedMatrix[2, 0] > 0)
                                {
                                    paragraph = row.Cells[columnIndex].AddParagraph();
                                    paragraph.AddFormattedText("SUPERIOR", "CellHeading3");
                                    hotelusedMatrix[2, 1] = columnIndex;
                                    columnIndex++;
                                }
                                if (hotelusedMatrix[3, 0] > 0)
                                {
                                    paragraph = row.Cells[columnIndex].AddParagraph();
                                    paragraph.AddFormattedText("LUXORY", "CellHeading3");
                                    hotelusedMatrix[3, 1] = columnIndex;
                                }
                            }
                            if (!lastCity.Equals(item["hotelcity"].ToString()))
                            {
                                row = table.AddRow();
                                rowsCount++;
                                row.VerticalAlignment = VerticalAlignment.Center;
                                row.Cells[0].AddParagraph("IN " + item["hotelcity"].ToString());
                                lastCity = item["hotelcity"].ToString();
                                dataTable.Columns.Add(lastCity);
                            }
                            columnIndex = 0;
                            if (string.Equals(item["hotelrating"].ToString(), "STANDARD"))
                            {
                                columnIndex = hotelusedMatrix[0, 1];
                            }
                            else if (string.Equals(item["hotelrating"].ToString(), "DELUXE"))
                            {
                                columnIndex = hotelusedMatrix[1, 1];
                            }
                            else if (string.Equals(item["hotelrating"].ToString(), "SUPERIOR"))
                            {
                                columnIndex = hotelusedMatrix[2, 1];
                            }
                            else if (string.Equals(item["hotelrating"].ToString(), "LUXORY"))
                            {
                                columnIndex = hotelusedMatrix[3, 1];
                            }
                            bool addHotelEntry = true;
                            for (int index = 0; index < dataTable.Rows.Count; index++)
                            {
                                if (dataTable.Rows[index][lastCity].ToString().Equals(item["hotelname"].ToString() + "(" + item["roomtype"].ToString() + ")"))
                                {
                                    addHotelEntry = false;
                                    //MessageBox.Show(item["hotelname"].ToString() + "(" + item["roomtype"].ToString() + ") FOUND" );
                                    break;
                                }
                            }
                            if (addHotelEntry)
                            {
                                row.Cells[columnIndex].AddParagraph(item["hotelname"].ToString() + "(" + item["roomtype"].ToString() + ")");
                                dataRow           = dataTable.NewRow();
                                dataRow[lastCity] = item["hotelname"].ToString() + "(" + item["roomtype"].ToString() + ")";
                                dataTable.Rows.Add(dataRow);
                            }
                        }
                        if (rowsCount > 0)
                        {
                            table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Black);
                        }
                        dataTable.Clear();
                    }
                    /* add flight information in the itenary */
                    rowsCount = 0;
                    amount    = 0;
                    foreach (DataRow item in queryDataset.Tables["QUERY_FLIGHT_INFO"].Rows)
                    {
                        if (rowsCount == 0)
                        {
                            paragraph   = section.AddParagraph("AIR/TRAIN FARE " + currency + " PER PERSON EXTRA", "Heading3");
                            columnCount = 5;
                            columnWidth = (21.0 - 2.0) / columnCount;

                            table = section.AddTable();
                            table.Borders.Visible = true;
                            table.Borders.Width   = 0.75;
                            for (int index = 0; index < columnCount; index++)
                            {
                                column = table.AddColumn(Unit.FromCentimeter(columnWidth));
                                column.Format.Alignment = ParagraphAlignment.Center;
                            }
                            row = table.AddRow();
                            rowsCount++;
                            row.Shading.Color = Colors.RoyalBlue;
                            paragraph         = row.Cells[0].AddParagraph();
                            paragraph.AddFormattedText("DATE", "CellHeading3");
                            paragraph = row.Cells[1].AddParagraph();
                            paragraph.AddFormattedText("FROM", "CellHeading3");
                            paragraph = row.Cells[2].AddParagraph();
                            paragraph.AddFormattedText("TO", "CellHeading3");
                            paragraph = row.Cells[3].AddParagraph();
                            paragraph.AddFormattedText("FLIGHT/TRAIN", "CellHeading3");
                            paragraph = row.Cells[4].AddParagraph();
                            paragraph.AddFormattedText("AMOUNT", "CellHeading3");
                        }
                        row = table.AddRow();
                        rowsCount++;

                        /*if ((rowsCount % 2) == 0)
                         * {
                         *  row.Shading.Color = Colors.PaleTurquoise;
                         * }
                         * else
                         * {
                         *  row.Shading.Color = Colors.PapayaWhip;
                         * }*/
                        row.Cells[0].AddParagraph(item["date"].ToString());
                        row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
                        row.Cells[1].AddParagraph(item["fromcity"].ToString().ToUpper());
                        row.Cells[1].VerticalAlignment = VerticalAlignment.Center;
                        row.Cells[2].AddParagraph(item["tocity"].ToString().ToUpper());
                        row.Cells[2].VerticalAlignment = VerticalAlignment.Center;
                        row.Cells[3].AddParagraph(item["flightnumber"].ToString().ToUpper());
                        row.Cells[3].VerticalAlignment = VerticalAlignment.Center;
                        amount = amount + Convert.ToDouble(item["rateperticket"].ToString());
                    }
                    if (rowsCount > 0)
                    {
                        table.Rows[1].Cells[4].MergeDown = rowsCount - 2;
                        amount = amount / usdRate;
                        table.Rows[1].Cells[4].AddParagraph(Convert.ToInt32(amount).ToString());
                        table.Rows[1].Cells[4].Shading.Color     = Colors.WhiteSmoke;
                        table.Rows[1].Cells[4].VerticalAlignment = VerticalAlignment.Center;
                        table.SetEdge(0, 0, columnCount, rowsCount, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Black);
                    }

                    /* add notes in the document */
                    MyPdfDocuments.WriteItineraryLastStaticDetails(section, tourIncContent, tourNoteContent);


                    //////////////////////////////////////////////////////////////////////////////////////////////////
                    PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);

                    try
                    {
                        /* try to save file */
                        renderer.Document = document;
                        renderer.RenderDocument();
                        renderer.PdfDocument.Save(saveFileDialogItinerary.FileName);
                        renderer.PdfDocument.Close();
                        Process.Start(saveFileDialogItinerary.FileName);
                    }
                    catch (Exception errSave)
                    {
                        MessageBox.Show("Error in saving file " + saveFileDialogItinerary.FileName + " because " + errSave.Message);
                        Debug.WriteLine("Error in saving file " + saveFileDialogItinerary.FileName + " because " + errSave.Message);
                    }
                    finally
                    {
                        System.IO.File.Delete(imagePath);
                    }

                    /*/////////////////////////////PDF OF ITENARY CREATED AND SAVED//////////////////////////////////////////////////*/
                    MySqlCommand     mySqlCommand     = frmMysqlConnection.CreateCommand();
                    MySqlTransaction mySqlTransaction = frmMysqlConnection.BeginTransaction();
                    mySqlCommand.Connection  = frmMysqlConnection;
                    mySqlCommand.Transaction = mySqlTransaction;
                    mySqlCommand.CommandType = CommandType.Text;
                    mySqlCommand.CommandText = "UPDATE `queries` SET " +
                                               "`querylastupdatetime` = NOW(), " +
                                               "`querycurrentstate` = " + Properties.Resources.queryStageMailed + " " +
                                               "WHERE " +
                                               "queryid = '" + DataGrdVuAdminQueries.SelectedRows[0].Cells["QueryId"].Value.ToString() + "'";
                    mySqlCommand.Prepare();

                    try
                    {
                        mySqlCommand.ExecuteNonQuery();
                        mySqlTransaction.Commit();
                    }
                    catch (Exception errquery)
                    {
                        MessageBox.Show("Error while executing insert query because:\n" + errquery.Message);
                    }

                    try
                    {
                        frmMysqlConnection.Close();
                    }
                    catch (Exception errConnClose)
                    {
                        MessageBox.Show("Error in Closing mysql connection because : " + errConnClose.Message);
                    }
                }
                else
                {
                    MessageBox.Show("Wrong argument passed", "Wrong argument", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("Please load Queries First", "Load Queries", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Example #18
0
        private bool showPDF()
        {
            try
            {
                //Create a PDF document
                Document doc = new Document();


                //Create a section inside the document
                Section template = doc.AddSection();

                template.PageSetup.RightMargin    = 30;
                template.PageSetup.LeftMargin     = 30;
                template.PageSetup.FooterDistance = new Unit(0, UnitType.Point);
                template.PageSetup.DifferentFirstPageHeaderFooter = true;

                //Headers
                MigraDoc.DocumentObjectModel.Shapes.Image logo = template.Headers.FirstPage.AddImage(config.LogoPath);
                logo.ScaleWidth  = 0.5;
                logo.ScaleHeight = 0.5;

                template.AddParagraph();
                template.AddParagraph();
                template.AddParagraph();

                template.Headers.FirstPage.AddParagraph();
                Paragraph titre = template.Headers.FirstPage.AddParagraph(TitleSet.Text);
                titre.Format.Font.Bold = true;
                titre.Format.Alignment = ParagraphAlignment.Center;
                titre.Format.Font.Size = new Unit(16, UnitType.Point);

                template.AddParagraph();
                template.AddParagraph();
                template.AddParagraph();

                //Excel Table
                CreateTable(ExcelFilePath.Text, template, GetCheckedItems());

                //Footers
                DateTime input       = DateTime.Today;
                int      deltaMonday = System.DayOfWeek.Monday - input.DayOfWeek;
                DateTime monday      = input.AddDays(deltaMonday);
                int      deltaSunday = System.DayOfWeek.Sunday - input.DayOfWeek;
                DateTime sunday      = input.AddDays(deltaSunday);
                string   validText   = "";
                if (config.IsValidityDateInFooter)
                {
                    validText = "Valide du " + monday.ToShortDateString() + " au " + sunday.ToShortDateString() + "\n\n";
                }
                string contactText = validText + config.Footer;
                template.AddParagraph();
                template.AddParagraph();
                template.AddParagraph(contactText);

                PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false);
                pdfRenderer.Document = doc;
                pdfRenderer.RenderDocument();
                pdfFileName = Environment.CurrentDirectory + "\\" + TitleSet.Text + ".pdf";
                pdfRenderer.PdfDocument.Save(pdfFileName);
                var p = Process.Start(pdfFileName);
                p.WaitForExit();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Un problème est survenu durant la création du fichier PDF\n" + ex.Message);
                return(false);
            }
            return(true);
        }
Example #19
0
        public Document CreateTreningDOC()
        {
            Section section = document.AddSection();


            PageSettings(section);

            Paragraph p = section.AddParagraph();

            /*  int[] imp = wyliczimpy(vugraph1.Vu_ContractList_Open, vugraph1.Vu_ContractList_Closed);
             *
             * int impsns = 0, impsew = 0;
             * for (int i = 0; i < Ustawienia.ilosc_rozdan; i++)
             * {
             *    if (imp[i] > 0)
             *        impsns += imp[i];
             *    else
             *        impsew -= imp[i];
             * }
             * p.AddFormattedText("Rezultat segmentu w meczu orginalnym " + vugraph.team1Name + " - " + vugraph.team2Name + " " + impsns.ToString() + ":" + impsew.ToString(), font_tytuly);
             * p.AddLineBreak();
             * p.AddLineBreak();
             * p.AddFormattedText("Poniżej porównanie meczu treningowego do dwóch pozostałych stołów", font_normal);
             * p.AddLineBreak();
             * p.AddLineBreak();
             */
            MakeTable33(vugraph1);
            MakeTable33(vugraph2);

            //   int[,,] lewy;

            if (Ustawienia.deepfin)
            {
                lewy = InfoBridge.wylicz_DF(vugraph1.rozklady);
            }
            for (int i = 0; i < Ustawienia.ilosc_rozdan; i++)
            {
                // if (i != 0)
                document.AddSection();
                CreateBoard(i, vugraph1.rozklady[i]);
                Paragraph pbreak = document.LastSection.AddParagraph();
                pbreak.AddLineBreak();
                pbreak.AddLineBreak();
                pbreak.AddFormattedText("Liczba lew do wzięcia : ", font_normal);
                pbreak.AddLineBreak();
                pbreak.AddLineBreak();
                if (Ustawienia.deepfin)
                {
                    CreateDF(i);
                }


                CreateBidding(i);


                //      WriteLineKontrakt(game.ContractList[i], vugraph.Vu_ContractList_Open[i], vugraph.Vu_ContractList_Closed[i]);

                // WriteCommentTitle();
            }

            MigraDoc.DocumentObjectModel.Shapes.Image reklama = new MigraDoc.DocumentObjectModel.Shapes.Image("images\\reklama.png");

            reklama.Height = Unit.FromCentimeter(8.0);
            reklama.Width  = Unit.FromCentimeter(12.0);

            reklama.WrapFormat.DistanceTop  = Unit.FromCentimeter(1.0);
            reklama.WrapFormat.DistanceLeft = Unit.FromCentimeter(2.0);

            document.LastSection.Add(reklama);
            document.UseCmykColor = true;

            document.Info.Author = "Maciej Bielawski";


            string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document);

            /*
             * RtfDocumentRenderer renderer = new RtfDocumentRenderer();
             *     renderer.Render(document,"Test.doc", null);
             *
             * Process.Start("Test.doc");*/

            return(document);
        }
        public void MakeGiftCert(int itemID)
        {
            try
            {
                GiftCertificateInfo item;
                //load the item
                GiftCertificateController controller = new GiftCertificateController();
                item = controller.GetGiftCert(itemId);

                string CertAmountWords    = "";
                string MailToAddressField = "";
                string CertAmountNumber   = "";

                if (item != null)
                {
                    if (item.PaypalPaymentState.ToString().Length == 0)
                    {
                        Response.Redirect(Globals.NavigateURL("Access Denied"), true);
                    }

                    TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

                    CertAmountWords  = textInfo.ToTitleCase(NumberToWords(Int32.Parse(item.CertAmount.ToString())).ToString()).ToString() + " Dollars" + Environment.NewLine;
                    CertAmountNumber = "$" + String.Format("{0:f2}", item.CertAmount).ToString();

                    MailToAddressField = item.MailTo.ToString() + Environment.NewLine
                                         + item.MailToAddress.ToString() + Environment.NewLine
                                         + item.MailToCity.ToString() + ", " + item.MailToState.ToString() + " " + item.MailToZip.ToString();

                    _CertNotes = item.Notes.ToString();
                }


                string myPortalName = this.PortalSettings.PortalName.ToString();



                Document document = new Document();
                document.Info.Author   = "Joseph Aucoin";
                document.Info.Keywords = "Gift Certificate";
                document.Info.Title    = myPortalName.ToString() + " Gift Certificate";

                // Get the A4 page size
                MigraDoc.DocumentObjectModel.Unit width, height;
                PageSetup.GetPageSize(PageFormat.Letter, out width, out height);



                // Add a section to the document and configure it such that it will be in the centre
                // of the page
                Section section = document.AddSection();
                section.PageSetup.PageHeight  = height;
                section.PageSetup.PageWidth   = width;
                section.PageSetup.LeftMargin  = 20;
                section.PageSetup.RightMargin = 10;
                section.PageSetup.TopMargin   = 20; // height / 2;



                //++++++++++++++++++++++++++++++
                //++++++++++++++++++++++++++++++
                //++++++++++++++++++++++++++++++
                // ADD LOGO
                string myLogo = PortalSettings.HomeDirectoryMapPath + _CertLogo.ToString(); // "Images\\Chapins-Logo.png";
                MigraDoc.DocumentObjectModel.Shapes.Image image = section.Headers.Primary.AddImage(myLogo.ToString());

                image.LockAspectRatio    = true;
                image.RelativeVertical   = MigraDoc.DocumentObjectModel.Shapes.RelativeVertical.Line;
                image.RelativeHorizontal = MigraDoc.DocumentObjectModel.Shapes.RelativeHorizontal.Margin;
                image.Top              = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Top;
                image.Left             = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Right;
                image.WrapFormat.Style = MigraDoc.DocumentObjectModel.Shapes.WrapStyle.Through;

                MigraDoc.DocumentObjectModel.Tables.Table HeaderTable = new MigraDoc.DocumentObjectModel.Tables.Table();
                HeaderTable.Borders.Width         = 0; // Default to show borders 1 pixel wide Column
                HeaderTable.LeftPadding           = 10;
                HeaderTable.RightPadding          = 10;
                HeaderTable.Borders.Left.Visible  = false;
                HeaderTable.Borders.Right.Visible = false;


                // Add 1 columns
                float myColumnWidth = ((section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin) / 2);   // ((width / 2) - 10);
                MigraDoc.DocumentObjectModel.Tables.Column column0 = HeaderTable.AddColumn(myColumnWidth);

                MigraDoc.DocumentObjectModel.Tables.Row row1 = HeaderTable.AddRow();
                row1.Cells[0].Elements.AddParagraph(_CertReturnAddress.ToString());
                row1.Cells[0].Format.Alignment = ParagraphAlignment.Left;


                section.Add(HeaderTable);

                /// SPACING
                MigraDoc.DocumentObjectModel.Paragraph paragraph = section.AddParagraph();
                paragraph.Format.LineSpacingRule = MigraDoc.DocumentObjectModel.LineSpacingRule.Exactly;
                paragraph.Format.LineSpacing     = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(30.0);

                //   section.Add(paragraph);

                //++++++++++++++++++++++++++++++
                // ADD ANOTHER TABLE FOR MAIL TO ADDRESS
                // Create a table so that we can draw the horizontal lines
                MigraDoc.DocumentObjectModel.Tables.Table tableMailToAddress = new MigraDoc.DocumentObjectModel.Tables.Table();
                tableMailToAddress.Borders.Width = 0; // Default to show borders 1 pixel wide Column
                tableMailToAddress.LeftPadding   = 20;
                tableMailToAddress.RightPadding  = 10;

                //  float myColumnWidth100percent = (width - 10);
                var column = tableMailToAddress.AddColumn((section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin));

                double fontHeight = 20;
                Font   font       = new Font("Times New Roman", fontHeight);

                // Add a row with a single cell for the first line
                MigraDoc.DocumentObjectModel.Tables.Row  row  = tableMailToAddress.AddRow();
                MigraDoc.DocumentObjectModel.Tables.Cell cell = row.Cells[0];


                cell = row.Cells[0];

                cell.Format.Font.Color = Colors.Black;
                cell.Format.Alignment  = ParagraphAlignment.Left;
                cell.Format.Font.ApplyFont(font);

                cell.AddParagraph(MailToAddressField.ToString());

                section.Add(tableMailToAddress);

                // ADD SPACER+++++++++++++++++++++++++++++++++++++++
                MigraDoc.DocumentObjectModel.Paragraph paragraph1 = section.AddParagraph();
                paragraph1.Format.LineSpacingRule = MigraDoc.DocumentObjectModel.LineSpacingRule.Exactly;
                paragraph1.Format.LineSpacing     = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(20.0);



                // ADD ANOTHER TABLE FOR CERT
                // Create a table so that we can draw the horizontal lines
                MigraDoc.DocumentObjectModel.Tables.Table tableCert = new MigraDoc.DocumentObjectModel.Tables.Table();
                tableCert.Borders.Width         = 0; // Default to show borders 1 pixel wide Column
                tableCert.LeftPadding           = 10;
                tableCert.RightPadding          = 10;
                tableCert.Borders.Right.Visible = true;

                //  float myColumnWidth100percent = (width - 10);
                float sectionWidth = section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin;
                float columnWidth  = sectionWidth;


                var columnCert = tableCert.AddColumn(columnWidth);
                columnCert.Format.Alignment = ParagraphAlignment.Center;

                double fontHeightCert = 30;
                Font   fontCert       = new Font("Times New Roman", fontHeightCert);

                // Add a row with a single cell for the first line
                MigraDoc.DocumentObjectModel.Tables.Row  rowCert  = tableCert.AddRow();
                MigraDoc.DocumentObjectModel.Tables.Cell cellCert = rowCert.Cells[0];

                cellCert.Format.Font.Color = Colors.Black;
                cellCert.Format.Font.ApplyFont(fontCert);
                cellCert.Borders.Left.Visible   = false;
                cellCert.Borders.Right.Visible  = false;
                cellCert.Borders.Bottom.Visible = false;

                cellCert.AddParagraph(_CertBannerText.ToString());

                // Add a row with a single cell for the second line
                rowCert  = tableCert.AddRow();
                cellCert = rowCert.Cells[0];

                cellCert.Format.Font.Color = Colors.Black;
                cellCert.Format.Alignment  = ParagraphAlignment.Center;
                cellCert.Format.Font.ApplyFont(fontCert);
                cellCert.Borders.Left.Visible  = false;
                cellCert.Borders.Right.Visible = false;
                cellCert.Borders.Top.Visible   = false;

                cellCert.AddParagraph(CertAmountWords.ToString());

                // 3RD LINE
                // Add a row with a single cell for the third line
                rowCert  = tableCert.AddRow();
                cellCert = rowCert.Cells[0];


                Font fontCertDetails = new Font("Times New Roman", 20);
                cellCert.Format.Font.Color = Colors.Black;

                cellCert.Format.Alignment = ParagraphAlignment.Left;
                cellCert.Format.Font.ApplyFont(fontCertDetails);
                cellCert.Borders.Left.Visible  = false;
                cellCert.Borders.Right.Visible = false;
                cellCert.Borders.Top.Visible   = false;

                cellCert.Format.SpaceBefore = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(10.0);
                cellCert.Format.LeftIndent  = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(15.0);
                cellCert.AddParagraph("Date:" + item.CreatedDate.ToShortDateString() + Environment.NewLine + "Presented to: " + item.ToName.ToString() + Environment.NewLine +
                                      "From: " + item.FromName.ToString() + Environment.NewLine + "Amount: " + CertAmountNumber.ToString());


////////////////////////////////
                // 4th LINE
                // Add a row with a single cell for the forth line
                rowCert  = tableCert.AddRow();
                cellCert = rowCert.Cells[0];


                Font fontCertSignature = new Font("Arial", 12);
                cellCert.Format.Font.Color = Colors.Black;

                cellCert.Format.Alignment = ParagraphAlignment.Left;
                cellCert.Format.Font.ApplyFont(fontCertSignature);
                cellCert.Borders.Left.Visible  = false;
                cellCert.Borders.Right.Visible = false;
                cellCert.Borders.Top.Visible   = false;

                cellCert.Format.SpaceBefore = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(10.0);
                cellCert.Format.LeftIndent  = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(15.0);
                cellCert.AddParagraph("Authorized Signature: __________________________________________________");

                ////////////////////////////////
                // 5th LINE
                // Add a row with a single cell for the fifth line
                rowCert  = tableCert.AddRow();
                cellCert = rowCert.Cells[0];


                Font fontCertInvoiceNumber = new Font("Arial", 10);
                cellCert.Format.Font.Color = Colors.Black;

                cellCert.Format.Alignment = ParagraphAlignment.Center;
                cellCert.Format.Font.ApplyFont(fontCertInvoiceNumber);
                cellCert.Borders.Left.Visible  = false;
                cellCert.Borders.Right.Visible = false;
                cellCert.Borders.Top.Visible   = false;
                //      cellCert.Format.AddTabStop("16cm", TabAlignment.Right);
                cellCert.Format.SpaceBefore = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(3.0);
                //cellCert.Format.LeftIndent = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(15.0);
                cellCert.AddParagraph("Certificate Number 00" + item.ItemId.ToString());

                document.LastSection.Add(tableCert);


                if (item.Notes.ToString().Trim().Length > 0)
                {
                    //+++++++++ ADD PARAGRAPH FOR BUYER NOTES
                    MigraDoc.DocumentObjectModel.Paragraph paragraphFooter = section.AddParagraph();
                    paragraphFooter.Format.LineSpacingRule = MigraDoc.DocumentObjectModel.LineSpacingRule.Exactly;
                    paragraphFooter.Format.LineSpacing     = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(8.0);
                    paragraphFooter.Format.SpaceBefore     = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(10.0);
                    paragraphFooter.AddText("NOTES:" + Environment.NewLine + _CertNotes.ToString());
                }



                Paragraph footerText = new Paragraph();
                footerText.Format.Alignment = ParagraphAlignment.Center;
                footerText.AddText(_CertFooterText.ToString());

                section.Footers.Primary.Add(footerText);



                // Create a renderer
                PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer();

                // Associate the MigraDoc document with a renderer
                pdfRenderer.Document = document;

                // Layout and render document to PDF
                pdfRenderer.RenderDocument();


                string pdfFilename = PortalSettings.HomeDirectoryMapPath + _PdfFilesFolder.ToString() + "Cert" + itemId.ToString() + ".pdf";

                if (File.Exists(pdfFilename))
                {
                    File.Delete(pdfFilename);
                }

                pdfRenderer.PdfDocument.Save(pdfFilename);



                bool watermarkIsNeeded = false;
                if (_CertWatermark.ToString().Trim().Length > 1)
                {
                    watermarkIsNeeded = true;
                }

                if (watermarkIsNeeded)
                {
                    PdfDocument pdfIn  = PdfReader.Open(pdfFilename, PdfDocumentOpenMode.Import);
                    PdfDocument pdfOut = new PdfDocument();

                    for (int i = 0; i < pdfIn.PageCount; i++)
                    {
                        PdfPage pg = pdfIn.Pages[i];
                        pg = pdfOut.AddPage(pg);
                        // WATERMARK TEXT
                        string draftFlagStr = _CertWatermark.ToString();

                        // Get an XGraphics object for drawing beneath the existing content
                        XGraphics gfx = XGraphics.FromPdfPage(pg, XGraphicsPdfPageOptions.Prepend);

                        // Get the size (in point) of the text
                        XFont fontWM = new XFont("Verdana", 62, XFontStyle.Bold);
                        XSize size   = gfx.MeasureString(draftFlagStr, fontWM);

                        // Define a rotation transformation at the center of the page
                        gfx.TranslateTransform(pg.Width / 2, pg.Height / 2);
                        gfx.RotateTransform(-Math.Atan(pg.Height / pg.Width) * 180 / Math.PI);
                        gfx.TranslateTransform(-pg.Width / 2, -pg.Height / 2);

                        // Create a string format
                        XStringFormat format = new XStringFormat();
                        format.Alignment     = XStringAlignment.Near;
                        format.LineAlignment = XLineAlignment.Near;

                        // Create a dimmed red brush
                        XBrush brush = new XSolidBrush(XColor.FromArgb(32, 0, 0, 255));

                        // Draw the string
                        gfx.DrawString(draftFlagStr, fontWM, brush,
                                       new XPoint((pg.Width - size.Width) / 2, (pg.Height - size.Height) / 2),
                                       format);
                    }
                    pdfOut.Save(pdfFilename);
                }



                // Save and show the document
                //  pdfRenderer.PdfDocument.Save("TestDocument.pdf");
                Process.Start("explorer.exe", pdfFilename);


                HyperLinkPDF.Visible     = true;
                HyperLinkPDF.NavigateUrl = PortalSettings.HomeDirectory + _PdfFilesFolder.ToString() + "Cert" + itemId.ToString() + ".pdf";
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
Example #21
0
        public Document CreateTreningDOC()
        {
            Section section = document.AddSection();


            PageSettings(section);

            Paragraph p = section.AddParagraph();

            MakeTable11();

            if (Ustawienia.deepfin)
            {
                lewy = InfoBridge.wylicz_DF(game.rozklady);
            }

            for (int i = 1; i < Ustawienia.ilosc_rozdan + 1; i++)
            {
                // if (i != 0)
                document.AddSection();
                CreateBoard(i - 1, game.rozklady[i]);
                Paragraph pbreak = document.LastSection.AddParagraph();
                pbreak.AddLineBreak();
                pbreak.AddLineBreak();
                pbreak.AddFormattedText("Liczba lew do wzięcia : ", font_normal);
                pbreak.AddLineBreak();
                pbreak.AddLineBreak();
                if (Ustawienia.deepfin)
                {
                    CreateDF(i);
                }


                CreateBidding(i - 1);


                //       WriteLineKontrakt(game.ContractList[i], vugraph.Vu_ContractList_Open[i], vugraph.Vu_ContractList_Closed[i]);

                WriteCommentTitle();
            }

            MigraDoc.DocumentObjectModel.Shapes.Image reklama = new MigraDoc.DocumentObjectModel.Shapes.Image("images\\reklama.png");

            reklama.Height = Unit.FromCentimeter(8.0);
            reklama.Width  = Unit.FromCentimeter(12.0);

            reklama.WrapFormat.DistanceTop  = Unit.FromCentimeter(1.0);
            reklama.WrapFormat.DistanceLeft = Unit.FromCentimeter(2.0);

            document.LastSection.Add(reklama);
            document.UseCmykColor = true;

            document.Info.Author = "Maciej Bielawski";


            string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document);

            /*
             * RtfDocumentRenderer renderer = new RtfDocumentRenderer();
             *     renderer.Render(document,"Test.doc", null);
             *
             * Process.Start("Test.doc");*/

            return(document);
        }
Example #22
0
        /// <summary>
        /// Creates an absolutely minimalistic document.
        /// </summary>
        static Document CreateDocument()
        {
            // Create a new MigraDoc document
            Document document = new Document();

            document.DefaultPageSetup.PageHeight = Unit.FromCentimeter(1.6);
            document.DefaultPageSetup.PageWidth  = Unit.FromCentimeter(10);

            document.DefaultPageSetup.TopMargin    = Unit.FromCentimeter(0.1);
            document.DefaultPageSetup.RightMargin  = Unit.FromCentimeter(0.2);
            document.DefaultPageSetup.BottomMargin = Unit.FromCentimeter(0.1);
            document.DefaultPageSetup.LeftMargin   = Unit.FromCentimeter(0.2);

            //Add styling
            Styles.DefineStyles(document);

            // Add a section to the document
            Section section = document.AddSection();

            string labelText = string.Format("Testing 123 {0} \u26c4 \u26fd {0} \u260e \u0040", Environment.NewLine);

            Table table = new Table();

            table.Borders.Width = 0.75;

            for (int i = 0; i < 3; i++)
            {
                Column column = table.AddColumn("1.2cm");
                column.Format.Alignment = ParagraphAlignment.Center;
                Column column2 = table.AddColumn("2.1cm");
                column2.Format.Alignment = ParagraphAlignment.Center;
            }

            Row row = table.AddRow();

            for (int i = 0; i < 3; i++)
            {
                int tmp = i * 2;

                //circle image
                //Image image = new Image("../../circle-outline-512.png");
                //image.WrapFormat.Style = WrapStyle.Through;
                //image.ScaleHeight = 1.7;
                //image.LockAspectRatio = true;
                //image.Width = "0.7cm";

                //row.Cells[tmp].Add(image);

                //icon image
                MigraDoc.DocumentObjectModel.Shapes.Image iconImage = new MigraDoc.DocumentObjectModel.Shapes.Image("../../1352357958_large.png");
                iconImage.ScaleHeight     = 0.3;
                iconImage.LockAspectRatio = true;
                //iconImage.Resolution = 200;
                //row.Cells[tmp].Add(iconImage);

                row.Cells[tmp].VerticalAlignment = VerticalAlignment.Center;
                row.Cells[tmp].Format.Alignment  = ParagraphAlignment.Center;

                Paragraph imgParagraph = new Paragraph();
                //imgParagraph.Add(image);
                imgParagraph.Add(iconImage);

                row.Cells[tmp].Add(imgParagraph);

                //label text
                row.Cells[tmp + 1].AddParagraph(labelText);
                row.Cells[tmp + 1].VerticalAlignment = VerticalAlignment.Center;
            }

            document.LastSection.Add(table);

            return(document);
        }
Example #23
0
        public static string CreatePDFFileFromTxtFile(string textfilefullpath, string playerName)
        {
            Document doc     = new Document();
            Section  section = doc.AddSection();

            section.PageSetup.TopMargin    = 25;
            section.PageSetup.LeftMargin   = 30;
            section.PageSetup.RightMargin  = 30;
            section.PageSetup.BottomMargin = 25;

            MigraDoc.DocumentObjectModel.Font font = new MigraDoc.DocumentObjectModel.Font("Adobe Garamond Pro", 22);
            font.Bold      = true;
            font.Italic    = false;
            font.Underline = Underline.None;
            Paragraph paragraph = section.AddParagraph();

            paragraph.AddFormattedText(playerName + "'s Stats up to Season " + ConfigFile.SEASON_LAST, font);
            paragraph.Format.Shading.Color = Colors.LightSteelBlue;
            paragraph.Format.Alignment     = ParagraphAlignment.Center;
            Paragraph paragraph2 = section.AddParagraph();

            paragraph2.AddFormattedText("  ", new MigraDoc.DocumentObjectModel.Font("Courier New", 24));

            if (new FileInfo(Path.Combine(ConfigFile.DIRECTORY_OUTPUT.FullName, "chart.png")).Exists)
            {
                MigraDoc.DocumentObjectModel.Shapes.Image image = section.AddImage(Path.Combine(ConfigFile.DIRECTORY_OUTPUT.FullName, "chart.png"));
                image.Width              = "18cm";
                image.LockAspectRatio    = true;
                image.Left               = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Center;
                image.LineFormat.Visible = true;
                image.LineFormat.Width   = 1;
                image.LineFormat.Color   = Colors.LightGreen;
            }
            Paragraph paragraph3 = section.AddParagraph();

            paragraph3.AddFormattedText("  ", new MigraDoc.DocumentObjectModel.Font("Courier New", 10));

            if (new FileInfo(Path.Combine(ConfigFile.DIRECTORY_OUTPUT.FullName, "chart2.png")).Exists)
            {
                MigraDoc.DocumentObjectModel.Shapes.Image image = section.AddImage(Path.Combine(ConfigFile.DIRECTORY_OUTPUT.FullName, "chart2.png"));
                image.Width              = "18cm";
                image.LockAspectRatio    = true;
                image.Left               = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Center;
                image.LineFormat.Visible = true;
                image.LineFormat.Width   = 1;
                image.LineFormat.Color   = Colors.LightCoral;
            }
            Paragraph paragraph4 = section.AddParagraph();

            paragraph4.AddFormattedText("  ", new MigraDoc.DocumentObjectModel.Font("Courier New", 10));

            if (new FileInfo(Path.Combine(ConfigFile.DIRECTORY_OUTPUT.FullName, "chart3.png")).Exists)
            {
                MigraDoc.DocumentObjectModel.Shapes.Image image = section.AddImage(Path.Combine(ConfigFile.DIRECTORY_OUTPUT.FullName, "chart3.png"));
                image.Width              = "18cm";
                image.LockAspectRatio    = true;
                image.Left               = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Center;
                image.LineFormat.Visible = true;
                image.LineFormat.Width   = 1;
                image.LineFormat.Color   = Colors.LightBlue;
            }

            section.AddPageBreak();


            //just font arrangements as you wish

            section = DataOps.PrintDataSeason(section, textfilefullpath);
            section.AddPageBreak();
            section = DataOps.PrintDataByCategory(section, textfilefullpath);
            //add each line to pdf
            //foreach (string line in textFileLines)
            //{
            //    MigraDoc.DocumentObjectModel.Font font = new MigraDoc.DocumentObjectModel.Font("Courier New", 10);
            //    font.Bold = true;

            //    Paragraph paragraph = section.AddParagraph();
            //    paragraph.AddFormattedText(line, font);

            //}


            //save pdf document
            PdfDocumentRenderer renderer = new PdfDocumentRenderer();

            renderer.Document = doc;
            renderer.RenderDocument();
            FileInfo fileName = new FileInfo(Path.Combine(ConfigFile.DIRECTORY_OUTPUT.FullName, playerName + "_" + ConfigFile.SEASON_LAST.ToString() + ".pdf"));

            FileOps.CheckFile(fileName, true);
            renderer.Save(fileName.FullName);
            //if(fileName.Exists)
            //    Process.Start(fileName.FullName);
            return(fileName.FullName);
        }