CompleteRow() public method

public CompleteRow ( ) : void
return void
Example #1
0
 public void GenerarDocumento(Document document)
 {
     int i, j;
     PdfPTable datatable = new PdfPTable(dataGridView1.ColumnCount);
     datatable.DefaultCell.Padding = 3;
     float[] headerwidths = GetTamañoColumnas(dataGridView1);
     datatable.SetWidths(headerwidths);
     datatable.WidthPercentage = 100;
     datatable.DefaultCell.BorderWidth = 2;
     datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
     for (i = 0; i < dataGridView1.ColumnCount; i++)
     {
         datatable.AddCell(dataGridView1.Columns[i].HeaderText);
     }
     datatable.HeaderRows = 1;
     datatable.DefaultCell.BorderWidth = 1;
     for (i = 0; i < dataGridView1.Rows.Count; i++)
     {
         for (j = 0; j < dataGridView1.Columns.Count; j++)
         {
             if (dataGridView1[j, i].Value != null)
             {
                 datatable.AddCell(new Phrase(dataGridView1[j, i].Value.ToString()));//En esta parte, se esta agregando un renglon por cada registro en el datagrid
             }
         }
         datatable.CompleteRow();
     }
     document.Add(datatable);
 }
    private bool AddColumnHeader(DataTable dt, ref iTextSharp.text.pdf.PdfPTable mainTable, List <int> lstColumnNums, Dictionary <int, Helper.Alignment> dicDataType, List <int> lstColumnsDisplay)
    {
        try {
            mainTable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.BLACK;

            // Sets the gridview column names as table headers.

            foreach (int iCol in lstColumnNums)
            {
                if (lstColumnsDisplay.Count > 0 && lstColumnsDisplay.Contains(iCol) == false)
                {
                    continue;
                }

                Phrase ph = default(Phrase);
                //Dim strText As String = If(iCol = 999, String.Empty, dt.Columns(iCol).Caption)
                if (iCol == 999)
                {
                    PdfPCell cell = EmptyCell();
                    cell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
                    mainTable.AddCell(cell);
                }
                else
                {
                    ph            = new Phrase(dt.Columns[iCol].Caption, FontFactory.GetFont(SelectedFont, ColumnHeaderTextSize, iTextSharp.text.Font.NORMAL));
                    ph.Font.Color = iTextSharp.text.BaseColor.WHITE;

                    PdfPCell cell = new PdfPCell(ph);
                    //cell.HorizontalAlignment = GetAlignMent(dicDataType[iCol]);

                    if ((int)dicDataType[iCol] == (int)Helper.Alignment.Center)
                    {
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    }
                    if ((int)dicDataType[iCol] == (int)Helper.Alignment.Right)
                    {
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    }
                    if ((int)dicDataType[iCol] == (int)Helper.Alignment.Left)
                    {
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    }

                    cell.BackgroundColor = iTextSharp.text.BaseColor.GREEN;
                    //cell. Color == iTextSharp.text.BaseColor.BLACK
                    cell.NoWrap = true;
                    mainTable.AddCell(cell);
                }
            }
            mainTable.CompleteRow();
            mainTable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(true);
    }
Example #3
0
        public void MakeCards()
        {
            var deck = JsonConvert.DeserializeObject<Deck>(File.ReadAllText(@"C:\temp\testdeck.cm"));

            var cards = new List<MagickImage>();
            foreach (var card in deck.Cards) {
                var image = new MagickImage(new MagickColor("WhiteSmoke"), deck.Width, deck.Height);
                image.Density = new MagickGeometry(300, 300);
                image.Format = MagickFormat.Bmp;
                foreach (var element in deck.Elements) {
                    var data = card.ElementData[element.Key];
                    if (File.Exists(data)) {
                        using (var overlayImage = new MagickImage(data)) {
                            image.Composite(overlayImage, (int)element.Value.X, (int)element.Value.Y, CompositeOperator.Over);
                        }
                    } else {
                        using (var textImage = new MagickImage(MagickColor.Transparent, deck.Width, deck.Height)) {
                            textImage.Density = new MagickGeometry(300, 300);
                            textImage.Font = "Arial";
                            textImage.FontPointsize = 12;
                            textImage.FillColor = new MagickColor("Black");
                            var drawableText = new DrawableText(element.Value.X, element.Value.Y, data);
                            textImage.Draw(drawableText);
                            image.Composite(textImage, CompositeOperator.Over);
                        }
                    }
                }
                image.Write(string.Format(@"c:\temp\CardMaker\{0}.png", card.Name));
                cards.Add(image);

            }
            using (var doc = new Document()) {
                PdfWriter.GetInstance(doc, new FileStream(@"C:\temp\CardMaker\cards.pdf", FileMode.Create));
                doc.Open();
                var columns = (int)Math.Floor(doc.PageSize.Width / (deck.Width + 10));
                var table = new PdfPTable(columns) { WidthPercentage = 100, DefaultCell = { Border = 0, Padding = 5 } };

                foreach (var card in cards) {
                    var instance = Image.GetInstance(card.ToByteArray());
                    instance.SetDpi(300, 300);
                    var cell = new PdfPCell(instance) {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        Border = 0,
                        Padding = 5,
                    };
                    table.AddCell(cell);
                }
                table.CompleteRow();
                doc.Add(table);
            }
        }
Example #4
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         string RESOURCE = Utility.ResourcePosters;
         // we'll use 4 images in this example
         Image[] img = {
             Image.GetInstance(Path.Combine(RESOURCE, "0120903.jpg")),
             Image.GetInstance(Path.Combine(RESOURCE, "0290334.jpg")),
             Image.GetInstance(Path.Combine(RESOURCE, "0376994.jpg")),
             Image.GetInstance(Path.Combine(RESOURCE, "0348150.jpg"))
         };
         // Creates a table with 6 columns
         PdfPTable table = new PdfPTable(6);
         table.WidthPercentage = 100;
         // first movie
         table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
         table.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
         table.AddCell("X-Men");
         // we wrap he image in a PdfPCell
         PdfPCell cell = new PdfPCell(img[0]);
         table.AddCell(cell);
         // second movie
         table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
         table.AddCell("X2");
         // we wrap the image in a PdfPCell and let iText scale it
         cell = new PdfPCell(img[1], true);
         table.AddCell(cell);
         // third movie
         table.DefaultCell.VerticalAlignment = Element.ALIGN_BOTTOM;
         table.AddCell("X-Men: The Last Stand");
         // we add the image with addCell()
         table.AddCell(img[2]);
         // fourth movie
         table.AddCell("Superman Returns");
         cell = new PdfPCell();
         // we add it with addElement(); it can only take 50% of the width.
         img[3].WidthPercentage = 50;
         cell.AddElement(img[3]);
         table.AddCell(cell);
         // we complete the table (otherwise the last row won't be rendered)
         table.CompleteRow();
         document.Add(table);
     }
 }
Example #5
0
 private void AddEmptyRow(PdfPTable pdfPTable)
 {
     var columns = pdfPTable.NumberOfColumns;
     PdfPCell[] rowCells = new PdfPCell[columns];
     for (int j = 0; j < columns; j++)
     {
         rowCells[j] = new PdfPCell((new Phrase(" ", PDFBuilder.DefaultFont)))
         {
             PaddingLeft = 4,
             PaddingRight = 4,
             UseBorderPadding = true
         };
     }
     pdfPTable.Rows.Add(new PdfPRow(rowCells));
     pdfPTable.CompleteRow();
 }
Example #6
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;
            var q = DbUtil.Db.PeopleQuery(id);
            var q2 = from p in q
                     orderby p.Name2
                     select new
                     {
                         First = p.PreferredName,
                         Last = p.LastName,
                         p.PeopleId,
                         dob = p.DOB,
                         Phone = p.CellPhone.Length > 0 ? p.CellPhone : p.HomePhone,
                         p.DoNotPublishPhones
                     };
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            var document = new Document(PageSize.LETTER);
            document.SetMargins(40f, 36f, 32f, 36f);
            var w = PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();
            dc = w.DirectContent;

            var cols = new float[] { W, W, W - 10f };
            var t = new PdfPTable(cols);
            t.SetTotalWidth(cols);

            t.HorizontalAlignment = Element.ALIGN_CENTER;
            t.LockedWidth = true;
            t.DefaultCell.Border = PdfPCell.NO_BORDER;

            if (!q2.Any())
                document.Add(new Phrase("no data"));
            else
                foreach (var m in q2)
                    AddCell(t, m.First, m.Last, m.Phone, m.PeopleId, m.DoNotPublishPhones);
            t.CompleteRow();
            document.Add(t);

            document.Close();
        }
Example #7
0
        /// <summary>
        /// Exportars the PDF planificacion.
        /// </summary>
        /// <param name="TituloInforme">The titulo informe.</param>
        /// <param name="objPlanificacion">The obj planificacion.</param>
        public static void ExportarPDFPlanificacion(string TituloInforme, PlanificacionAnual objPlanificacion)
        {
            itsEvents ev = new itsEvents();

            Document documento = new Document(PageSize.A4, 10, 10, 80, 50);
            PdfWriter writerPdf = PdfWriter.GetInstance(documento, HttpContext.Current.Response.OutputStream);
            writerPdf.PageEvent = ev;
            documento.Open();

            string strTitulo = "Asignatura: " + objPlanificacion.curricula.asignatura.nombre
                          + "\n " + objPlanificacion.cicloLectivo.nombre.Substring(0, 13) + ": "
                          + objPlanificacion.cicloLectivo.nombre.Substring(14);

            string strFileName = "Planificacion_" + objPlanificacion.curricula.asignatura.nombre
                          + "_" + objPlanificacion.curricula.nivel.nombre;

            string fecha = DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour.ToString().PadLeft(2, '0') + ":" + DateTime.Now.Minute.ToString().PadLeft(2, '0');

            Font font24B = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 24, Font.BOLD, BaseColor.GRAY);
            Phrase Titulo = new Phrase("EDU@R 2.0", font24B);

            Font font15B = FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLD);
            ev.tituloReporte = TituloInforme;
            ev.fechaReporte = fecha;

            Font font12 = FontFactory.GetFont(FontFactory.TIMES, 12, Font.NORMAL);

            Paragraph parrafo = new Paragraph(strTitulo, font15B);
            documento.Add(parrafo);

            if (objPlanificacion.listaCursos != null && objPlanificacion.listaCursos.Count > 0)
            {
                parrafo = new Paragraph("Cursos: ", font15B);
                documento.Add(parrafo);
                foreach (CursoCicloLectivo item in objPlanificacion.listaCursos)
                {
                    parrafo = new Paragraph("- " + objPlanificacion.curricula.nivel.nombre + " " + item.curso.nombre, font15B);
                    documento.Add(parrafo);
                }
            }

            string strFechas;
            if (objPlanificacion.fechaAprobada.HasValue)
            {
                strFechas = "Fecha Aprobación: " + Convert.ToDateTime(objPlanificacion.fechaAprobada).ToShortDateString();
                parrafo = new Paragraph(strFechas, font15B);
                documento.Add(parrafo);
            }
            else
            {
                Font font15R = FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLDITALIC, BaseColor.RED);
                strFechas = "Pendiente de Aprobación";
                parrafo = new Paragraph(strFechas, font15R);
                documento.Add(parrafo);
            }

            PdfPTable tabla = new PdfPTable(1);
            tabla.SpacingBefore = 10;
            tabla.SpacingAfter = 0;
            tabla.KeepTogether = true;
            tabla.WidthPercentage = 100;
            PdfPCell celdaTitulo = new PdfPCell(new Phrase("", font15B));
            celdaTitulo.Border = 0;
            celdaTitulo.BorderWidthBottom = 1;
            tabla.AddCell(celdaTitulo);
            tabla.CompleteRow();
            documento.Add(tabla);

            //parrafo = new Paragraph("\n", font15B);
            //documento.Add(parrafo);

            if (objPlanificacion.listaTemasPlanificacion.Count > 0)
            {
                int contador = 0;
                foreach (TemaPlanificacionAnual item in objPlanificacion.listaTemasPlanificacion)
                {
                    contador++;
                    parrafo = new Paragraph("Periodo: " + Convert.ToDateTime(item.fechaInicioEstimada).ToShortDateString() + " al " + Convert.ToDateTime(item.fechaFinEstimada).ToShortDateString(), font15B);
                    documento.Add(parrafo);

                    if (item.contenidosConceptuales.Trim().Length > 0)
                    {
                        parrafo = new Paragraph("Contenidos Conceptuales", font15B);
                        documento.Add(parrafo);

                        parrafo = new Paragraph(item.contenidosConceptuales, font12);
                        documento.Add(parrafo);

                        parrafo = new Paragraph("\n", font15B);
                        documento.Add(parrafo);
                    }

                    if (item.contenidosActitudinales.Trim().Length > 0)
                    {
                        parrafo = new Paragraph("Contenidos Actitudinales", font15B);
                        documento.Add(parrafo);

                        parrafo = new Paragraph(item.contenidosActitudinales, font12);
                        documento.Add(parrafo);

                        parrafo = new Paragraph("\n", font15B);
                        documento.Add(parrafo);
                    }

                    if (item.contenidosProcedimentales.Trim().Length > 0)
                    {
                        parrafo = new Paragraph("Contenidos Procedimentales", font15B);
                        documento.Add(parrafo);

                        parrafo = new Paragraph(item.contenidosProcedimentales, font12);
                        documento.Add(parrafo);

                        parrafo = new Paragraph("\n", font15B);
                        documento.Add(parrafo);
                    }

                    if (item.criteriosEvaluacion.Trim().Length > 0)
                    {
                        parrafo = new Paragraph("Criterios de Evaluación", font15B);
                        documento.Add(parrafo);

                        parrafo = new Paragraph(item.criteriosEvaluacion, font12);
                        documento.Add(parrafo);

                        parrafo = new Paragraph("\n", font15B);
                        documento.Add(parrafo);
                    }

                    if (item.estrategiasAprendizaje.Trim().Length > 0)
                    {
                        parrafo = new Paragraph("Estrategias de Aprendizaje", font15B);
                        documento.Add(parrafo);

                        parrafo = new Paragraph(item.estrategiasAprendizaje, font12);
                        documento.Add(parrafo);

                        parrafo = new Paragraph("\n", font15B);
                        documento.Add(parrafo);
                    }

                    if (item.instrumentosEvaluacion.Trim().Length > 0)
                    {
                        parrafo = new Paragraph("Instrumentos de Evaluación", font15B);
                        documento.Add(parrafo);

                        parrafo = new Paragraph(item.instrumentosEvaluacion, font12);
                        documento.Add(parrafo);

                        parrafo = new Paragraph("\n", font15B);
                        documento.Add(parrafo);
                    }

                    if (contador < objPlanificacion.listaTemasPlanificacion.Count)
                    {
                        tabla = new PdfPTable(1);
                        tabla.SpacingBefore = 10;
                        tabla.SpacingAfter = 0;
                        tabla.KeepTogether = true;
                        tabla.WidthPercentage = 100;
                        celdaTitulo = new PdfPCell(new Phrase("", font15B));
                        celdaTitulo.Border = 0;
                        celdaTitulo.BorderWidthBottom = 1;
                        tabla.AddCell(celdaTitulo);
                        tabla.CompleteRow();
                        documento.Add(tabla);

                        //parrafo = new Paragraph("\n", font15B);
                        //documento.Add(parrafo);
                    }
                }
            }

            documento.Close();
            strFileName = strFileName.Trim().Replace("\n", "_").Replace(" ", "_");
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + strFileName + "-" + fecha.Replace(' ', '_').Trim() + ".pdf");
            HttpContext.Current.Response.Flush();//HttpContext.Current.Response.End();
        }
Example #8
0
        /// <summary>
        /// Exportars the grafico PDF.
        /// </summary>
        /// <param name="TituloInforme">The titulo informe.</param>
        /// <param name="username">The username.</param>
        /// <param name="filtros">The filtros.</param>
        /// <param name="nombrePNG">The nombre PNG.</param>
        /// <param name="tablaGrafico">The tabla grafico.</param>
        public static void ExportarGraficoPDF(string TituloInforme, string username, string filtros, string nombrePNG, List<string> tablaGrafico)
        {
            itsEvents ev = new itsEvents();

            Persona usuario = new Persona();
            usuario.username = username;
            BLPersona objBLPersona = new BLPersona(usuario);
            objBLPersona.GetPersonaByEntidad();
            usuario = objBLPersona.Data;

            Document documento = new Document(PageSize.A4, 10, 10, 80, 50);
            PdfWriter writerPdf = PdfWriter.GetInstance(documento, HttpContext.Current.Response.OutputStream);
            writerPdf.PageEvent = ev;
            documento.Open();

            string strTitulo = TituloInforme;
            string fecha = DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour.ToString().PadLeft(2, '0') + ":" + DateTime.Now.Minute.ToString().PadLeft(2, '0');

            Font font24B = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 24, Font.BOLD, BaseColor.GRAY);
            Phrase Titulo = new Phrase("EDU@R 2.0", font24B);

            Font font15B = FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLDITALIC);
            ev.tituloReporte = strTitulo;
            ev.fechaReporte = fecha;

            Font font12B = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, Font.NORMAL);
            Font font10N = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.NORMAL);
            PdfPTable grdTableEncabezado = new PdfPTable(1);
            grdTableEncabezado.WidthPercentage = 90;
            grdTableEncabezado.AddCell(new PdfPCell(new Phrase("- Usuario: " + usuario.apellido + " " + usuario.nombre, font12B)));
            grdTableEncabezado.CompleteRow();
            grdTableEncabezado.AddCell(new PdfPCell(new Phrase(filtros, font12B)));
            grdTableEncabezado.CompleteRow();
            documento.Add(grdTableEncabezado);

            //valido si mando el nombre de un gráfico
            if (!string.IsNullOrEmpty(nombrePNG))
            {
                //Verifica si existe el archivo
                if (System.IO.File.Exists(nombrePNG))
                {
                    documento.Add(new Paragraph(""));
                    Image grafico = Image.GetInstance(nombrePNG);
                    grafico.ScalePercent(50, 50);
                    grafico.Alignment = Element.ALIGN_CENTER;
                    if (grafico != null)
                        documento.Add(grafico);
                    documento.Add(new Paragraph(""));
                }
            }

            // Recorremos la variable tablaGrafico para agregar información adicional a la exportación del gráfico
            foreach (var item in tablaGrafico)
            {
                if (item.Substring(0, 1).Equals("-"))
                    documento.Add(new iTextSharp.text.Paragraph(item, font12B));
                else
                    documento.Add(new iTextSharp.text.Paragraph(item, font10N));
            }

            //Cerramos el Documento
            documento.Close();
            strTitulo = strTitulo.Replace(" ", string.Empty);
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + strTitulo.Trim().Replace(" ", string.Empty) + "-" + fecha.Replace(' ', '_').Trim() + ".pdf");
            HttpContext.Current.Response.Flush();
        }
        public ActionResult Index()
        {
           
            var doc = new Document();
            doc.AddTitle("PDF Sales Report");
            string path = "../../PDFReports";
            
            PdfWriter.GetInstance(doc, new FileStream(path + "/Doc.pdf", FileMode.Create));

            
            PdfPTable table = new PdfPTable(5);
            PdfPCell cell = new PdfPCell();
            PdfPCell firstCell = new PdfPCell();
            firstCell.Phrase = new Phrase("Aggregated Sales Report");
            firstCell.Colspan = 5;
            
                       
            table.AddCell(firstCell);
            table.CompleteRow();

            cell.Phrase = new Phrase("Product");
            table.AddCell(cell);

            cell.Phrase = new Phrase("Quantity");
            table.AddCell(cell);

            cell.Phrase = new Phrase("Unit Price");
            table.AddCell(cell);

            cell.Phrase = new Phrase("Location");
            table.AddCell(cell);

            cell.Phrase = new Phrase("Sum");
            table.AddCell(cell);



            /////////////////
            SqlConnection con = new SqlConnection("Database=.;Initial Catalog=Supermarket;Integrated Security=true");
            con.Open();
            using (con)
            {
                SqlCommand com = new SqlCommand("SELECT * FROM Productss", con);
                SqlDataReader reader = com.ExecuteReader();

                decimal totalSum = 0;

                while (reader.Read())
                {

                    string productName = (string)reader[1];
                    string quantity = (string)reader[2];
                    decimal price = (decimal)reader[3];
                    string location = (string)reader[4];
                    decimal sum = (decimal)reader[5];
                    totalSum += sum;

                    cell.Phrase = new Phrase(productName);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(quantity);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(price.ToString());
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(location);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(sum.ToString());
                    table.AddCell(cell);
                }
                var rows = table.GetRows(0, 4);

                for (int i = 3; i < rows.Count; i++)
                {
                    var row = table.GetRow(i);
                    var cols = row.GetCells();
                    foreach (var col in cols)
                    {
                        Console.Write(col.Phrase.Content + " ");
                    }
                    Console.WriteLine();
                }
                
            }
            doc.Open();
            doc.Add(table);
            doc.Close();

            return Redirect("http://localhost:20144/pdfreports/doc.pdf");
        }
Example #10
0
 // ---------------------------------------------------------------------------
 /**
  * Creates a PDF document.
  */
 public virtual void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document(PageSize.A4.Rotate()))
     {
         // step 2
         PdfWriter writer = PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         // "en" => System.Globalization.GregorianCalendar 
         Calendar calendar = new CultureInfo(LANGUAGE, false).Calendar;
         PdfContentByte canvas = writer.DirectContent;
         // Loop over the months
         for (int month = 0; month < 12; month++)
         {
             int current_month = month + 1;
             DateTime dt = new DateTime(YEAR, current_month, 1, calendar);
             // draw the background
             DrawImageAndText(canvas, dt);
             // create a table with 7 columns
             PdfPTable table = new PdfPTable(7);
             table.TotalWidth = 504;
             // add the name of the month
             table.DefaultCell.BackgroundColor = BaseColor.WHITE;
             table.AddCell(GetMonthCell(dt));
             int daysInMonth = DateTime.DaysInMonth(YEAR, dt.Month);
             int day = 1;
             // add empty cells
             // SUNDAY; Java => 1, .NET => 0
             int position = 0;
             while (position++ != (int)dt.DayOfWeek)
             {
                 table.AddCell("");
             }
             // add cells for each day
             while (day <= daysInMonth)
             {
                 dt = new DateTime(YEAR, current_month, day++, calendar);
                 table.AddCell(GetDayCell(dt));
             }
             // complete the table
             table.CompleteRow();
             // write the table to an absolute position
             table.WriteSelectedRows(0, -1, 169, table.TotalHeight + 18, canvas);
             document.NewPage();
         }
     }
 }
Example #11
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            dt = Util.Now;

            doc = new Document(PageSize.LETTER, 36, 36, 36, 36);
            var w = PdfWriter.GetInstance(doc, Response.OutputStream);
            w.PageEvent = pageEvents;
            doc.Open();
            dc = w.DirectContent;
            ct = new ColumnText(dc);

            if (!qid.HasValue)
                doc.Add(new Phrase("no data"));
            else
            {
                pageEvents.StartPageSet("Outreach/Inreach Report: {0:d}".Fmt(dt));
                IQueryable<ProspectInfo> q = GetProspectInfo(AlphaSort);
                if (!q.Any())
                    doc.Add(new Phrase("no data"));
                else
                    foreach (var p in q)
                    {
                        doc.NewPage();
                        var t = new PdfPTable(new float[] { 62f, 61f, 67f });
                        t.SetNoPadding();
                        var t1 = new PdfPTable(1);
                        t1.SetNoBorder();
                        var t2 = new PdfPTable(new float[] { 30f, 31f });
                        t2.SetNoBorder();
                        var t3 = new PdfPTable(new float[] { 27f, 40f });
                        t3.SetNoBorder();

                        var ph = new Paragraph();
                        ph.Add(new Chunk(p.Name, bfont));
                        ph.Add(new Chunk(" ({0})".Fmt(p.PeopleId), smallfont));
                        t1.AddCell(ph);
                        ph = new Paragraph();
                        ph.AddLine(p.Address, font);
                        ph.AddLine(p.Address2, font);
                        ph.AddLine(p.CityStateZip, font);
                        ph.Add("\n");
                        ph.AddLine(p.HomePhone.FmtFone("H"), font);
                        ph.AddLine(p.CellPhone.FmtFone("C"), font);
                        ph.AddLine(p.EMail, font);
                        t1.AddCell(ph);
                        t.AddCell(t1);

                        t2.Add("Position in Family:", font);
                        t2.Add(p.PositionInFamily, font);
                        t2.Add("Gender:", font);
                        t2.Add(p.Gender, font);
                        t2.Add("Marital Status:", font);
                        t2.Add(p.MaritalStatus, font);
                        t2.Add("", font);
                        t2.CompleteRow();

                        if (p.ChristAsSavior.HasValue())
                            t2.Add(p.ChristAsSavior, 2, font);
                        if (p.InfoBecomeAChristian.HasValue())
                            t2.Add(p.InfoBecomeAChristian, 2, font);
                        if (p.InterestedInJoining.HasValue())
                            t2.Add(p.InterestedInJoining, 2, font);
                        if (p.PleaseVisit.HasValue())
                            t2.Add(p.PleaseVisit, 2, font);

                        t.AddCell(t2);

                        t3.Add("Member Status:", font);
                        t3.Add(p.MemberStatus, font);
                        t3.Add("Origin:", font);
                        t3.Add(p.Origin, font);
                        t3.Add("Age:", font);
                        t3.Add(p.Age, font);
                        t3.Add("Comments:", 2, font);
                        t3.Add(p.Comment, 2, font);

                        t.AddCell(t3);
                        doc.Add(t);

                        if (p.Family.Count() > 0)
                        {
                            t = new PdfPTable(5);
                            t.SetNoBorder();
                            t.AddRow("Family Summary", bfont);
                            t.AddHeader("Name", bfont);
                            t.AddHeader("Age", bfont);
                            t.AddHeader("Cell Phone", bfont);
                            t.AddHeader("Position in Family", bfont);
                            t.AddHeader("Member Status", bfont);
                            foreach (var fm in p.Family)
                            {
                                t.Add(fm.Name, font);
                                t.Add(fm.Age.ToString(), font);
                                t.Add(fm.CellPhone.FmtFone(), font);
                                t.Add(fm.PositionInFamily, font);
                                t.Add(fm.MemberStatus, font);
                            }
                            doc.Add(t);
                        }
                        if (p.Comments.Count() > 0)
                        {
                            t = new PdfPTable(new float[] { 31f, 134f });
                            t.SetNoBorder();
                            t.AddRow("Comments", bfont);
                            t.AddHeader("Field", bfont);
                            t.AddHeader("Comments", bfont);
                            foreach (var c in p.Comments)
                            {
                                t.Add(c.CommentField, bfont);
                                t.Add(c.Comments, font);
                            }
                            doc.Add(t);
                        }

                        if (p.Attends.Count() > 0)
                        {
                            t = new PdfPTable(new float[] { 24f, 73f, 56f, 34f });
                            t.SetNoBorder();
                            t.AddRow("Attendance Summary", bfont);
                            t.AddHeader("Date", bfont);
                            t.AddHeader("Event", bfont);
                            t.AddHeader("Teacher", bfont);
                            t.AddHeader("Schedule", bfont);
                            foreach (var a in p.Attends)
                            {
                                t.Add(a.MeetingDate.FormatDate(), font);
                                t.Add(a.MeetingName, font);
                                t.Add(a.Teacher, font);
                                t.Add(a.MeetingDate.ToString2("t"), font);
                            }
                            doc.Add(t);
                        }

                        if (p.Contacts.Count() > 0)
                        {
                            t = new PdfPTable(new float[] { 31f, 134f });
                            t.SetNoBorder();
                            t.AddRow("Contacts", font);
                            t.AddHeader("Date/Type/Team", font);
                            t.AddHeader("Comments", font);
                            foreach (var a in p.Contacts)
                            {
                                t.AddHeader("{0:d}\n{1}\n{2}".Fmt(a.ContactDate, a.TypeOfContact, a.Team), font);
                                t.AddHeader(a.Comments, font);
                            }
                            doc.Add(t);
                        }

                        if (p.Memberships.Count() > 0)
                        {
                            t = new PdfPTable(4);
                            t.SetNoBorder();
                            t.AddRow("Current Enrollment", bfont);
                            t.AddHeader("Division", bfont);
                            t.AddHeader("Organization", bfont);
                            t.AddHeader("Member Type", bfont);
                            t.AddHeader("Enroll Date", bfont);
                            foreach (var m in p.Memberships)
                            {
                                t.Add(m.DivisionName, font);
                                t.Add(m.Name, font);
                                t.Add(m.MemberType, font);
                                t.Add(m.EnrollDate.FormatDate(), font);
                            }
                            doc.Add(t);
                        }
                        if (p.FamilyComments.Count() > 0)
                        {
                            t = new PdfPTable(new float[] { 31f, 134f });
                            t.SetNoBorder();
                            t.AddRow("Family Comments", bfont);
                            t.AddHeader("Field", bfont);
                            t.AddHeader("Comments", bfont);
                            foreach (var c in p.FamilyComments)
                            {
                                t.Add(c.CommentField, bfont);
                                t.Add(c.Comments, font);
                            }
                            doc.Add(t);
                        }
                        if (ShowForm)
                            ContactForm();
                    }
            }
            pageEvents.EndPageSet();
            doc.Close();
        }
        /// <summary>
        /// Add a row of pdfpcell to table.
        /// return True, current page have enought size for that row
        /// return False, current page not enought size for that row, row will be remove and need to draw on
        /// next page
        /// 20130606 :: jaimelopez :: mellorasinxelas to support absolute footer.
        /// </summary>
        /// <param name="table"></param>
        /// <param name="tableRowElement"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected bool DrawTableRow(
            PdfPTable table,
            TableRow tableRowElement,
            IDictionary data)
        {
            bool enoughSpace = true;
            PDFDrawItextSharp.PDFDrawItextSharp pdfDraw = (PDFDrawItextSharp.PDFDrawItextSharp)pdfDrawer;
            foreach (TableCell tableCell in tableRowElement.TableCells)
            {
                PdfPCell cell = pdfDraw.CreateTableCell(tableCell.Attributes, data);
                foreach (DrawElement drawElement in tableCell.DrawElements)
                {
                    if (drawElement is TextBox)
                    {
                        //iTextSharp.text.Phrase phrase = _pdfDraw.CreatePhrase(
                        //    ((PDFTemplate.TextBox)drawElement).GetText(data), drawElement.FontAttributes);
                        Paragraph paragraph = pdfDraw.CreateParagraph(((TextBox)drawElement).GetText(data), drawElement.FontAttributes);
                        paragraph.Alignment = PDFDrawItextSharpHelper.Align(Helper.GetAttributeValue("align", drawElement.Attributes, "Left"));

                        cell.AddElement(paragraph);
                    }
                    else if (drawElement is PDFTemplate.Image)
                    {
                        iTextSharp.text.Image image = pdfDraw.CreateImageFromAttribute(drawElement.Attributes);
                        image.Alignment = PDFDrawItextSharpHelper.Align(Helper.GetAttributeValue("align", drawElement.Attributes, "Left"));

                        cell.AddElement(image);
                    }
                }
                table.AddCell(cell);
            }
            table.CompleteRow();

            //if(table.row
            //fixme need to check if any row span
            if (pdfDrawer.isNoMoreY(table.TotalHeight, DocumentGroup.Table))
            {
                enoughSpace = false;
                table.DeleteLastRow();
            }

            return enoughSpace;
        }
    /// <summary>
    ///
    /// </summary>
    /// <param name="dt">Input Datatable to Export to PDF</param>
    /// <param name="strFilter">Filter conditions or remarks to display on report header</param>
    /// <param name="dicDataType">(ColumnIndex, XLDatattype)</param>
    /// <param name="lstRepeatColumn">Left most ColumnIndex to repeat on all pages</param>
    /// <param name="lstColumnsDisplay">ColumnIndex to display. Count = 0  or Nothing will Display All columns</param>
    /// <returns></returns>
    /// <remarks></remarks>
    public bool ExportToPDF(DataTable dt, string strFilter, Dictionary <int, Helper.Alignment> dicDataType, List <int> lstRepeatColumn = null, List <int> lstColumnsDisplay = null)
    {
        try {
            ICollection <string> myCol;           // = ICollection<string>;
            //'/Returns the list of all font families included in iTextSharp.
            myCol = iTextSharp.text.FontFactory.RegisteredFamilies;
            //'Returns the list of all fonts included in iTextSharp.
            myCol = iTextSharp.text.FontFactory.RegisteredFonts;

            //FontFactory.Register("F:\Transfer\SEGOEUI.TTF")
            //SelectedFont = FontFactory.GetFont("SEGOEUI")

            // Dim Segoe As Font = FontFactory.GetFont("SegoeUI") ' , BaseFont.IDENTITY_H, 8)
            //Dim bfTimes As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
            //Dim customfont As BaseFont
            //Try
            //    'customfont = BaseFont.CreateFont("F:\Transfer\SEGOEUI.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
            //    ' customfont = BaseFont.CreateFont(Segoe) '"F:\Transfer\SEGOEUI.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
            //    FontFactory.Register("F:\Transfer\SEGOEUI.TTF")
            //Catch ex As Exception
            //    Dim s = ex.Message
            //End Try


            int noOfColumns = dt.Columns.Count;
            int noOfRows    = dt.Rows.Count;
            Dictionary <int, float> dicWidth = new Dictionary <int, float>();

            if ((lstRepeatColumn == null))
            {
                lstRepeatColumn = new List <int>();
            }
            if ((lstColumnsDisplay == null))
            {
                lstColumnsDisplay = new List <int>();
            }
            if ((dicDataType == null))
            {
                dicDataType = new Dictionary <int, Helper.Alignment>();
                for (int icol = 0; icol <= noOfColumns - 1; icol++)
                {
                    dicDataType.Add(icol, Helper.Alignment.Left);
                }
            }

            SelectedFont = "Arial";
            // "Arial"  SEGOEUI COURIER HELVETICA
            HeaderFontColor = iTextSharp.text.BaseColor.BLUE;

            List <iTextSharp.text.pdf.PdfPTable> lstTables = new List <iTextSharp.text.pdf.PdfPTable>();
            // Creates a PDF document
            Document document = null;
            //If LandScape = True Then
            //document = new Document( PageSize.A4.Rotate   , 0.0f, 0.0f, 40.0f, 15.0f);
            document = new Document(new RectangleReadOnly(595, 842, 90), 0.0f, 0.0f, 40.0f, 15.0f);
            //LandScape  (W x H, 842 x 595) points
            //Else
            //'document = New Document(PageSize.A4, 0, 0, 15, 5) 'Portrait (W x H, 595 × 842) points
            //End If

            //dicWidth = GetColumnWidth(dt)
            dicWidth = GetColumnWidth(dt, SelectedFont, ColumnHeaderTextSize);

            Dictionary <int, List <int> > dicColsPerPage = new Dictionary <int, List <int> >();

            dicColsPerPage = GetColumnsPerPageByWidth(dt, dicWidth, lstRepeatColumn, lstColumnsDisplay);

            foreach (int intDt in dicColsPerPage.Keys)
            {
                List <int> lstColumnNums = dicColsPerPage[intDt];

                float[] arrColsrelativeWidths = new float[lstColumnNums.Count];
                dynamic dblTotalWidth         = dicWidth.Sum(t => t.Value);

                int iArrIndex = 0;

                foreach (int iCol in lstColumnNums)
                {
                    arrColsrelativeWidths[iArrIndex] = dicWidth[iCol];
                    //dblTotalWidth = dblTotalWidth + dicWidth(iCol)
                    iArrIndex = iArrIndex + 1;
                }

                iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(arrColsrelativeWidths);

                mainTable.TotalWidth = document.PageSize.Width * 0.9f;

                AddPageHeaderToPDFDataTable(ref mainTable, dt.TableName, strFilter, lstColumnNums.Count - 1);
                AddColumnHeader(dt, ref mainTable, lstColumnNums, dicDataType, lstColumnsDisplay);

                //'  If dblTotalWidth <= A4Dimension.Width * 0.9 - 30 Then mainTable.LockedWidth = True
                Phrase ph = default(Phrase);

                //' Date - centre, Double Right, String Left, INteger centre
                // Reads the gridview rows and adds them to the mainTable


                for (int rowNo = 0; rowNo <= noOfRows - 1; rowNo++)
                {
                    foreach (int iCol in lstColumnNums)
                    {
                        if (lstColumnsDisplay.Count > 0 && lstColumnsDisplay.Contains(iCol) == false)
                        {
                            continue;
                        }
                        if (iCol == 999)
                        {
                            mainTable.AddCell(EmptyCell());
                        }
                        else
                        {
                            string sData = (dt.Rows[rowNo][iCol] == null) ? string.Empty : dt.Rows[rowNo][iCol].ToString().Trim();
                            ph = new Phrase(sData, FontFactory.GetFont(SelectedFont, ReportTextSize, iTextSharp.text.Font.NORMAL));

                            PdfPCell cell = new PdfPCell(ph);
                            //cell.HorizontalAlignment =  GetAlignMent(dicDataType[iCol]);
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Center)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            }
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Right)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            }
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Left)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            }

                            if (lstRepeatColumn.Contains(iCol))
                            {
                                cell.BackgroundColor = iTextSharp.text.BaseColor.YELLOW;
                            }

                            cell.NoWrap            = true;
                            cell.VerticalAlignment = Element.ALIGN_TOP;
                            //Element.ALIGN_TOP
                            mainTable.AddCell(cell);
                        }
                    }

                    mainTable.CompleteRow();
                    // Tells the mainTable to complete the row even if any cell is left incomplete.

                    if (mainTable.TotalHeight >= 595 - 65)                     // A4Dimension.Height - 65) {
                    {
                        lstTables.Add(mainTable);

                        mainTable            = new iTextSharp.text.pdf.PdfPTable(arrColsrelativeWidths);
                        mainTable.TotalWidth = document.PageSize.Width * 0.9f;

                        AddPageHeaderToPDFDataTable(ref mainTable, dt.TableName, strFilter, lstColumnNums.Count - 1);
                        AddColumnHeader(dt, ref mainTable, lstColumnNums, dicDataType, lstColumnsDisplay);
                    }
                }

                mainTable.CompleteRow();
                lstTables.Add(mainTable);
            }
            //Dict

            string strFileName = @"C:\Code\Project\TrailCode\eCatenate" + "\\" + dt.TableName + "_" + DateTime.Now.ToString("yyyyMMdd HHmmss") + ".pdf";

            // Gets the instance of the document created and writes it to the output stream of the Response object.
            PdfWriter pdfWrite = PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
            // Response.OutputStream)
            pdfPage _pdfpage = new pdfPage(SelectedFont, HeaderFontColor);

            pdfWrite.PageEvent = _pdfpage;
            // Creates a footer for the PDF document.
            //Dim pdfFooter As New HeaderFooter(New Phrase("Page : ", FontFactory.GetFont(FontFactory.COURIER, FooterTextSize, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.DARK_GRAY)), True)

            //pdfFooter.Alignment = Element.ALIGN_CENTER
            //pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER

            var _with1 = document;
            //.Footer = pdfFooter
            _with1.Open();

            //document.Add(New Paragraph(strFont, times))

            _with1.AddCreator("ElaiyaKumar");
            _with1.AddAuthor("By ElaiyaKumar");
            foreach (iTextSharp.text.pdf.PdfPTable oMainTable in lstTables)
            {
                _with1.Add(oMainTable);
                _with1.NewPage();
            }
            _with1.Close();

            document = null;
            Console.WriteLine("Any key to save ....");
            Console.ReadKey();
            //Interaction.MsgBox("Report Saved as " + strFileName, MsgBoxStyle.Information, "Export PDF");
            Console.WriteLine(strFileName);
            Console.WriteLine();

            Process.Start(strFileName);
            return(true);
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(false);
    }
Example #14
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            dt = Util.Now;

            doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64);
            var w = PdfWriter.GetInstance(doc, Response.OutputStream);

            var i = (from m in DbUtil.Db.Meetings
                     where m.MeetingId == mtgid
                     select new
                     {
                         m.Organization.OrganizationName,
                         m.Organization.LeaderName,
                         m.MeetingDate
                     }).SingleOrDefault();

            w.PageEvent = new HeadFoot
            {
                HeaderText = $"Guests/Absents Report: {i.OrganizationName} - {i.LeaderName} {i.MeetingDate:g}",
                FooterText = "Guests/Absents Report"
            };
            doc.Open();

            var q = VisitsAbsents(mtgid.Value);

            if (!mtgid.HasValue || i == null || !q.Any())
                doc.Add(new Paragraph("no data"));
            else
            {
                var mt = new PdfPTable(1);
                mt.SetNoPadding();
                mt.HeaderRows = 1;

                float[] widths = {4f, 6f, 7f, 2.6f, 2f, 3f};
                var t = new PdfPTable(widths);
                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
                t.DefaultCell.SetLeading(2.0f, 1f);
                t.WidthPercentage = 100;

                t.AddHeader("Name", boldfont);
                t.AddHeader("Address", boldfont);
                t.AddHeader("Phone/Email", boldfont);
                t.AddHeader("Last Att.", boldfont);
                t.AddHeader("Birthday", boldfont);
                t.AddHeader("Guest/Member", boldfont);
                mt.AddCell(t);

                var color = BaseColor.BLACK;
                bool? v = null;
                foreach (var p in q)
                {
                    if (color == BaseColor.WHITE)
                        color = new GrayColor(240);
                    else
                        color = BaseColor.WHITE;

                    t = new PdfPTable(widths);
                    t.SetNoBorder();
                    t.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
                    t.DefaultCell.BackgroundColor = color;

                    if (v != p.visitor)
                        t.Add($"             ------ {(p.visitor ? "Guests" : "Absentees")} ------", 6, bigboldfont);
                    v = p.visitor;

                    t.Add(p.Name, font);

                    var ph = new Paragraph();
                    ph.AddLine(p.Address, font);
                    ph.AddLine(p.Address2, font);
                    ph.AddLine(p.CSZ, font);
                    t.AddCell(ph);

                    ph = new Paragraph();
                    ph.AddLine(p.HomePhone.FmtFone("H"), font);
                    ph.AddLine(p.CellPhone.FmtFone("C"), font);
                    ph.AddLine(p.Email, font);
                    t.AddCell(ph);

                    t.Add(p.LastAttend.FormatDate(), font);
                    t.Add(p.Birthday, font);
                    t.Add(p.Status, font);
                    t.CompleteRow();

                    if (p.Status == null || !p.Status.StartsWith("Visit"))
                    {
                        t.Add("", font);
                        t.Add($"{p.AttendStr}           {p.AttendPct:n1}{(p.AttendPct.HasValue ? "%" : "")}", 5, monofont);
                    }

                    mt.AddCell(t);
                }
                doc.Add(mt);
            }
            doc.Close();
        }
Example #15
0
    public void ExportToPDF(string ReportName, GridView grdPDF, bool isLandscape, string Filename)
    {
        int       noOfColumns = 0, noOfRows = 0;
        DataTable tbl = null;

        if (grdPDF.AutoGenerateColumns)
        {
            tbl         = grdPDF.DataSource as DataTable; // Gets the DataSource of the GridView Control.
            noOfColumns = tbl.Columns.Count;
            noOfRows    = tbl.Rows.Count;
        }
        else
        {
            noOfColumns = grdPDF.Columns.Count;
            noOfRows    = grdPDF.Rows.Count;
        }
        float HeaderTextSize      = 8;
        float ReportNameSize      = 10;
        float ReportTextSize      = 8;
        float ApplicationNameSize = 7;

        // Creates a PDF document
        Document document = null;

        if (isLandscape == true)
        {
            // Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
            document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
        }
        else
        {
            document = new Document(PageSize.A4, 0, 0, 15, 5);
        }

        PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

        // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
        mainTable.HeaderRows = 4;

        // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
        PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);
        //iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("../Images/medtech_logo.jpg"));
        //imgLogo.ScaleToFit(100, 25);

        //PdfPCell clApplicationName = new PdfPCell(imgLogo);
        //clApplicationName.Border = PdfPCell.NO_BORDER;
        //clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

        // Creates a phrase to show the current date at the right hand side of the header.
        Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd-MMM-yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
        // Creates a PdfPCell which accepts the date phrase as a parameter.
        PdfPCell clDate = new PdfPCell(phDate);

        // Sets the Horizontal Alignment of the PdfPCell to right.
        clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
        // Sets the border of the cell to zero.
        clDate.Border = PdfPCell.NO_BORDER;

        //headerTable.AddCell(clApplicationName);
        headerTable.AddCell(clDate);
        headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

        // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
        PdfPCell cellHeader = new PdfPCell(headerTable);

        cellHeader.Border = PdfPCell.NO_BORDER;
        // Sets the column span of the header cell to noOfColumns.
        cellHeader.Colspan = noOfColumns;
        // Adds the above header cell to the table.
        mainTable.AddCell(cellHeader);

        // Creates a phrase which holds the file name.
        //Phrase phHeader = new Phrase(sApplicationName, FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
        //PdfPCell clHeader = new PdfPCell(phHeader);
        //clHeader.Colspan = noOfColumns;
        //clHeader.Border = PdfPCell.NO_BORDER;
        //clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
        //mainTable.AddCell(clHeader);

        // Creates a phrase for a new line.
        Phrase   phSpace = new Phrase("\n");
        PdfPCell clSpace = new PdfPCell(phSpace);

        clSpace.Border  = PdfPCell.NO_BORDER;
        clSpace.Colspan = noOfColumns;
        mainTable.AddCell(clSpace);

        // Sets the gridview column names as table headers.
        for (int i = 0; i < noOfColumns; i++)
        {
            Phrase ph = null;
            if (grdPDF.AutoGenerateColumns)
            {
                ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
            }
            else
            {
                ph = new Phrase(grdPDF.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
            }
            mainTable.AddCell(ph);
        }

        // Reads the gridview rows and adds them to the mainTable
        for (int rowNo = 0; rowNo < noOfRows; rowNo++)
        {
            for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
            {
                if (grdPDF.AutoGenerateColumns)
                {
                    string s  = grdPDF.Rows[rowNo].Cells[columnNo].Text.Trim();
                    Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                    mainTable.AddCell(ph);
                }
                else
                {
                    string s = "";
                    if (grdPDF.Columns[columnNo] is TemplateField)
                    {
                        DataBoundLiteralControl lc = grdPDF.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                        if (lc != null)
                        {
                            s = lc.Text.Trim();
                        }
                        else
                        {
                            for (int i = 0; i < grdPDF.Rows[rowNo].Cells[columnNo].Controls.Count; i++)
                            {
                                if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(TextBox))
                                {
                                    s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as TextBox).Text;
                                }
                                else if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(Label))
                                {
                                    s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as Label).Text;
                                }
                                else if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(System.Web.UI.WebControls.Image))
                                {
                                    s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as System.Web.UI.WebControls.Image).ToolTip;
                                }
                            }
                        }
                        Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                        mainTable.AddCell(ph);
                    }
                    else
                    {
                        s = grdPDF.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                        mainTable.AddCell(ph);
                    }
                }
            }
            mainTable.CompleteRow();
        }

        PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
        //HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
        //pdfFooter.Alignment = Element.ALIGN_CENTER;
        //pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;
        //document.Footer = pdfFooter;
        document.Open();
        document.Add(mainTable);
        document.Close();

        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename= " + Filename + "_" + DateTime.Now.ToString("dd_MMM_yyyy") + ".pdf");
        HttpContext.Current.Response.End();
    }
Example #16
0
        /*
         * (non-Javadoc)
         *
         * @see
         * com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag,
         * java.util.List, com.itextpdf.text.Document)
         */
        public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) {
            try {
			    bool percentage = false;
                String widthValue = null;
                tag.CSS.TryGetValue(HTML.Attribute.WIDTH, out widthValue);
			    if (!tag.CSS.TryGetValue(HTML.Attribute.WIDTH, out widthValue)
                    && !tag.Attributes.TryGetValue(HTML.Attribute.WIDTH, out widthValue)) {
			        widthValue = null;
			    }
			    if(widthValue != null && widthValue.Trim().EndsWith("%")) {
				    percentage = true;
			    }
                int numberOfColumns = 0;
                List<TableRowElement> tableRows = new List<TableRowElement>(currentContent.Count);
                IList<IElement> invalidRowElements = new List<IElement>(1);
                String repeatHeader;
                tag.CSS.TryGetValue(CSS.Property.REPEAT_HEADER, out repeatHeader);
                String repeatFooter;
                tag.CSS.TryGetValue(CSS.Property.REPEAT_FOOTER, out repeatFooter);
                int headerRows = 0;
                int footerRows = 0;
                foreach (IElement e in currentContent) {
                    int localNumCols = 0;
                    if (e is TableRowElement) {
                        TableRowElement tableRowElement = (TableRowElement) e;
                        foreach (HtmlCell cell in tableRowElement.Content) {
                            localNumCols += cell.Colspan;
                        }
                        if (localNumCols > numberOfColumns) {
                            numberOfColumns = localNumCols;
                        }
                        tableRows.Add(tableRowElement);
                        if (repeatHeader != null && Util.EqualsIgnoreCase(repeatHeader, "yes") && tableRowElement.RowPlace.Equals(TableRowElement.Place.HEADER)) {
                            headerRows++;
                        }
                        if (repeatFooter != null && Util.EqualsIgnoreCase(repeatFooter, "yes") && tableRowElement.RowPlace.Equals(TableRowElement.Place.FOOTER)){
                            footerRows++;
                        }
                    } else {
                        invalidRowElements.Add(e);
                    }
                }
                if(repeatFooter == null || !Util.EqualsIgnoreCase(repeatFooter, "yes")) {
                    SortUtil.InsertionSort<TableRowElement>(tableRows, delegate(TableRowElement o1, TableRowElement o2) {
                        return o1.RowPlace.Normal.CompareTo(o2.RowPlace.Normal);
                    });
                } else {
                    SortUtil.InsertionSort<TableRowElement>(tableRows, delegate(TableRowElement o1, TableRowElement o2) {
                        return o1.RowPlace.Repeated.CompareTo(o2.RowPlace.Repeated);
                    });
                }
                PdfPTable table = new PdfPTable(numberOfColumns);
                table.HeaderRows = headerRows+footerRows;
                table.FooterRows = footerRows;
                table.HorizontalAlignment = Element.ALIGN_LEFT;
                table.SplitLate = false;
                TableStyleValues styleValues = SetStyleValues(tag);
                table.TableEvent = new TableBorderEvent(styleValues);
                SetVerticalMargin(table, tag, styleValues, ctx);
                WidenLastCell(tableRows, styleValues.HorBorderSpacing);
                float[] columnWidths = new float[numberOfColumns];
                float[] widestWords = new float[numberOfColumns];
                float[] fixedWidths = new float[numberOfColumns];
                float[] colspanWidestWords = new float[numberOfColumns];
                int[] rowspanValue = new int[numberOfColumns];
                float largestColumn = 0;
                float largestColspanColumn = 0;
                int indexOfLargestColumn = -1;
                int indexOfLargestColspanColumn = -1;

                // Initial fill of the widths arrays
                foreach (TableRowElement row in tableRows) {
                    int column = 0;
                    foreach (HtmlCell cell in row.Content) {
                        // check whether the current column should be skipped due to a
                        // rowspan value of higher cell in this column.
                        // Contribution made by Arnost Havelka (Asseco): added while condition
                        while ((column < numberOfColumns) && (rowspanValue[column] > 0)) {
                            rowspanValue[column] = rowspanValue[column] - 1;
                            ++column;
                        }
                        // sets a rowspan counter for current column (counter not
                        // needed for last column).
                        if (cell.Rowspan > 1 && column != numberOfColumns - 1 && column < rowspanValue.Length) {
                            rowspanValue[column] = cell.Rowspan - 1;
                        }
                        int colspan = cell.Colspan;
                        if (cell.FixedWidth != 0) {
                            float fixedWidth = cell.FixedWidth + GetCellStartWidth(cell);
                            fixedWidth /= colspan;
                            for (int i = 0; i < colspan; i++) {
                                int c = column + i;
                                // Contribution made by Arnost Havelka (Asseco)
                                if (c > numberOfColumns - 1) {
                                    break;
                                }
                                if (fixedWidth > fixedWidths[c]) {
                                    fixedWidths[c] = fixedWidth;
                                    columnWidths[c] = fixedWidth;
                                }
                            }
                        }
                        if (cell.CompositeElements != null) {
                            float[] widthValues = SetCellWidthAndWidestWord(cell);
                            float cellWidth = widthValues[0] / colspan;
                            float widestWordOfCell = widthValues[1] / colspan;
                            for (int i = 0; i < colspan; i++) {
                                int c = column + i;
                                // Contribution made by Arnost Havelka (Asseco)
                                if (c >= numberOfColumns) {
                                    continue;
                                }
                                if (fixedWidths[c] == 0 && cellWidth > columnWidths[c]) {
                                    columnWidths[c] = cellWidth;
                                    if (colspan == 1) {
                                        if (cellWidth > largestColumn) {
                                            largestColumn = cellWidth;
                                            indexOfLargestColumn = c;
                                        }
                                    } else {
                                        if (cellWidth > largestColspanColumn) {
                                            largestColspanColumn = cellWidth;
                                            indexOfLargestColspanColumn = c;
                                        }
                                    }
                                }
                                if (colspan == 1) {
                                    if (widestWordOfCell > widestWords[c]) {
                                        widestWords[c] = widestWordOfCell;
                                    }
                                } else {
                                    if (widestWordOfCell > colspanWidestWords[c]) {
                                        colspanWidestWords[c] = widestWordOfCell;
                                    }
                                }
                            }
                        }
                        if (colspan > 1) {
                            if (LOG.IsLogging(Level.TRACE)) {
                                LOG.Trace(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.COLSPAN), colspan));
                            }
                            column += colspan - 1;
                        }
                        column++;
                    }
                }

                if (indexOfLargestColumn == -1) {
                    indexOfLargestColumn = indexOfLargestColspanColumn;
                    if (indexOfLargestColumn == -1) {
                        indexOfLargestColumn = 0;
                    }

                    for (int column = 0; column < numberOfColumns; column++) {
                        widestWords[column] = colspanWidestWords[column];
                    }
                }
                float outerWidth = GetTableOuterWidth(tag, styleValues.HorBorderSpacing, ctx);
                float initialTotalWidth = GetTableWidth(columnWidths, 0);
    //          float targetWidth = calculateTargetWidth(tag, columnWidths, outerWidth, ctx);
                float targetWidth = 0;
                HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx);
                float max = htmlPipelineContext.PageSize.Width - outerWidth;
                bool tableWidthFixed = false;
                if (tag.Attributes.ContainsKey(CSS.Property.WIDTH) || tag.CSS.ContainsKey(CSS.Property.WIDTH)) {
                    targetWidth = new WidthCalculator().GetWidth(tag, htmlPipelineContext.GetRootTags(), htmlPipelineContext.PageSize.Width);
                    if (targetWidth > max) {
                        targetWidth = max;
                    }
                    tableWidthFixed = true;
                } else if (initialTotalWidth <= max) {
                    targetWidth = initialTotalWidth;
                } else if (null == tag.Parent || (null != tag.Parent && htmlPipelineContext.GetRootTags().Contains(tag.Parent.Name))) {
                    targetWidth = max;
                } else /* this table is an inner table and width adjustment is done in outer table */{
                    targetWidth = GetTableWidth(columnWidths, outerWidth);
                }
                float totalFixedColumnWidth = GetTableWidth(fixedWidths, 0);
                float targetPercentage = 0;
                if (totalFixedColumnWidth == initialTotalWidth) { // all column widths are fixed
                    targetPercentage = targetWidth / initialTotalWidth;
                    if (initialTotalWidth > targetWidth) {
                        for (int column = 0; column < columnWidths.Length; column++) {
                            columnWidths[column] *= targetPercentage;
                        }
                    } else if(tableWidthFixed && targetPercentage != 1){
                        for (int column = 0; column < columnWidths.Length; column++) {
                            columnWidths[column] *= targetPercentage;
                        }
                    }
                } else {
                    targetPercentage = (targetWidth - totalFixedColumnWidth) / (initialTotalWidth - totalFixedColumnWidth);
                    // Reduce width of columns if the columnWidth array + borders +
                    // paddings
                    // is too large for the given targetWidth.
                    if (initialTotalWidth > targetWidth) {
                        float leftToReduce = 0;
                        for (int column = 0; column < columnWidths.Length; column++) {
                            if (fixedWidths[column] == 0) {
                                // Reduce width of the column to its targetWidth, if
                                // widestWord of column still fits in the targetWidth of
                                // the
                                // column.
                                if (widestWords[column] <= columnWidths[column] * targetPercentage) {
                                    columnWidths[column] *= targetPercentage;
                                    // else take the widest word and calculate space
                                    // left to
                                    // reduce.
                                } else {
                                    columnWidths[column] = widestWords[column];
                                    leftToReduce += widestWords[column] - columnWidths[column] * targetPercentage;
                                }
                                // if widestWord of a column does not fit in the
                                // fixedWidth,
                                // set the column width to the widestWord.
                            } else if (fixedWidths[column] < widestWords[column]) {
                                columnWidths[column] = widestWords[column];
                                leftToReduce += widestWords[column] - fixedWidths[column];
                            }
                        }
                        if (leftToReduce != 0) {
                            // Reduce width of the column with the most text, if its
                            // widestWord still fits in the reduced column.
                            if (widestWords[indexOfLargestColumn] <= columnWidths[indexOfLargestColumn] - leftToReduce) {
                                columnWidths[indexOfLargestColumn] -= leftToReduce;
                            } else { // set all columns to their minimum, with the
                                        // widestWord array.
                                for (int column = 0; leftToReduce != 0 && column < columnWidths.Length; column++) {
                                    if (fixedWidths[column] == 0 && columnWidths[column] > widestWords[column]) {
                                        float difference = columnWidths[column] - widestWords[column];
                                        if (difference <= leftToReduce) {
                                            leftToReduce -= difference;
                                            columnWidths[column] = widestWords[column];
                                        } else {
                                            columnWidths[column] -= leftToReduce;
                                            leftToReduce = 0;
                                        }
                                    }
                                }
                                if (leftToReduce != 0) {
                                    // If the table has an insufficient fixed width
                                    // by
                                    // an
                                    // attribute or style, try to enlarge the table
                                    // to
                                    // its
                                    // minimum width (= widestWords array).
                                    float pageWidth = GetHtmlPipelineContext(ctx).PageSize.Width;
                                    if (GetTableWidth(widestWords, outerWidth) < pageWidth) {
                                        targetWidth = GetTableWidth(widestWords, outerWidth);
                                        leftToReduce = 0;
                                    } else {
                                        // If all columnWidths are set to the
                                        // widestWordWidths and the table is still
                                        // to
                                        // wide
                                        // content will fall off the edge of a page,
                                        // which
                                        // is similar to HTML.
                                        targetWidth = pageWidth - outerWidth;
                                        leftToReduce = 0;
                                    }
                                }
                            }
                        }
                        // Enlarge width of columns to fit the targetWidth.
                    } else if (initialTotalWidth < targetWidth) {
                        for (int column = 0; column < columnWidths.Length; column++) {
                            if (fixedWidths[column] == 0) {
                                columnWidths[column] *= targetPercentage;
                            }
                        }
                    }
                }
                try {
                    table.SetTotalWidth(columnWidths);
                    table.LockedWidth = true;
                    table.DefaultCell.Border = Rectangle.NO_BORDER;
                } catch (DocumentException e) {
                    throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
                }
                float? tableHeight = new HeightCalculator().GetHeight(tag, GetHtmlPipelineContext(ctx).PageSize.Height);
                float? tableRowHeight = null;
                if (tableHeight != null && tableHeight > 0)
                    tableRowHeight = tableHeight / tableRows.Count;
                int rowNumber = 0;
                foreach (TableRowElement row in tableRows) {
                    int columnNumber = -1;
                    float? computedRowHeight = null;
                    /*if ( tableHeight != null &&  tableRows.IndexOf(row) == tableRows.Count - 1) {
                        float computedTableHeigt = table.CalculateHeights();
                        computedRowHeight = tableHeight - computedTableHeigt;
                    }*/
                    IList<HtmlCell> rowContent = row.Content;
                    if(rowContent.Count < 1)
                        continue;
                    foreach (HtmlCell cell in rowContent) {
                        IList<IElement> compositeElements = cell.CompositeElements;
                        if (compositeElements != null) {
                            foreach (IElement baseLevel in compositeElements) {
                                if (baseLevel is PdfPTable) {
                                    TableStyleValues cellValues = cell.CellValues;
                                    float totalBordersWidth = cellValues.IsLastInRow ? styleValues.HorBorderSpacing * 2
                                            : styleValues.HorBorderSpacing;
                                    totalBordersWidth += cellValues.BorderWidthLeft + cellValues.BorderWidthRight;
                                    float columnWidth = 0;
                                    for (int currentColumnNumber = columnNumber + 1; currentColumnNumber <= columnNumber + cell.Colspan; currentColumnNumber++){
                                        columnWidth += columnWidths[currentColumnNumber];
                                    }
                                    IPdfPTableEvent tableEvent = ((PdfPTable) baseLevel).TableEvent;
                                    TableStyleValues innerStyleValues = ((TableBorderEvent) tableEvent).TableStyleValues;
                                    totalBordersWidth += innerStyleValues.BorderWidthLeft;
                                    totalBordersWidth += innerStyleValues.BorderWidthRight;
                                    ((PdfPTable) baseLevel).TotalWidth = columnWidth - totalBordersWidth;
                                }
                            }
                        }
                        columnNumber += cell.Colspan;

                        table.AddCell(cell);
                    }
                    table.CompleteRow();
                    if ((computedRowHeight == null || computedRowHeight <= 0) && tableRowHeight != null)
                        computedRowHeight = tableRowHeight;
                    if (computedRowHeight != null && computedRowHeight > 0) {
                        float rowHeight = table.GetRow(rowNumber).MaxHeights;
                        if (rowHeight < computedRowHeight) {
                            table.GetRow(rowNumber).MaxHeights = computedRowHeight.Value;
                        }
                        else if (tableRowHeight != null && tableRowHeight < rowHeight)
                        {
                            tableRowHeight = (tableHeight - rowHeight - rowNumber * tableRowHeight)
                                    / (tableRows.Count - rowNumber - 1);
                        }
                    }
                    rowNumber++;
                }
                if (percentage) {
				    table.WidthPercentage = utils.ParsePxInCmMmPcToPt(widthValue);
				    table.LockedWidth = false;
			    }
                List<IElement> elems = new List<IElement>();
                if (invalidRowElements.Count > 0) {
                    // all invalid row elements taken as caption
                    int i = 0;
                    Tag captionTag = tag.Children[i++];
                    while (!Util.EqualsIgnoreCase(captionTag.Name, HTML.Tag.CAPTION) && i < tag.Children.Count) {
                        captionTag = tag.Children[i];
                        i++;
                    }
                    String captionSideValue;
                    captionTag.CSS.TryGetValue(CSS.Property.CAPTION_SIDE, out captionSideValue);
                    if (captionSideValue != null && Util.EqualsIgnoreCase(captionSideValue, CSS.Value.BOTTOM)) {
                        elems.Add(table);
                        elems.AddRange(invalidRowElements);
                    } else {
                        elems.AddRange(invalidRowElements);
                        elems.Add(table);
                    }
                } else {
                    elems.Add(table);
                }
                return elems;
            } catch (NoCustomContextException e) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
            }
        }
Example #17
0
        private static void CreatePDFReport(Dictionary<DateTime, List<DayReport>> sales)
        {
            //creating the document and setting the path
            var doc = new Document();
            doc.AddTitle("PDF Sales Report");
            string path = "../../PDFReports";
            PdfWriter.GetInstance(doc, new FileStream(path + "\\report.pdf", FileMode.Create));
            PdfPTable table = new PdfPTable(5);

            PdfPCell cell = new PdfPCell();
            PdfPCell firstCell = new PdfPCell();
            firstCell.PaddingLeft = 133;
            firstCell.Phrase = new Phrase("Aggregated Sales Report");
            firstCell.Colspan = 5;
            firstCell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.Aquamarine);
            table.AddCell(firstCell);
            firstCell.PaddingLeft = 2;
            table.CompleteRow();

            foreach (var saleByDate in sales)
            {
                firstCell.Phrase = new Phrase("Date: " + saleByDate.Key.ToShortDateString());
                table.AddCell(firstCell);
                table.CompleteRow();
                cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.Aquamarine);
                Font boldFont = new Font();
                boldFont.Size = 18;
                cell.Phrase = new Phrase("Product", boldFont);
                table.AddCell(cell);
                cell.Phrase = new Phrase("Quantity", boldFont);
                table.AddCell(cell);
                cell.Phrase = new Phrase("Unit Price", boldFont);
                table.AddCell(cell);
                cell.Phrase = new Phrase("Location", boldFont);
                table.AddCell(cell);
                cell.Phrase = new Phrase("Sum", boldFont);
                table.AddCell(cell);
                cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.White);
                var reportsByDay = sales[saleByDate.Key];
                double totalSum = 0;
                foreach (var item in reportsByDay)
                {
                    cell.Phrase = new Phrase(item.ProductName);
                    table.AddCell(cell);
                    cell.Phrase = new Phrase(item.Quantity);
                    table.AddCell(cell);
                    cell.Phrase = new Phrase(item.UnitPrice.ToString());
                    table.AddCell(cell);
                    cell.Phrase = new Phrase(item.MarketName);
                    table.AddCell(cell);
                    cell.Phrase = new Phrase(item.Sum.ToString());
                    table.AddCell(cell);
                    totalSum += item.Sum;
                }
                PdfPCell finalCell = new PdfPCell();
                finalCell.Colspan = 4;
                finalCell.Phrase = new Phrase("Total sum for " + saleByDate.Key.ToShortDateString() + ":");
                finalCell.PaddingLeft = 200;
                table.AddCell(finalCell);
                finalCell.Colspan = 1;
                finalCell.PaddingLeft = 1;
                boldFont.Size = 15;
                finalCell.Phrase = new Phrase(totalSum.ToString(),boldFont);
                table.AddCell(finalCell);
            }
                
            doc.Open();
            doc.Add(table);
            doc.Close();
        }
Example #18
0
        public override void ExecuteResult(ControllerContext context)
        {
            var ctl = new MailingController { UseTitles = titles ?? false, UseMailFlags = useMailFlags ?? false };
            var Response = context.HttpContext.Response;

            IEnumerable<MailingController.MailingInfo> q = null;
            switch (format)
            {
                case "Individual":
                    q = ctl.FetchIndividualList(sort, id);
                    break;
                case "GroupAddress":
                    q = ctl.GroupByAddress(id);
                    break;
                case "Family":
                case "FamilyMembers":
                    q = ctl.FetchFamilyList(sort, id);
                    break;
                case "ParentsOf":
                    q = ctl.FetchParentsOfList(sort, id);
                    break;
                case "CouplesEither":
                    q = ctl.FetchCouplesEitherList(sort, id);
                    break;
                case "CouplesBoth":
                    q = ctl.FetchCouplesBothList(sort, id);
                    break;
                default:
                    Response.Write("unknown format");
                    return;
            }
            if (!q.Any())
            {
                Response.Write("no data found");
                return;
            }
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            var document = new Document(PageSize.LETTER);
            document.SetMargins(50f, 36f, 32f, 36f);
            var w = PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();
            dc = w.DirectContent;

            var cols = new float[] { W, W, W - 25f };
            var t = new PdfPTable(cols);
            t.SetTotalWidth(cols);
            t.HorizontalAlignment = Element.ALIGN_CENTER;
            t.LockedWidth = true;
            t.DefaultCell.Border = PdfPCell.NO_BORDER;
            t.DefaultCell.FixedHeight = H;
            t.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
            t.DefaultCell.PaddingLeft = 8f;
            t.DefaultCell.PaddingRight = 8f;
            t.DefaultCell.SetLeading(2.0f, 1f);

            if (skip > 0)
            {
                var blankCell = new PdfPCell(t.DefaultCell);

                for (int iX = 0; iX < skip; iX++)
                {
                    t.AddCell(blankCell);
                }
            }

            foreach (var m in q)
            {
                var c = new PdfPCell(t.DefaultCell);
                var ph = new Paragraph();
                if (format == "GroupAddress")
                    ph.AddLine(m.LabelName + " " + m.LastName, font);
                else
                    ph.AddLine(m.LabelName, font);
                ph.AddLine(m.Address, font);
                ph.AddLine(m.Address2, font);
                ph.AddLine(m.CityStateZip, font);
                c.AddElement(ph);
                if (usephone)
                {
                    var phone = Util.PickFirst(m.CellPhone.FmtFone("C "), m.HomePhone.FmtFone("H "));
                    var p = new Paragraph();
                    c.PaddingRight = 7f;
                    p.Alignment = Element.ALIGN_RIGHT;
                    p.Add(new Chunk(phone, smfont));
                    p.ExtraParagraphSpace = 0f;
                    c.AddElement(p);
                }
                t.AddCell(c);
            }
            t.CompleteRow();
            document.Add(t);

            document.Close();
        }
    private bool AddPageHeaderToPDFDataTable(ref iTextSharp.text.pdf.PdfPTable mainTable, string sName, string strFilter, int noOfColumns)
    {
        try {
            //'mainTable.LockedWidth = True
            float ReportNameSize      = 11;
            float ApplicationNameSize = 11;
            float FooterTextSize      = 8;
            float HeaderTextSize      = 9;

            float[] arColWidth1 = new float[3];
            arColWidth1[0] = 350;
            arColWidth1[1] = 300;
            arColWidth1[2] = 150;

            // Creates a PdfPTable with 3 columns to hold the header in the exported PDF.
            iTextSharp.text.pdf.PdfPTable HeaderTable = new iTextSharp.text.pdf.PdfPTable(arColWidth1);

            // Creates a phrase to hold the application name at the left hand side of the header.
            Phrase phApplicationName = new Phrase("Peacock", FontFactory.GetFont(SelectedFont, ApplicationNameSize, iTextSharp.text.Font.NORMAL));
            phApplicationName.Font.Color = HeaderFontColor;
            // iTextSharp.text.BaseColor.BLUE

            PdfPCell clApplicationName = new PdfPCell(phApplicationName);
            clApplicationName.Border = PdfPCell.NO_BORDER;
            clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

            // Creates a phrase to show the current date at the right hand side of the header.
            Phrase phDate = new Phrase(DateTime.Now.ToString("dd-MM-yy HH:mm"), FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phDate.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE

            PdfPCell clDate = new PdfPCell(phDate);
            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
            clDate.Border = PdfPCell.NO_BORDER;

            Phrase phName = new Phrase(sName, FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phName.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE

            PdfPCell cellName = new PdfPCell(phName);
            cellName.HorizontalAlignment = Element.ALIGN_LEFT;
            cellName.Border = PdfPCell.NO_BORDER;

            HeaderTable.AddCell(cellName);
            HeaderTable.AddCell(clApplicationName);
            HeaderTable.AddCell(clDate);


            Phrase phFilter = new Phrase(strFilter, FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phFilter.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE
            PdfPCell clFilter = new PdfPCell(phFilter);
            clFilter.Colspan             = 2;
            clFilter.Border              = PdfPCell.NO_BORDER;
            clFilter.HorizontalAlignment = Element.ALIGN_LEFT;


            Phrase phUserid = new Phrase("Elaiya Kumar", FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phUserid.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE
            PdfPCell clUserid = new PdfPCell(phUserid);
            clUserid.HorizontalAlignment = Element.ALIGN_RIGHT;
            clUserid.Border = PdfPCell.NO_BORDER;

            HeaderTable.AddCell(clFilter);
            //rowTabe1.AddCell(EmptyCell())
            HeaderTable.AddCell(clUserid);

            // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
            PdfPCell cellHeader1 = new PdfPCell(HeaderTable);
            cellHeader1.Border  = PdfPCell.NO_BORDER;
            cellHeader1.Colspan = noOfColumns + 1;
            mainTable.AddCell(cellHeader1);


            //mainTable.AddCell(clph)
            Phrase ph = new Phrase();
            // Creates a phrase for a new line.
            Phrase phSpace = new Phrase("\r\n");
            phSpace.Font.Size = 1;

            PdfPCell clSpace = new PdfPCell(phSpace);
            clSpace.Border  = PdfPCell.NO_BORDER;
            clSpace.Colspan = noOfColumns + 1;
            // noOfColumns
            mainTable.AddCell(clSpace);

            mainTable.CompleteRow();

            return(true);
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(true);
    }
    private bool AddPageHeaderToPDFDataTableLogo(ref iTextSharp.text.pdf.PdfPTable mainTable, string sName, int noOfColumns)
    {
        //As iTextSharp.text.pdf.PdfPTable

        try {
            string strPath             = ""; //My.Application.Info.DirectoryPath + "\\syneco_rgb.jpg"
            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(strPath);
            //'mainTable.LockedWidth = True
            float ReportNameSize      = 11;
            float ApplicationNameSize = 11;
            float FooterTextSize      = 8;
            float HeaderTextSize      = 9;


            // Creates a PdfPTable with 3 columns to hold the header in the exported PDF.
            iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(3);

            // Creates a phrase to hold the application name at the left hand side of the header.
            Phrase phApplicationName = new Phrase("Eagle", FontFactory.GetFont(SelectedFont, ApplicationNameSize, iTextSharp.text.Font.NORMAL));
            //phApplicationName.Font = SelectedFont
            //'phApplicationName.Font.SetFamily(iTextSharp.text.Font.FontFamily.COURIER) ' .Font.SetFamily(SelectedFont)
            //'With phApplicationName.Font
            //'    .Size = ApplicationNameSize
            //'    '.SetFamily(iTextSharp.text.Font.FontFamily.COURIER)
            //'    .SetStyle(iTextSharp.text.Font.NORMAL)
            //'End With
            // Creates a PdfPCell which accepts a phrase as a parameter.
            PdfPCell clApplicationName = new PdfPCell(phApplicationName);

            // Sets the border of the cell to zero.
            clApplicationName.Border = PdfPCell.NO_BORDER;

            // Sets the Horizontal Alignment of the PdfPCell to left.
            clApplicationName.HorizontalAlignment = Element.ALIGN_CENTER;

            // Creates a phrase to show the current date at the right hand side of the header.
            Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd-MMM-yyyy"), FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));

            // Creates a PdfPCell which accepts the date phrase as a parameter.
            PdfPCell clDate = new PdfPCell(phDate);

            // Sets the Horizontal Alignment of the PdfPCell to right.
            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;

            // Sets the border of the cell to zero.
            clDate.Border = PdfPCell.NO_BORDER;
            PdfPCell cllogo = new PdfPCell(logo);

            cllogo.HorizontalAlignment = Element.ALIGN_LEFT;

            cllogo.Border = PdfPCell.NO_BORDER;
            headerTable.AddCell(cllogo);

            // Adds the cell which holds the application name to the headerTable.
            headerTable.AddCell(clApplicationName);

            // Adds the cell which holds the date to the headerTable.
            headerTable.AddCell(clDate);

            // Creates a phrase which holds the file name.
            Phrase phHeader = new Phrase(sName, FontFactory.GetFont(SelectedFont, ReportNameSize, iTextSharp.text.Font.BOLD));
            //phHeader.Font = SelectedFont
            //'phHeader.Font.SetFamily(iTextSharp.text.Font.FontFamily.COURIER) '.Font.SetFamily(SelectedFont)
            //'With phHeader.Font
            //'    .Size = ReportNameSize
            //'    '.SetFamily(iTextSharp.text.Font.FontFamily.COURIER)
            //'    .SetStyle(iTextSharp.text.Font.BOLD)
            //'End With

            PdfPCell clHeader = new PdfPCell(phHeader);
            clHeader.Colspan             = noOfColumns;
            clHeader.Border              = PdfPCell.NO_BORDER;
            clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.AddCell(clHeader);

            // Dim phFilter As New Phrase(strFormulaToPrint)

            //With phFilter.Font
            //    .Size = HeaderTextSize ' ReportTextSize
            //    .SetFamily(iTextSharp.text.Font.FontFamily.COURIER)
            //    .SetStyle(iTextSharp.text.Font.NORMAL)
            //End With

            //Dim clFilter As New PdfPCell(phFilter)
            //clFilter.Colspan = noOfColumns
            //clFilter.HorizontalAlignment = Element.ALIGN_LEFT
            //clFilter.Border = PdfPCell.NO_BORDER
            //headerTable.AddCell(clFilter)

            // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
            PdfPCell cellHeader = new PdfPCell(headerTable);
            cellHeader.Border = PdfPCell.NO_BORDER;

            // Sets the column span of the header cell to noOfColumns.
            cellHeader.Colspan = noOfColumns;

            mainTable.AddCell(cellHeader);

            //mainTable.AddCell(clph)
            Phrase ph = new Phrase();
            // Creates a phrase for a new line.
            Phrase phSpace = new Phrase("\r\n");
            phSpace.Font.Size = 1;

            PdfPCell clSpace = new PdfPCell(phSpace);
            clSpace.Border  = PdfPCell.NO_BORDER;
            clSpace.Colspan = noOfColumns;
            // noOfColumns
            mainTable.AddCell(clSpace);

            mainTable.CompleteRow();
            return(true);
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(true);
    }
        protected void OnExportToPDF()
        {
            try
            {
                int noOfColumns = 0, noOfRows = 0;
                noOfColumns = 4;
                noOfRows    = AllSales.Count;

                float HeaderTextSize      = 8;
                float ReportNameSize      = 10;
                float ReportTextSize      = 8;
                float ApplicationNameSize = 7;

                // Creates a PDF document

                document = null;
                document = new Document(PageSize.A4, 0, 0, 15, 5);

                // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
                iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

                // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
                mainTable.HeaderRows = 4;

                // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
                iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

                // Creates a phrase to hold the application name at the left hand side of the header.
                Phrase phApplicationName = new Phrase("Total Month Sales", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

                // Creates a PdfPCell which accepts a phrase as a parameter.
                PdfPCell clApplicationName = new PdfPCell(phApplicationName);
                // Sets the border of the cell to zero.
                clApplicationName.Border = PdfPCell.NO_BORDER;
                // Sets the Horizontal Alignment of the PdfPCell to left.
                clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

                // Creates a phrase to show the current date at the right hand side of the header.
                Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

                // Creates a PdfPCell which accepts the date phrase as a parameter.
                PdfPCell clDate = new PdfPCell(phDate);
                // Sets the Horizontal Alignment of the PdfPCell to right.
                clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
                // Sets the border of the cell to zero.
                clDate.Border = PdfPCell.NO_BORDER;

                // Adds the cell which holds the application name to the headerTable.
                headerTable.AddCell(clApplicationName);
                // Adds the cell which holds the date to the headerTable.
                headerTable.AddCell(clDate);
                // Sets the border of the headerTable to zero.
                headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

                // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
                PdfPCell cellHeader = new PdfPCell(headerTable);
                cellHeader.Border = PdfPCell.NO_BORDER;
                // Sets the column span of the header cell to noOfColumns.
                cellHeader.Colspan = noOfColumns;
                // Adds the above header cell to the table.
                mainTable.AddCell(cellHeader);

                // Creates a phrase which holds the file name.
                Phrase   phHeader = new Phrase("Sales for " + SelectedMonth, FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
                PdfPCell clHeader = new PdfPCell(phHeader);
                clHeader.Colspan             = noOfColumns;
                clHeader.Border              = PdfPCell.NO_BORDER;
                clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
                mainTable.AddCell(clHeader);

                // Creates a phrase for a new line.
                Phrase   phSpace = new Phrase("\n");
                PdfPCell clSpace = new PdfPCell(phSpace);
                clSpace.Border  = PdfPCell.NO_BORDER;
                clSpace.Colspan = noOfColumns;
                mainTable.AddCell(clSpace);

                // Sets the gridview column names as table headers.

                mainTable.AddCell(new Phrase("Seller", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));
                mainTable.AddCell(new Phrase("Product", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));
                mainTable.AddCell(new Phrase("Qty", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));
                mainTable.AddCell(new Phrase("Total", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));

                // Reads the gridview rows and adds them to the mainTable
                foreach (var item in AllSales)
                {
                    {
                        mainTable.AddCell(new Phrase(item.Seller, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                        mainTable.AddCell(new Phrase(item.OrderItems.Name, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                        mainTable.AddCell(new Phrase(item.OrderItems.Quantity.ToString(), FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                        mainTable.AddCell(new Phrase(item.ItemTotal.ToString(), FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                    }
                    // Tells the mainTable to complete the row even if any cell is left incomplete.
                    mainTable.CompleteRow();
                }


                // Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                PdfWriter wri = PdfWriter.GetInstance(document, new System.IO.FileStream("SalesReport.pdf", FileMode.Create));

                document.Open();//Open Document to write


                Paragraph paragraph = new Paragraph("data Exported From DataGridview!");

                document.Add(mainTable);
                //doc.Add(t1);
                document.Close(); //Close document
                //Ope the pdf file just created
                System.Diagnostics.Process.Start(@"SalesReport.pdf");
            }
            catch
            {
                MessageBox.Show("The Pdf could not be created or it could not be opened", "Error PDF", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public static void CreatePDFDocument()
        {
            var document = new Document();
            //string path = Server.MapPath("PDFs");
            PdfWriter.GetInstance(document, new FileStream("../../document.pdf", FileMode.Create));
            document.Open();
            PdfPTable table = new PdfPTable(5);


            //leave a gap before and after the table
            table.SpacingBefore = 20f;
            table.SpacingAfter = 30f;

            using (var db = new CatalogContext())
            {

                //one query to the database
                var sales = db.Sales
                    .Include("Product")
                    .Include("Shop")
                    .OrderBy(x => new { x.Date, x.ProductID, x.ShopID })
                    .ToList();
                DateTime reportDate = new DateTime();
                decimal totalSum = 0;
                foreach (var sale in sales)
                {
                    if (reportDate != sale.Date)
                    {
                        if (totalSum != 0)
                        {
                            table.AddCell("");
                            table.AddCell("");
                            table.AddCell("");
                            table.AddCell(string.Format("Total sum for: {0}", reportDate.ToString("dd-MMM-yyyy")));
                            //PdfPCell total = new PdfPCell(new Phrase(string.Format("Total: {0}", totalSum)));
                            //total.HorizontalAlignment = 1;
                            //total.Colspan = 4;

                            //table.AddCell(total);
                            table.AddCell(string.Format("Total: {0}", totalSum));
                            totalSum = 0;
                        }
                        table.AddCell(string.Format("Date: {0}", sale.Date.ToString("dd-MMM-yyyy")));
                        table.CompleteRow();
                        table.AddCell("Product");
                        table.AddCell("Quantity");
                        table.AddCell("UnitPrice");
                        table.AddCell("Location");
                        table.AddCell("Sum");
                        reportDate = sale.Date;
                    }
                    totalSum += sale.Sum;
                    table.AddCell(sale.Product.ProductName);
                    table.AddCell(sale.Quantity.ToString());
                    table.AddCell(sale.UnitPrice.ToString());
                    table.AddCell(sale.Shop.Name);
                    table.AddCell(sale.Sum.ToString());
                }

                document.Add(table);
                document.Close();
            }
        }
Example #23
0
        public void InformeGenerlaObras()
        {
            Document doc = new Document(PageSize.LETTER, 9, 9, 9, 9);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filepath, FileMode.Create));
            doc.AddTitle("Mi primer PDF");
            doc.AddCreator("Padrón");
            doc.Open();
            Chunk encab = new Chunk("Reporte de obras ", FontFactory.GetFont("COURIER", 18));
            Chunk ap = new Chunk("REPORTE de esta fecha", FontFactory.GetFont("COURIER", 18));

            try
            {              
                doc.Add(new Paragraph(encab));
                doc.Add(new Paragraph(ap));
                //se crea un objeto PdfTable con el numero de columnas del dataGridView 
                PdfPTable datatable = new PdfPTable(5);
                //asignamos algunas propiedades para el diseño del pdf 
                datatable.DefaultCell.Padding = 1;
                float[] headerwidths = new float[5]; // GetTamañoColumnas;
                headerwidths[0] = 1;
                headerwidths[1] = 1;
                headerwidths[2] = 1;
                headerwidths[3] = 1;
                headerwidths[4] = 1;

                datatable.SetWidths(headerwidths);
                datatable.WidthPercentage = 100;
                datatable.DefaultCell.BorderWidth = 1;

                datatable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;//DEFINIMOS EL COLOR DE LAS CELDAS EN EL PDF
                datatable.DefaultCell.BorderColor = iTextSharp.text.BaseColor.BLACK;//DEFINIMOS EL COLOR DE LOS BORDES
                iTextSharp.text.Font fuente = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA);//LA FUENTE DE NUESTRO TEXTO

                Phrase objP = new Phrase("A", fuente);
                datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

                //SE GENERA EL ENCABEZADO DE LA TABLA EN EL PDF 
                objP = new Phrase("Consecutivo", fuente);
                datatable.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(objP);
                objP = new Phrase("Título", fuente);
                datatable.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(objP);
                objP = new Phrase("Núm. de Material", fuente);
                datatable.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(objP);
                objP = new Phrase("Año", fuente);
                datatable.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(objP);
                objP = new Phrase("Tiraje", fuente);
                datatable.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(objP);
                
                datatable.HeaderRows = 2;

                datatable.DefaultCell.BorderWidth = 1;

                //SE GENERA EL CUERPO DEL PDF
                for (int i = 0; i < obrasImprimir.Count; i++)
                {                   
                    objP = new Phrase(obrasImprimir[i].Consecutivo.ToString(), fuente);
                    datatable.AddCell(objP);
                    objP = new Phrase(obrasImprimir[i].Titulo.ToString(), fuente);
                    datatable.AddCell(objP);
                    objP = new Phrase(obrasImprimir[i].NumMaterial.ToString(), fuente);
                    datatable.AddCell(objP);
                    objP = new Phrase(obrasImprimir[i].AnioPublicacion.ToString(), fuente);
                    datatable.AddCell(objP);
                    objP = new Phrase(obrasImprimir[i].Tiraje.ToString(), fuente);
                    datatable.AddCell(objP);                    
                    datatable.CompleteRow();
                }
                doc.Add(datatable);                
                doc.Close();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }            
        }       
        private void ExportToPDF(GridView gvReport, string tenBang, bool LandScape)
        {
            int       noOfColumns = 0, noOfRows = 0;
            DataTable tbl = null;

            if (gvReport.AutoGenerateColumns)
            {
                tbl         = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
                noOfColumns = tbl.Columns.Count;
                noOfRows    = tbl.Rows.Count;
            }
            else
            {
                noOfColumns = gvReport.Columns.Count;
                noOfRows    = gvReport.Rows.Count;
            }

            float ApplicationNameSize = 7;

            // Creates a PDF document

            Document document = null;

            if (LandScape == true)
            {
                // Sets the document to A4 size and rotates it so that the     orientation of the page is Landscape.
                document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
            }
            else
            {
                document = new Document(PageSize.A4, 0, 0, 15, 5);
            }

            // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
            iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

            // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
            mainTable.HeaderRows = 4;
            string   ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "times.TTF");
            BaseFont bf           = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 14, iTextSharp.text.Font.NORMAL);

            // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
            iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

            // Creates a phrase to hold the application name at the left hand side of the header.
            Phrase phApplicationName = new Phrase("Nhom 5 - Library management", text);

            // Creates a PdfPCell which accepts a phrase as a parameter.
            PdfPCell clApplicationName = new PdfPCell(phApplicationName);

            // Sets the border of the cell to zero.
            clApplicationName.Border = PdfPCell.NO_BORDER;
            // Sets the Horizontal Alignment of the PdfPCell to left.
            clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

            // Creates a phrase to show the current date at the right hand side of the header.
            Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

            // Creates a PdfPCell which accepts the date phrase as a parameter.
            PdfPCell clDate = new PdfPCell(phDate);

            // Sets the Horizontal Alignment of the PdfPCell to right.
            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
            // Sets the border of the cell to zero.
            clDate.Border = PdfPCell.NO_BORDER;

            // Adds the cell which holds the application name to the headerTable.
            headerTable.AddCell(clApplicationName);
            // Adds the cell which holds the date to the headerTable.
            headerTable.AddCell(clDate);
            // Sets the border of the headerTable to zero.
            headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

            // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
            PdfPCell cellHeader = new PdfPCell(headerTable);

            cellHeader.Border = PdfPCell.NO_BORDER;
            // Sets the column span of the header cell to noOfColumns.
            cellHeader.Colspan = noOfColumns;
            // Adds the above header cell to the table.
            mainTable.AddCell(cellHeader);

            // Creates a phrase which holds the file name.
            Phrase   phHeader = new Phrase(tenBang, text);
            PdfPCell clHeader = new PdfPCell(phHeader);

            clHeader.Colspan             = noOfColumns;
            clHeader.Border              = PdfPCell.NO_BORDER;
            clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            mainTable.AddCell(clHeader);

            // Creates a phrase for a new line.
            Phrase   phSpace = new Phrase("\n");
            PdfPCell clSpace = new PdfPCell(phSpace);

            clSpace.Border  = PdfPCell.NO_BORDER;
            clSpace.Colspan = noOfColumns;
            mainTable.AddCell(clSpace);

            // Sets the gridview column names as table headers.
            for (int i = 0; i < noOfColumns; i++)
            {
                Phrase ph = null;

                if (gvReport.AutoGenerateColumns)
                {
                    ph = new Phrase(tbl.Columns[i].ColumnName, text);
                }
                else
                {
                    ph = new Phrase(gvReport.Columns[i].HeaderText, text);
                }

                mainTable.AddCell(ph);
            }

            // Reads the gridview rows and adds them to the mainTable
            for (int rowNo = 0; rowNo < noOfRows; rowNo++)
            {
                for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
                {
                    if (gvReport.AutoGenerateColumns)
                    {
                        string s  = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, text);
                        mainTable.AddCell(ph);
                    }
                    else
                    {
                        if (gvReport.Columns[columnNo] is TemplateField)
                        {
                            DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                            string s  = lc.Text.Trim();
                            Phrase ph = new Phrase(s, text);
                            mainTable.AddCell(ph);
                        }
                        else
                        {
                            string s  = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                            Phrase ph = new Phrase(s, text);
                            mainTable.AddCell(ph);
                        }
                    }
                }

                // Tells the mainTable to complete the row even if any cell is left incomplete.
                mainTable.CompleteRow();
            }

            // Gets the instance of the document created and writes it to the output stream of the Response object.
            PdfWriter.GetInstance(document, Response.OutputStream);

            // Creates a footer for the PDF document.

            //HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
            //pdfFooter.Alignment = Element.ALIGN_CENTER;
            //pdfFooter.Border = Rectangle.NO_BORDER;

            //// Sets the document footer to pdfFooter.
            //document.Footer = pdfFooter;
            // Opens the document.
            document.Open();
            // Adds the mainTable to the document.
            document.Add(mainTable);
            // Closes the document.
            document.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
            Response.End();
        }
Example #25
0
        private void BuildHeader(int columns, PdfPTable pdfPTable)
        {
            PdfPCell[] headrowCells = new PdfPCell[columns];
            for (int j = 0; j < columns; j++)
            {
                var col = table.Heads[j];
                headrowCells[j] = new PdfPCell(new Phrase(col.DisplayName, PDFBuilder.DefaultFont))
                {
                    VerticalAlignment = col.VerticalAlignment,
                    HorizontalAlignment = col.HorizontalAlignment
                };
                headwidth[j] = col.Width;
            }
            pdfPTable.Rows.Add(new PdfPRow(headrowCells));

            pdfPTable.CompleteRow();
        }
        public void GetPDFValue(TestRequestClass aTestRequestClass)
        {
            int       noOfColumns = 0, noOfRows = 0;
            DataTable tbl = null;

            if (showGridView.AutoGenerateColumns)
            {
                tbl         = showGridView.DataSource as DataTable; // Gets the DataSource of the GridView Control.
                noOfColumns = tbl.Columns.Count;
                noOfRows    = tbl.Rows.Count;
            }
            else
            {
                noOfColumns = showGridView.Columns.Count;
                noOfRows    = showGridView.Rows.Count;
            }
            float HeaderTextSize      = 8;
            float ReportNameSize      = 10;
            float ReportTextSize      = 8;
            float ApplicationNameSize = 12;

            Document document = null;

            if (LandScape == true)
            {
                document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
            }
            else
            {
                document = new Document(PageSize.A4, 0, 0, 15, 5);
            }
            iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);
            mainTable.HeaderRows = 5;
            iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);
            Phrase phApplicationName =
                new Phrase(
                    "Bill No:" + aTestRequestClass.BillNo + "\nName: " + aTestRequestClass.Name + "\nMobile No: " +
                    aTestRequestClass.MobileNo + "\nDate Of Birth: " + aTestRequestClass.DateofBirth + " ",
                    FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.BOLD));
            PdfPCell clApplicationName = new PdfPCell(phApplicationName);

            clApplicationName.Border = PdfPCell.NO_BORDER;
            clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;
            Phrase aphSpace = new Phrase("\n");

            PdfPCell aclSpace = new PdfPCell(aphSpace);

            aclSpace.Border  = PdfPCell.NO_BORDER;
            aclSpace.Colspan = noOfColumns;
            mainTable.AddCell(aclSpace);


            Phrase phDate = new Phrase("Entry Date: " + DateTime.Now.Date.ToString("dd/MM/yyyy"),
                                       FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
            PdfPCell clDate = new PdfPCell(phDate);

            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
            clDate.Border = PdfPCell.NO_BORDER;
            headerTable.AddCell(clApplicationName);
            headerTable.AddCell(clDate);
            headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

            Phrase phHeader = new Phrase("PATIENT BILL ",
                                         FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
            PdfPCell clHeader = new PdfPCell(phHeader);

            clHeader.Colspan             = noOfColumns;
            clHeader.Border              = PdfPCell.NO_BORDER;
            clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            mainTable.AddCell(clHeader);

            PdfPCell cellHeader = new PdfPCell(headerTable);

            cellHeader.Border  = PdfPCell.NO_BORDER;
            cellHeader.Colspan = noOfColumns;
            mainTable.AddCell(cellHeader);

            Phrase   phSpace = new Phrase("\n");
            PdfPCell clSpace = new PdfPCell(phSpace);

            clSpace.Border  = PdfPCell.NO_BORDER;
            clSpace.Colspan = noOfColumns;
            mainTable.AddCell(clSpace);

            for (int i = 0; i < noOfColumns; i++)
            {
                Phrase ph = null;
                if (showGridView.AutoGenerateColumns)
                {
                    ph = new Phrase(tbl.Columns[i].ColumnName,
                                    FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                }
                else
                {
                    ph = new Phrase(showGridView.Columns[i].HeaderText,
                                    FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                }
                mainTable.AddCell(ph);
            }
            for (int rowNo = 0; rowNo < noOfRows; rowNo++)
            {
                for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
                {
                    if (showGridView.AutoGenerateColumns)
                    {
                        string s  = showGridView.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                        mainTable.AddCell(ph);
                    }
                    else
                    {
                        if (showGridView.Columns[columnNo] is TemplateField)
                        {
                            DataBoundLiteralControl lc =
                                showGridView.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                            string s  = lc.Text.Trim();
                            Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                            mainTable.AddCell(ph);
                        }
                        else
                        {
                            string s  = showGridView.Rows[rowNo].Cells[columnNo].Text.Trim();
                            Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                            mainTable.AddCell(ph);
                        }
                    }
                }
                mainTable.CompleteRow();
            }

            Phrase phHeaderTotal = new Phrase("Total: " + aTestRequestClass.TotalFee + " TK ",
                                              FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
            PdfPCell clHeaderTotal = new PdfPCell(phHeaderTotal);

            clHeaderTotal.Colspan             = noOfColumns;
            clHeaderTotal.Border              = PdfPCell.BOX;
            clHeaderTotal.HorizontalAlignment = Element.ALIGN_RIGHT;
            mainTable.AddCell(clHeaderTotal);

            PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();
            document.Add(mainTable);
            document.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename= PatientBill.pdf");
            Response.End();
        }
Example #27
0
        private void BuilBodyData(PdfPTable pdfPTable)
        {
            DataManager manager = new DataManager(table.DataSource) { NameIgnoreCase = true };

            int columns = table.Heads.Length;

            var indexs = new int[columns];
            for (int i = 0; i < columns; i++)
            {
                var col = table.Heads[i];
                indexs[i] = manager.GetOrdinal(col.BindName);
            }

            for (int i = 0; i < manager.Count; i++)
            {
                manager.Position = i;
                PdfPCell[] rowCells = new PdfPCell[columns];
                int j = 0;
                foreach (var i1 in indexs)
                {
                    var cel = ObjectUtility.Cast<string>(manager.GetValue(i1));

                    rowCells[j] = new PdfPCell((new Phrase(string.IsNullOrEmpty(cel) ? " " : cel, PDFBuilder.DefaultFont)))
                    {
                        PaddingLeft = 4,
                        PaddingRight = 4,
                        UseBorderPadding = true
                    };
                    j++;
                }

                pdfPTable.Rows.Add(new PdfPRow(rowCells));
                pdfPTable.CompleteRow();
            }
            if (!table.FillRows) return;
            var count = table.FillRowCounts - manager.Count;
            if (count > 0)
            {
                FillTabel(count, pdfPTable);
            }
        }
    protected void ExportToPDF(Recordset Recordset, bool LandScape, string StationID)
    {
        try { 

        DataTable MasterCouponTable = new DataTable("MasterCoupon");
        MasterCouponTable.Columns.Add("日期 / 時間", typeof(String));
        MasterCouponTable.Columns.Add("更期", typeof(String));
        MasterCouponTable.Columns.Add("禮券編號", typeof(String));
        MasterCouponTable.Columns.Add("類型", typeof(String));
        MasterCouponTable.Columns.Add("產品", typeof(String));
        MasterCouponTable.Columns.Add("升數", typeof(String));
        MasterCouponTable.Columns.Add("銀碼", typeof(String));
        MasterCouponTable.Columns.Add("車牌", typeof(String));
        while (!(Recordset.Eof))
        {

            //MasterCouponTable.Rows.Add(Recordset.Fields["Present_Date"].Value);
            //MasterCouponTable.Rows.Add(Recordset.Fields["Period"].Value);
            DataRow trow = MasterCouponTable.NewRow();
            trow[0] = Recordset.Fields["Present_Date"].Value;
          //  trow[1] = Recordset.Fields["Period"].Value;
            if (Convert.ToInt32(Recordset.Fields["Period"].Value) == 11)
            {
               // Response.Write("早");
                trow[1] = "早";
            }
            else if (Convert.ToInt32(Recordset.Fields["Period"].Value) == 12)
            {
               // Response.Write("中");
                trow[1] = "中";
            }
            else if (Convert.ToInt32(Recordset.Fields["Period"].Value) == 13)
            {
                //Response.Write("晚");
                trow[1] = "晚";
            }

            trow[2] = Recordset.Fields["Coupon_Number"].Value;
            trow[3] = Recordset.Fields["Coupon_type"].Value;
            trow[4] = Recordset.Fields["Product_Type"].Value;
            trow[5] = String.Format("{0:0.00}", Recordset.Fields["SaleLitre"].Value);
            trow[6] = Recordset.Fields["SaleAmount"].Value;
            trow[7] = Recordset.Fields["Car_ID"].Value;
           

            MasterCouponTable.Rows.Add(trow);
            Recordset.MoveNext();
        }

        GridView gvReport = new GridView();

        gvReport.DataSource = MasterCouponTable;
        gvReport.DataBind();
      

        int noOfColumns = 0, noOfRows = 0;
        DataTable tbl = new DataTable();



        
        tbl = gvReport.DataSource as DataTable;
        noOfColumns = tbl.Columns.Count;
        noOfRows = gvReport.Rows.Count;
        

        float HeaderTextSize = 8;
        float ReportNameSize = 10;
        float ReportTextSize = 8;
        float ApplicationNameSize = 7;

        // Creates a PDF document
        Document document = null;
        FontSelector selector = new FontSelector();
        selector.AddFont(FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12));
        selector.AddFont(FontFactory.GetFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED));

        string fontpath =
        System.Web.HttpContext.Current.Request.PhysicalApplicationPath +
        "include\\fonts\\SimSun.ttf";
        //"simsun.ttf" file was downloaded from web and placed in the folder
        BaseFont bf = BaseFont.CreateFont(fontpath,
                         BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        //create new font based on BaseFont
        Font fontContent = new Font(bf, 11);
        Font fontHeader = new Font(bf, 12);


        Font simsunBold = new Font(bf, 14, Font.BOLD, Color.BLACK);
        Font simsunNormal = new Font(bf, 11, Font.NORMAL, Color.BLACK);
      
        if (LandScape == true)
        {
            // Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
            document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
        }
        else
        {
            document = new Document(PageSize.A4, 0, 0, 15, 5);
        }

        // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
        iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

        // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
        mainTable.HeaderRows = 4;

        // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
        iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

        // Creates a phrase to hold the application name at the left hand side of the header.
        Phrase phApplicationName =  new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL)); 

        // Creates a PdfPCell which accepts a phrase as a parameter.
        PdfPCell clApplicationName = new PdfPCell(phApplicationName);
        // Sets the border of the cell to zero.
        clApplicationName.Border = PdfPCell.NO_BORDER;
        // Sets the Horizontal Alignment of the PdfPCell to left.
        clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

        // Creates a phrase to show the current date at the right hand side of the header.
        Phrase phDate = new Phrase("油站 : " + StationID, simsunNormal);

        // Creates a PdfPCell which accepts the date phrase as a parameter.
        PdfPCell clDate = new PdfPCell(phDate);
        // Sets the Horizontal Alignment of the PdfPCell to right.
        clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
        // Sets the border of the cell to zero.
        clDate.Border = PdfPCell.NO_BORDER;

        // Adds the cell which holds the application name to the headerTable.
        headerTable.AddCell(clApplicationName);
        // Adds the cell which holds the date to the headerTable.
        headerTable.AddCell(clDate);
        // Sets the border of the headerTable to zero.
        headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

        // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
        PdfPCell cellHeader = new PdfPCell(headerTable);
        cellHeader.Border = PdfPCell.NO_BORDER;
        // Sets the column span of the header cell to noOfColumns.
        cellHeader.Colspan = noOfColumns;
        // Adds the above header cell to the table.
        mainTable.AddCell(cellHeader);

        // Creates a phrase which holds the file name.
        Phrase phHeader = new Phrase("禮券驗證系統",simsunNormal);
        PdfPCell clHeader = new PdfPCell(phHeader);
        clHeader.Colspan = noOfColumns;
        clHeader.Border = PdfPCell.NO_BORDER;
        clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
        mainTable.AddCell(clHeader);

        // Creates a phrase for a new line.
        Phrase phSpace = new Phrase("\n");
        PdfPCell clSpace = new PdfPCell(phSpace);
        clSpace.Border = PdfPCell.NO_BORDER;
        clSpace.Colspan = noOfColumns;
        mainTable.AddCell(clSpace);
        PdfPCell hc;
        PdfPCell fc;

        // Sets the gridview column names as table headers.
        for (int i = 0; i < noOfColumns; i++)
        {
            Phrase ph = null;
            

            if (gvReport.AutoGenerateColumns)
            {
                ph = new Phrase(tbl.Columns[i].ColumnName, simsunNormal);
            }
            else
            {
                ph = new Phrase(gvReport.Columns[i].HeaderText, simsunNormal);
                  
            }

            hc = new PdfPCell(new Phrase(ph));
            hc.Top = 5f;
          
            hc.FixedHeight = 20f;
            hc.HorizontalAlignment =1 ;
            hc.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY;// new BaseColor(221,221,221,1);  

           // BaseColor objBaseColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#008000"));
            
            


            mainTable.AddCell(hc);
        }

        // Reads the gridview rows and adds them to the mainTable
        for (int rowNo = 0; rowNo < noOfRows; rowNo++)
        {
            for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
            {
                if (gvReport.AutoGenerateColumns)
                {
                    string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                    Phrase ph = new Phrase(s, simsunNormal);
                    hc = new PdfPCell(new Phrase(ph));
                    hc.Left =2f;
                    mainTable.AddCell(hc);
                }
                else
                {
                    if (gvReport.Columns[columnNo] is TemplateField)
                    {
                        DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                        string s = lc.Text.Trim();
                        Phrase ph = new Phrase(s, simsunNormal);
                        hc = new PdfPCell(new Phrase(ph));
                        hc.Top = 0f;
                        hc.FixedHeight = 7f;
                        hc.HorizontalAlignment = 1;
                        hc.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY;
                        ((Chunk)(hc.Phrase[0])).Font = new iTextSharp.text.Font(((Chunk)(hc.Phrase[0])).Font.Family, 5f);
                        mainTable.AddCell(hc); 
                       
                    }
                    else
                    {
                        string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, simsunNormal);
                        hc = new PdfPCell(new Phrase(ph));
                        hc.Left = 2f;
                        mainTable.AddCell(hc);
                    }
                }
            }

            // Tells the mainTable to complete the row even if any cell is left incomplete.
            mainTable.CompleteRow();
        }

        // Gets the instance of the document created and writes it to the output stream of the Response object.
        PdfWriter.GetInstance(document, Response.OutputStream);

        // Creates a footer for the PDF document.
        HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
        pdfFooter.Alignment = Element.ALIGN_CENTER;
        pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;

        // Sets the document footer to pdfFooter.
        document.Footer = pdfFooter;
        // Opens the document.
        document.Open();
        // Adds the mainTable to the document.
        document.Add(mainTable);
        // Closes the document.
        document.Close();

         
       
            }
        catch(Exception ex)
        { 
            
        }

    }
Example #29
0
        /// <summary>
        /// Exportars the PDF.
        /// </summary>
        /// <param name="TituloPagina">The titulo pagina.</param>
        /// <param name="dtReporte">The dt reporte.</param>
        /// <param name="username">The username.</param>
        /// <param name="filtros">The filtros.</param>
        /// <param name="nombrePNG">The nombre PNG.</param>
        public static void ExportarPDF(string TituloInforme, DataTable dtReporte, string username, string filtros, string nombrePNG)
        {
            itsEvents ev = new itsEvents();

            Persona usuario = new Persona();
            usuario.username = username;
            BLPersona objBLPersona = new BLPersona(usuario);
            objBLPersona.GetPersonaByEntidad();
            usuario = objBLPersona.Data;

            int columnCount = dtReporte.Columns.Count;
            int rowCount = dtReporte.Rows.Count;

            Document documento = new Document(PageSize.A4, 10, 10, 80, 50);
            PdfWriter writerPdf = PdfWriter.GetInstance(documento, HttpContext.Current.Response.OutputStream);
            writerPdf.PageEvent = ev;
            documento.Open();

            string strTitulo = TituloInforme;
            string fecha = DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour.ToString().PadLeft(2, '0') + ":" + DateTime.Now.Minute.ToString().PadLeft(2, '0');

            Font font24B = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 24, Font.BOLD, BaseColor.GRAY);
            Phrase Titulo = new Phrase("EDU@R 2.0", font24B);

            Font font15B = FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLDITALIC);
            ev.tituloReporte = strTitulo;
            ev.fechaReporte = fecha;

            Font font12B = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, Font.NORMAL);
            PdfPTable grdTableEncabezado = new PdfPTable(1);
            grdTableEncabezado.WidthPercentage = 90;
            grdTableEncabezado.AddCell(new PdfPCell(new Phrase("- Usuario: " + usuario.apellido + " " + usuario.nombre, font12B)));
            grdTableEncabezado.CompleteRow();
            grdTableEncabezado.AddCell(new PdfPCell(new Phrase(filtros, font12B)));
            grdTableEncabezado.CompleteRow();
            documento.Add(grdTableEncabezado);

            //valido si mando el nombre de un gráfico
            if (!string.IsNullOrEmpty(nombrePNG))
            {
                //Verifica si existe el archivo
                if (System.IO.File.Exists(nombrePNG))
                {
                    string TmpPath = System.Configuration.ConfigurationManager.AppSettings["oTmpPath"];

                    documento.Add(new Paragraph(""));
                    Image grafico = Image.GetInstance(nombrePNG);
                    grafico.ScalePercent(50, 50);
                    grafico.Alignment = Element.ALIGN_CENTER;
                    if (grafico != null)
                        documento.Add(grafico);
                    documento.Add(new Paragraph(""));
                }
            }

            PdfPTable grdTable = new PdfPTable(columnCount);
            Font LetraTituloTabla = FontFactory.GetFont(FontFactory.HELVETICA, 9, Font.BOLDITALIC, BaseColor.BLUE);
            float[] espacios = new float[columnCount];
            for (int i = 0; i < columnCount; i++)
            {
                espacios[i] = 80 / columnCount;
            }

            grdTable.SetWidths(espacios);
            grdTable.WidthPercentage = 90;

            //Creamos las cabeceras de la tabla
            //Adicionamos las cabeceras a la tabla
            foreach (DataColumn columna in dtReporte.Columns)
            {
                grdTable.AddCell(new PdfPCell(new Phrase(columna.ColumnName.ToUpperInvariant(), LetraTituloTabla)));
            }

            Font LetraDefecto = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL);

            grdTable.CompleteRow();

            grdTable.HeaderRows = 1;

            foreach (DataRow fila in dtReporte.Rows)
            {
                for (int i = 0; i < columnCount; i++)
                {
                    string dato = fila[i].ToString();
                    if (fila[i].GetType().Name == "DateTime")
                        dato = Convert.ToDateTime(fila[i].ToString()).ToShortDateString();
                    grdTable.AddCell(new Phrase(HttpUtility.HtmlDecode(dato), LetraDefecto));
                }
                grdTable.CompleteRow();
            }

            //Cerramos el Documento
            documento.Add(grdTable);
            documento.Close();

            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + strTitulo.Trim().Replace(" ", string.Empty) + "-" + fecha.Replace(' ', '_').Trim() + ".pdf");
            HttpContext.Current.Response.Flush();//HttpContext.Current.Response.End();
        }
Example #30
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            dt = Util.Now;

            doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64);
            var w = PdfWriter.GetInstance(doc, Response.OutputStream);

            var roles = DbUtil.Db.CurrentRoles();
            var i = (from o in DbUtil.Db.Organizations
                     where o.LimitToRole == null || roles.Contains(o.LimitToRole)
                     where o.OrganizationId == orgid
                     select new
                     {
                         o.OrganizationName,
                         o.LeaderName,
                         o.FirstMeetingDate
                     }).SingleOrDefault();

            w.PageEvent = new HeadFoot
            {
                HeaderText = "Recent Attendee Report: {0} - {1} ({2})".Fmt(
                    i.OrganizationName, i.LeaderName, i.FirstMeetingDate.HasValue ? "since " + i.FirstMeetingDate.FormatDate() : "no First Meeting Date set"),
                FooterText = "Recent Attendee Report"
            };
            doc.Open();

            var q = Attendees(orgid.Value);

            if (!orgid.HasValue || i == null || q.Count() == 0)
                doc.Add(new Phrase("no data"));
            else
            {
                var mt = new PdfPTable(1);
                mt.SetNoPadding();
                mt.HeaderRows = 1;

                float[] widths = new float[] { 4f, 6f, 7f, 2.6f, 2f, 3f };
                var t = new PdfPTable(widths);
                t.DefaultCell.Border = PdfPCell.NO_BORDER;
                t.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_TOP;
                t.DefaultCell.SetLeading(2.0f, 1f);
                t.WidthPercentage = 100;

                t.AddHeader("Name", boldfont);
                t.AddHeader("Address", boldfont);
                t.AddHeader("Phone/Email", boldfont);
                t.AddHeader("Last Att.", boldfont);
                t.AddHeader("Birthday", boldfont);
                t.AddHeader("Status", boldfont);
                mt.AddCell(t);

                var color = BaseColor.BLACK;
                bool? v = null;

                foreach (var p in q)
                {
                    if (color == BaseColor.WHITE)
                        color = new GrayColor(240);
                    else
                        color = BaseColor.WHITE;

                    t = new PdfPTable(widths);
                    t.SetNoBorder();
                    t.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
                    t.DefaultCell.BackgroundColor = color;

                    if (v != p.visitor)
                        t.Add("             ------ {0} ------".Fmt(p.visitor == true ? "Guests and Previous Members" : "Members"), 6, bigboldfont);
                    v = p.visitor;

                    t.Add(p.Name, font);

                    var ph = new Paragraph();
                    ph.AddLine(p.Address, font);
                    ph.AddLine(p.Address2, font);
                    ph.AddLine(p.CSZ, font);
                    t.AddCell(ph);

                    ph = new Paragraph();
                    ph.AddLine(p.HomePhone.FmtFone("H"), font);
                    ph.AddLine(p.CellPhone.FmtFone("C"), font);
                    ph.AddLine(p.Email, font);
                    t.AddCell(ph);

                    t.Add(p.LastAttend.FormatDate(), font);
                    t.Add(p.Birthday, font);
                    t.Add(p.AttendType, font);
                    t.CompleteRow();

                    t.Add("", font);
                    t.Add(p.AttendStr, 4, monofont);
                    t.AddRight("{0:n1}{1}".Fmt(p.AttendPct, p.AttendPct.HasValue ? "%" : ""), font);

                    mt.AddCell(t);
                }
                doc.Add(mt);
            }
            doc.Close();
        }
Example #31
0
        protected void lnkBtnRelatorio_Click(object sender, EventArgs e)
        {
            try
            {
                int       noOfColumns = 0, noOfRows = 0;
                DataTable tbl = null;

                if (grid.AutoGenerateColumns)
                {
                    tbl         = grid.DataSource as DataTable; // Gets the DataSource of the GridView Control.
                    noOfColumns = tbl.Columns.Count;
                    noOfRows    = tbl.Rows.Count;
                }
                else
                {
                    noOfColumns = grid.Columns.Count - 2;
                    noOfRows    = grid.Rows.Count;
                }



                float HeaderTextSize      = 8;
                float ReportNameSize      = 10;
                float ReportTextSize      = 8;
                float ApplicationNameSize = 7;

                // Creates a PDF document

                Document document = null;

                document = new Document(PageSize.A4, 0, 0, 15, 5);


                // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
                iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

                // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
                mainTable.HeaderRows = 4;

                // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
                iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

                // Creates a phrase to hold the application name at the left hand side of the header.
                Phrase phApplicationName = new Phrase("Cadastro dos Funcionarios", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

                // Creates a PdfPCell which accepts a phrase as a parameter.
                PdfPCell clApplicationName = new PdfPCell(phApplicationName);
                // Sets the border of the cell to zero.
                clApplicationName.Border = PdfPCell.NO_BORDER;
                // Sets the Horizontal Alignment of the PdfPCell to left.
                clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

                // Creates a phrase to show the current date at the right hand side of the header.
                Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

                // Creates a PdfPCell which accepts the date phrase as a parameter.
                PdfPCell clDate = new PdfPCell(phDate);
                // Sets the Horizontal Alignment of the PdfPCell to right.
                clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
                // Sets the border of the cell to zero.
                clDate.Border = PdfPCell.NO_BORDER;

                // Adds the cell which holds the application name to the headerTable.
                headerTable.AddCell(clApplicationName);
                // Adds the cell which holds the date to the headerTable.
                headerTable.AddCell(clDate);
                // Sets the border of the headerTable to zero.
                headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

                // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
                PdfPCell cellHeader = new PdfPCell(headerTable);
                cellHeader.Border = PdfPCell.NO_BORDER;
                // Sets the column span of the header cell to noOfColumns.
                cellHeader.Colspan = noOfColumns;
                // Adds the above header cell to the table.
                mainTable.AddCell(cellHeader);

                // Creates a phrase which holds the file name.
                Phrase   phHeader = new Phrase("Funcionarios Cadastrados", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
                PdfPCell clHeader = new PdfPCell(phHeader);
                clHeader.Colspan             = noOfColumns;
                clHeader.Border              = PdfPCell.NO_BORDER;
                clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
                mainTable.AddCell(clHeader);

                // Creates a phrase for a new line.
                Phrase   phSpace = new Phrase("\n");
                PdfPCell clSpace = new PdfPCell(phSpace);
                clSpace.Border  = PdfPCell.NO_BORDER;
                clSpace.Colspan = noOfColumns;
                mainTable.AddCell(clSpace);

                // Sets the gridview column names as table headers.
                for (int i = 0; i < noOfColumns; i++)
                {
                    Phrase ph = null;

                    if (grid.AutoGenerateColumns)
                    {
                        ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                    }
                    else
                    {
                        ph = new Phrase(grid.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                    }

                    mainTable.AddCell(ph);
                }

                // Reads the gridview rows and adds them to the mainTable
                for (int rowNo = 0; rowNo < noOfRows; rowNo++)
                {
                    for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
                    {
                        if (grid.AutoGenerateColumns)
                        {
                            string s = grid.Rows[rowNo].Cells[columnNo].Text.Trim();
                            if (s.Equals("&nbsp;"))
                            {
                                s = "";
                            }
                            Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                            mainTable.AddCell(ph);
                        }
                        else
                        {
                            if (grid.Columns[columnNo] is TemplateField)
                            {
                                DataBoundLiteralControl lc = grid.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                                string s = lc.Text.Trim();
                                if (s.Equals("&nbsp;"))
                                {
                                    s = "";
                                }
                                Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                                mainTable.AddCell(ph);
                            }
                            else
                            {
                                string s = grid.Rows[rowNo].Cells[columnNo].Text.Trim();
                                if (s.Equals("&nbsp;"))
                                {
                                    s = "";
                                }
                                Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                                mainTable.AddCell(ph);
                            }
                        }
                    }

                    // Tells the mainTable to complete the row even if any cell is left incomplete.
                    mainTable.CompleteRow();
                }

                // Gets the instance of the document created and writes it to the output stream of the Response object.
                PdfWriter.GetInstance(document, Response.OutputStream);

                //// Creates a footer for the PDF document.
                //HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
                //pdfFooter.Alignment = Element.ALIGN_CENTER;
                //pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;

                //// Sets the document footer to pdfFooter.
                //document.Footer = pdfFooter;
                // Opens the document.
                document.Open();
                // Adds the mainTable to the document.
                document.Add(mainTable);
                // Closes the document.
                document.Close();

                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment; filename=Relatorio de Funcionarios de " + DateTime.Now.ToLongDateString() + ".pdf");
                Response.End();
            }
            catch { }
        }
 public void GenerarDocumento(Document document)
 {
     //se crea un objeto PdfTable con el numero de columnas del dataGridView
     PdfPTable datatable = new PdfPTable(dgRegistroKARDEX.ColumnCount);
     //asignanos algunas propiedades para el diseño del pdf
     datatable.DefaultCell.Padding = 1;
     float[] headerwidths = GetTamañoColumnas(dgRegistroKARDEX);
     datatable.SetWidths(headerwidths);
     datatable.WidthPercentage = 80;
     datatable.DefaultCell.BorderWidth = 1;
     datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
     //SE GENERA EL ENCABEZADO DE LA TABLA EN EL PDF
     for (int i = 0; i < dgRegistroKARDEX.ColumnCount; i++)
     {
         datatable.AddCell(dgRegistroKARDEX.Columns[i].HeaderText);
     }
     datatable.HeaderRows = 1;
     datatable.DefaultCell.BorderWidth = 1;
     //SE GENERA EL CUERPO DEL PDF
     for (int i = 0; i < dgRegistroKARDEX.RowCount - 1; i++)
     {
         for (int j = 0; j < dgRegistroKARDEX.ColumnCount; j++)
         {
             datatable.AddCell(dgRegistroKARDEX[j, i].Value.ToString());
         }
         datatable.CompleteRow();
     }
     //SE AGREGAR LA PDFPTABLE AL DOCUMENTO
     document.Add(datatable);
 }