예제 #1
0
파일: PdfStamper.cs 프로젝트: dtommasi/PEM
        public static void CreaPDF(string txtHTML, string path, EmendamentiDto em, string urlPEM)
        {
            try
            {
                if (string.IsNullOrEmpty(txtHTML))
                {
                    throw new Exception("Nessun testo da inserire nel PDF.");
                }
                if (string.IsNullOrEmpty(path))
                {
                    throw new Exception("Percorso del PDF non valido.");
                }
                //Create a byte array that will eventually hold our final PDF
                byte[] bytes;

                //Boilerplate iTextSharp setup here
                //Create a stream that we can write to, in this case a MemoryStream
                using (var ms = new MemoryStream())
                {
                    //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
                    using (var doc = new Document(new Rectangle(600, 800), 20, 20, 20, 60))
                    {
                        //Create a writer that's bound to our PDF abstraction and our stream
                        using (var writer = PdfWriter.GetInstance(doc, ms))
                        {
                            var ev = new ITextEvents {
                                EM = em
                            };
                            writer.PageEvent = ev;
                            //Open the document for writing
                            doc.Open();

                            //XMLWorker also reads from a TextReader and not directly from a string
                            var hDocument = new HtmlDocument
                            {
                                OptionWriteEmptyNodes = true,
                                OptionAutoCloseOnEnd  = true
                            };
                            hDocument.LoadHtml(txtHTML);
                            txtHTML = hDocument.DocumentNode.WriteTo();

                            try
                            {
                                //Parse the HTML
                                using (var srHtml = new StringReader(txtHTML))
                                {
                                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                                }
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    using (var srHtml =
                                               new StringReader(txtHTML.Replace("<ol", "<div").Replace("</ol>", "</div>")))
                                    {
                                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                                    }
                                }
                                catch (Exception ex2)
                                {
                                    var linkPemError = $"{urlPEM}/{em.UIDEM}";
                                    using (var srHtml_ERR = new StringReader(
                                               $"<html><body>ATTENZIONE, Si è verificato un problema durante la generazione del pdf di questo EM/SUBEM: {ex2.Message} <br/> L'emendamento/subemendamento è stato comunque correttamente acquisito dal sistema ed è visualizzabile attraverso la piattaforma PEM all'indirizzo <a href='{linkPemError}'>{linkPemError}</a></body></html>")
                                           )
                                    {
                                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml_ERR);
                                    }
                                }
                            }

                            doc.Close();
                        }
                    }

                    //After all of the PDF "stuff" above is done and closed but **before** we
                    //close the MemoryStream, grab all of the active bytes from the stream
                    bytes = ms.ToArray();
                }

                //Now we just need to do something with those bytes.
                //Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them.
                //You could also write the bytes to a database in a varbinary() column (but please don't) or you
                //could pass them to another function for further PDF processing.
                //var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
                File.WriteAllBytes(path, bytes);


                //**********************************************************************************
                //MAX: ELIMINO LA FUFFA
                //**********************************************************************************
                //try
                //{
                //    if (File.Exists(path)) File.Delete(path);
                //}
                //catch (Exception ex)
                //{
                //    Log.Error("[CreaPDF]: Impossibile eliminare il file temporaneo " + path + " -->", ex);
                //}

                //**********************************************************************************
            }
            catch (Exception ex)
            {
                Log.Error("CreaPDF Error-->", ex);
                throw ex;
            }
        }
예제 #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string num_sp  = Request.QueryString["sp"].ToString();
            string n_file  = "/" + num_sp.Trim() + ".pdf";
            string pdfPath = Server.MapPath(@"~\PDFs\") + n_file;

            using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
            {
                using (Document pdfDoc = new Document(PageSize.LETTER))
                {
                    try
                    {
                        PdfWriter   pdfWriter        = PdfWriter.GetInstance(pdfDoc, msReport);
                        ITextEvents PageEventHandler = new ITextEvents();
                        pdfWriter.PageEvent = PageEventHandler;
                        pdfDoc.Open();
                        PdfPTable tabla1 = new PdfPTable(1);
                        tabla1.WidthPercentage = 100;
                        PdfPCell celda_vaciaSinborde = new PdfPCell(new Phrase(" ", FontFactory.GetFont(FontFactory.HELVETICA, 8)));
                        celda_vaciaSinborde.BorderWidth = 0;
                        Sp_datos sp_datos_class = Base.sp_encabezado(num_sp);
                        PdfPCell celda1         = new PdfPCell(new Phrase("Solicitud de pedido N° " + num_sp + " (" + sp_datos_class.estado_sp + ")", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        celda1.HorizontalAlignment = Element.ALIGN_LEFT;
                        celda1.BorderWidth         = 0;
                        celda1.BorderWidthBottom   = 0.5f;
                        celda1.BorderWidthTop      = 0.5f;
                        tabla1.AddCell(celda1);
                        tabla1.AddCell(celda_vaciaSinborde);
                        pdfDoc.Add(tabla1);
                        //ENCABEZADO
                        PdfPTable tabla2 = Base.encabezado_sp_pdf(sp_datos_class);
                        pdfDoc.Add(tabla2);
                        //DETALLE PRODUCTOS
                        PdfPTable tabla3 = Base.detalle_sp_pdf(num_sp);
                        pdfDoc.Add(tabla3);
                        //COMENTARIOS - TIPOCAMBIO
                        PdfPTable tabla4 = new PdfPTable(1);
                        tabla4.WidthPercentage = 100;
                        PdfPCell celda79 = new PdfPCell(new Phrase(sp_datos_class.nota_libre, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
                        celda79.HorizontalAlignment = Element.ALIGN_LEFT;
                        celda79.BorderWidth         = 0;
                        tabla4.AddCell(celda79);
                        pdfDoc.Add(tabla4);
                        PdfPTable tabla5 = new PdfPTable(1);
                        tabla5.WidthPercentage = 100;
                        PdfPCell celda80 = new PdfPCell(new Phrase("Tipo de Cambio: " + sp_datos_class.valor_t_cambio, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
                        celda80.HorizontalAlignment = Element.ALIGN_LEFT;
                        celda80.BorderWidth         = 0;
                        tabla5.AddCell(celda80);
                        pdfDoc.Add(tabla5);
                        pdfDoc.NewPage();
                        pdfDoc.Close();
                        WebClient client = new WebClient();
                        Byte[]    buffer = client.DownloadData(pdfPath);
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-length", buffer.Length.ToString());
                        Response.BinaryWrite(buffer);
                        Response.Flush();
                        Response.End();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
예제 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Document doc = new Document();

            try
            {
                bool          enviar_correo = false;
                string        id_cotizacion = "";
                DBUtil        db            = new DBUtil();
                usuarioEntity vend          = new usuarioEntity();
                vend = (usuarioEntity)(Session["usuario"]);
                if (vend != null)
                {
                    if (Request.QueryString["idctz"] != null)
                    {
                        id_cotizacion = Request.QueryString["idctz"].ToString();
                    }
                    if (Request.QueryString["cr"] != null)
                    {
                        if (Request.QueryString["cr"].ToString() == "SI")
                        {
                            enviar_correo = true;
                        }
                    }

                    if (id_cotizacion != "")
                    {
                        ctz_cotizacionEntity ctz = new ctz_cotizacionEntity();
                        ctz.id_cotizacion = int.Parse(id_cotizacion);

                        if (ctz_cotizacionBO.encontrar(ref ctz) == "OK")
                        {
                            if (ctz.cod_vendedor == vend.cod_usuario)
                            {
                                //
                                string path       = Server.MapPath("COTIZACIONES");
                                string nombre_pdf = "cotizacion_" + vend.cod_usuario + "_" + id_cotizacion;
                                string n_file     = "/" + nombre_pdf.Replace(",", "").Replace(".", "").Replace(" ", "").Replace("/", "") + ".pdf";
                                try
                                {
                                    System.IO.File.Delete(path + n_file);
                                }
                                catch (System.IO.IOException ex)
                                {
                                }
                                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path + n_file, FileMode.Create));
                                try
                                {
                                    ITextEvents PageEventHandler = new ITextEvents()
                                    {
                                        ImageFooter = iTextSharp.text.Image.GetInstance(Server.MapPath("~/COTIZADOR/LOGOS/banner.jpg"))
                                    };
                                    writer.PageEvent = PageEventHandler;

                                    DataTable dt_detalle = new DataTable();
                                    dt_detalle = db.consultar("select * from V_CTZ_COTIZACION_DET where id_cotizacion = " + ctz.id_cotizacion + " order by nom_categ, nom_producto");

                                    // CONFIGURACION PDF
                                    //doc.SetPageSize(PageSize.LEGAL.Rotate());
                                    doc.SetMargins(10f, 10f, 20f, 200f);
                                    doc.AddTitle("Cotización Soprodi");
                                    doc.AddCreator(vend.nombre_);
                                    // ------------ FONTS
                                    doc.Open();

                                    // ENCABEZADO (2 Logos y el encabezado superior).
                                    PdfPTable tabla_encabezado = new PdfPTable(3);
                                    tabla_encabezado.LockedWidth = true;
                                    tabla_encabezado.TotalWidth  = 575f;
                                    float[] widths_enc = new float[] { 100f, 375f, 100f };
                                    tabla_encabezado.SetWidths(widths_enc);

                                    // AGREGAR LOGOS
                                    iTextSharp.text.Image imagen  = creaimagen("~/COTIZADOR/LOGOS/dereyes.png", 80, "c");
                                    iTextSharp.text.Image imagen2 = creaimagen("~/COTIZADOR/LOGOS/soprodi.jpg", 80, "c");

                                    // PRIMERA IMAGEN
                                    agregaimagen(ref tabla_encabezado, imagen, 0, "c");
                                    // ************************************************

                                    // ENCABEZADO (DATOS SOPRODI)
                                    PdfPTable titulo = new PdfPTable(1);
                                    titulo.WidthPercentage = 100;
                                    agregacelda(ref titulo, "COTIZACION DE PRODUCTOS", titulo_font, 0, "c");
                                    //agregacelda(ref titulo, "SOCIEDAD PRODUCTORA Y DISTRIBUIDORA S.A", titulo_font, 0, "c");
                                    //agregacelda(ref titulo, "SOPRODI S.A", titulo_font, 0, "c");
                                    //agregacelda(ref titulo, "IMPORTACIONES, EXPORTACIONES,", fuente_negrita, 0, "c");
                                    //agregacelda(ref titulo, "DISTRIBUCIÓN DE PRODUCTOS AGRÍCOLAS", fuente_negrita, 0, "c");
                                    //agregacelda(ref titulo, "TRANSPORTES DE CARGA TERRESTRE,", fuente_negrita, 0, "c");
                                    //agregacelda(ref titulo, "ALMACENAJES, ABARROTES, TRANSPORTE MARÍTIMO Y DE CABOTAJE DE CARGA", fuente_negrita, 0, "c");
                                    //agregacelda(ref titulo, "Casa Matriz: Paradero 9 1/2, Camino Troncal San Pedro - Quillota - Casilla 7 Correo Quillota", fuente_normal, 0, "c");
                                    //agregacelda(ref titulo, "Fono: (56 33) 2292500 - Fax: (56 33) 2318139", fuente_normal, 0, "c");
                                    //agregacelda(ref titulo, "Email: [email protected]", fuente_normal, 0, "c");
                                    agregatabla(ref tabla_encabezado, titulo, 0, "c");
                                    // ***********************************************************************************************************************************************

                                    // SEGUNDA IMAGEN Y NUMERO DE COTIZACION
                                    PdfPTable columna3 = new PdfPTable(1);
                                    columna3.WidthPercentage = 100;
                                    agregaimagen(ref columna3, imagen2, 0, "c");
                                    agregacelda(ref columna3, " ", titulo_font, 0, "c");

                                    PdfPTable td_columna3 = new PdfPTable(1);
                                    td_columna3.WidthPercentage = 100;

                                    agregacelda(ref td_columna3, "COTIZACIÓN #", titulo_font, 0, "c");
                                    agregacelda(ref td_columna3, "***", titulo_font, 0, "c");
                                    agregacelda(ref td_columna3, "Válido hasta", fuente_normal, 0, "c");
                                    agregacelda(ref td_columna3, DateTime.Now.AddDays(2).ToString("dd/MM/yyyy"), fuente_negrita, 0, "c");
                                    agregatabla(ref columna3, td_columna3, 1, "c");

                                    agregatabla(ref tabla_encabezado, columna3, 0, "c");
                                    // *****************************************************************************

                                    // Insertamos el encabezado
                                    doc.Add(tabla_encabezado);
                                    doc.Add(Chunk.NEWLINE);
                                    SaltoLinea(ref doc);

                                    // SUB ENCABEZADO
                                    PdfPTable tabla_subencabezado = new PdfPTable(1);
                                    tabla_subencabezado.WidthPercentage = 100;

                                    PdfPTable td_tabla_subencabezado = new PdfPTable(6);
                                    td_tabla_subencabezado.TotalWidth = 575f;
                                    float[] widthsubencabezado = new float[] { 50f, 10f, 170f, 50f, 10f, 170f };
                                    td_tabla_subencabezado.SetWidths(widthsubencabezado);

                                    agregacelda(ref td_tabla_subencabezado, "Señor(es)", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, ":", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, "NOMBRE_CLIENTE", fuente_normal, 0, "i");

                                    agregacelda(ref td_tabla_subencabezado, "R.U.T", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, ":", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, "RUT_CLIENTE", fuente_normal, 0, "i");

                                    agregacelda(ref td_tabla_subencabezado, "Giro", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, ":", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, "GIRO_CLIENTE", fuente_normal, 0, "i");

                                    agregacelda(ref td_tabla_subencabezado, "Comuna", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, ":", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, "COMUNA_CLIENTE", fuente_normal, 0, "i");

                                    agregacelda(ref td_tabla_subencabezado, "Dirección", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, ":", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, "DIRECCION_CLIENTE", fuente_normal, 0, "i");

                                    agregacelda(ref td_tabla_subencabezado, "Ciudad", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, ":", fuente_negrita, 0, "i");
                                    agregacelda(ref td_tabla_subencabezado, "CIUDAD_CLIENTE", fuente_normal, 0, "i");

                                    agregatabla(ref tabla_subencabezado, td_tabla_subencabezado, 1, "i");

                                    doc.Add(tabla_subencabezado);

                                    // SUB ENCABEZADO 2
                                    PdfPTable tabla_subencabezado2 = new PdfPTable(3);
                                    tabla_subencabezado2.WidthPercentage = 100;

                                    PdfPTable td_sub2_1 = new PdfPTable(1);
                                    agregacelda(ref td_sub2_1, "FECHA DE EMISION", fuente_negrita, 0, "c");
                                    agregacelda(ref td_sub2_1, ctz.fecha_creacion.ToString("dd/MM/yyyy"), fuente_normal, 0, "c");
                                    agregatabla(ref tabla_subencabezado2, td_sub2_1, 1, "i");


                                    PdfPTable td_sub2_2 = new PdfPTable(1);
                                    agregacelda(ref td_sub2_2, "PLAZO DE PAGO", fuente_negrita, 0, "c");
                                    agregacelda(ref td_sub2_2, "CONVENIDO ENTRE LAS PARTES", fuente_normal, 0, "c");
                                    agregatabla(ref tabla_subencabezado2, td_sub2_2, 1, "i");

                                    PdfPTable td_sub2_5 = new PdfPTable(1);
                                    agregacelda(ref td_sub2_5, "VENDEDOR", fuente_negrita, 0, "c");
                                    agregacelda(ref td_sub2_5, vend.nombre_, fuente_normal, 0, "c");
                                    agregatabla(ref tabla_subencabezado2, td_sub2_5, 1, "i");

                                    doc.Add(tabla_subencabezado2);
                                    // ****************************************************************************

                                    SaltoLinea(ref doc);

                                    // RECORRER DETALLE// DETALLE
                                    int contador_bodegas = 0;
                                    int num_columnas     = 2;
                                    for (int i = 1; i <= 3; i++)
                                    {
                                        if (dt_detalle.Rows[0]["cod_bodega_" + i].ToString() != "NO")
                                        {
                                            contador_bodegas++;
                                            num_columnas = num_columnas + 5;
                                        }
                                    }
                                    PdfPTable tablaOTZ = new PdfPTable(num_columnas);
                                    tablaOTZ.LockedWidth = true;
                                    tablaOTZ.TotalWidth  = 575f;
                                    float[] widthtablaOTZ = new float[] { 0f };
                                    if (num_columnas == 7)
                                    {
                                        widthtablaOTZ = new float[] { 25f, 200f, 86f, 86f, 86f, 86f, 86f };
                                    }
                                    else if (num_columnas == 12)
                                    {
                                        widthtablaOTZ = new float[] { 25f, 200f, 43f, 43f, 43f, 43f, 43f, 43f, 43f, 43f, 43f, 43f };
                                    }
                                    else
                                    {
                                        widthtablaOTZ = new float[] { 25f, 60f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f, 29f };
                                    }
                                    tablaOTZ.SetWidths(widthtablaOTZ);
                                    //tablaOTZ.WidthPercentage = 100;

                                    // COLSPANS SUPERIORES
                                    PdfPCell td1 = new PdfPCell(new Phrase(" ", fuente_negrita));
                                    td1.Colspan     = 2;
                                    td1.BorderWidth = 1;
                                    tablaOTZ.AddCell(td1);

                                    for (int i = 1; i <= contador_bodegas; i++)
                                    {
                                        PdfPCell td2 = new PdfPCell(new Phrase(dt_detalle.Rows[0]["bod" + i].ToString(), fuente_negrita));
                                        td2.Colspan     = 5;
                                        td2.BorderWidth = 1;
                                        tablaOTZ.AddCell(td2);
                                    }
                                    // FIN COLSPANS

                                    agregacelda(ref tablaOTZ, "Nº", fuente_negrita, 1, "c");
                                    //agregacelda(ref tablaOTZ, "Cod. Producto", fuente_negrita, 1, "c");
                                    //agregacelda(ref tablaOTZ, "Categoría", fuente_negrita, 1, "c");
                                    agregacelda(ref tablaOTZ, "Producto", fuente_negrita, 1, "c");
                                    for (int i = 1; i <= contador_bodegas; i++)
                                    {
                                        agregacelda(ref tablaOTZ, "Precio", fuente_negrita, 1, "c");
                                        agregacelda(ref tablaOTZ, "Precio Unit.", fuente_negrita, 1, "c");
                                        agregacelda(ref tablaOTZ, "Precio Unit c/IVA", fuente_negrita, 1, "c");
                                        agregacelda(ref tablaOTZ, "Cantidad", fuente_negrita, 1, "c");
                                        agregacelda(ref tablaOTZ, "Subtotal neto", fuente_negrita, 1, "c");
                                    }

                                    int    contador = 1;
                                    string aux_cat  = "";
                                    foreach (DataRow dr in dt_detalle.Rows)
                                    {
                                        if (aux_cat != dr["nom_categ"].ToString())
                                        {
                                            PdfPCell td_categoria2 = new PdfPCell(new Phrase(" ", fuente_negrita));
                                            PdfPCell td_categoria  = new PdfPCell(new Phrase(dr["nom_categ"].ToString(), fuente_negrita));
                                            if (contador_bodegas == 1)
                                            {
                                                td_categoria.Colspan  = 7;
                                                td_categoria2.Colspan = 7;
                                            }
                                            else if (contador_bodegas == 2)
                                            {
                                                td_categoria.Colspan  = 12;
                                                td_categoria2.Colspan = 12;
                                            }
                                            else
                                            {
                                                td_categoria.Colspan  = 17;
                                                td_categoria2.Colspan = 17;
                                            }
                                            td_categoria.BorderWidth  = 0;
                                            td_categoria2.BorderWidth = 0;

                                            tablaOTZ.AddCell(td_categoria2);
                                            tablaOTZ.AddCell(td_categoria);

                                            agregacelda(ref tablaOTZ, contador.ToString(), fuente_normal, 1, "c");
                                            //agregacelda(ref tablaOTZ, dr["producto"].ToString(), fuente_normal, 1, "c");

                                            //agregacelda(ref tablaOTZ, dr["nom_categ"].ToString(), fuente_normal, 1, "i");
                                            agregacelda(ref tablaOTZ, dr["nom_producto"].ToString(), fuente_normal, 1, "i");
                                            for (int i = 1; i <= contador_bodegas; i++)
                                            {
                                                agregacelda(ref tablaOTZ, "$ " + int.Parse(dr["precio_con_descuento_" + i].ToString()).ToString("#,##0"), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, "$ " + int.Parse(dr["precio_con_descuento_unitario_" + i].ToString()).ToString("#,##0"), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, "$ " + (int.Parse(dr["precio_con_descuento_unitario_" + i].ToString()) + ((int.Parse(dr["precio_con_descuento_unitario_" + i].ToString()) * 19) / 100)).ToString("#,##0"), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, dr["cantidad_" + i].ToString(), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, "$ " + int.Parse(dr["total_" + i].ToString()).ToString("#,##0"), fuente_negrita, 1, "d");
                                            }

                                            aux_cat = dr["nom_categ"].ToString();
                                        }
                                        else
                                        {
                                            agregacelda(ref tablaOTZ, contador.ToString(), fuente_normal, 1, "c");
                                            //agregacelda(ref tablaOTZ, dr["producto"].ToString(), fuente_normal, 1, "c");

                                            //agregacelda(ref tablaOTZ, dr["nom_categ"].ToString(), fuente_normal, 1, "i");
                                            agregacelda(ref tablaOTZ, dr["nom_producto"].ToString(), fuente_normal, 1, "i");
                                            for (int i = 1; i <= contador_bodegas; i++)
                                            {
                                                agregacelda(ref tablaOTZ, "$ " + int.Parse(dr["precio_con_descuento_" + i].ToString()).ToString("#,##0"), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, "$ " + int.Parse(dr["precio_con_descuento_unitario_" + i].ToString()).ToString("#,##0"), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, "$ " + (int.Parse(dr["precio_con_descuento_unitario_" + i].ToString()) + ((int.Parse(dr["precio_con_descuento_unitario_" + i].ToString()) * 19) / 100)).ToString("#,##0"), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, dr["cantidad_" + i].ToString(), fuente_normal, 1, "d");
                                                agregacelda(ref tablaOTZ, "$ " + int.Parse(dr["total_" + i].ToString()).ToString("#,##0"), fuente_negrita, 1, "d");
                                            }
                                        }
                                        contador++;
                                    }

                                    doc.Add(tablaOTZ);
                                    SaltoLinea(ref doc);

                                    // TOTALES
                                    DataTable dt_totales = new DataTable();
                                    string    sql        = "";
                                    sql += " select bod1.nombre_bodega as nom1, bod2.nombre_bodega as nom2, bod3.nombre_bodega as nom3,  sum(total_1) as 'total_1', sum(total_2) as 'total_2' , sum(total_3) as 'total_3'  " +
                                           " ,sum(total_iva_1) as 'total_iva_1', sum(total_iva_2) as 'total_iva_2', sum(total_iva_3) as 'total_iva_3' " +
                                           " from CTZ_Cotizacion_det ctz left join CTZ_Bodegas bod1 on ctz.cod_bodega_1 = bod1.cod_bodega " +
                                           " left join CTZ_Bodegas bod2 on ctz.cod_bodega_2 = bod2.cod_bodega " +
                                           " left join CTZ_Bodegas bod3 on ctz.cod_bodega_3 = bod3.cod_bodega  " +
                                           " where id_cotizacion = " + id_cotizacion +
                                           " group by bod1.nombre_bodega, bod2.nombre_bodega,bod3.nombre_bodega ";
                                    dt_totales = db.consultar(sql);

                                    if (dt_totales.Rows.Count > 0)
                                    {
                                        PdfPTable tablaTotales = new PdfPTable(contador_bodegas);
                                        tablaTotales.HorizontalAlignment = Element.ALIGN_RIGHT;
                                        if (contador_bodegas == 1)
                                        {
                                            tablaTotales.WidthPercentage = 20;
                                        }
                                        else if (contador_bodegas == 2)
                                        {
                                            tablaTotales.WidthPercentage = 40;
                                        }
                                        else if (contador_bodegas == 3)
                                        {
                                            tablaTotales.WidthPercentage = 60;
                                        }

                                        for (int i = 1; i <= contador_bodegas; i++)
                                        {
                                            try
                                            {
                                                int total    = int.Parse(dt_totales.Rows[0]["total_" + i].ToString());
                                                int totaliva = int.Parse(dt_totales.Rows[0]["total_iva_" + i].ToString());
                                                if (dt_totales.Rows[0]["nom" + i].ToString() != "NO")
                                                {
                                                    PdfPTable tablaTotales_td = new PdfPTable(2);
                                                    PdfPCell  td_total        = new PdfPCell(new Phrase(dt_totales.Rows[0]["nom" + i].ToString(), fuente_negrita));
                                                    td_total.Colspan     = 2;
                                                    td_total.BorderWidth = 1;
                                                    tablaTotales_td.AddCell(td_total);
                                                    agregacelda(ref tablaTotales_td, "Total Neto", fuente_negrita, 1, "i");
                                                    agregacelda(ref tablaTotales_td, "$ " + total.ToString("#,##0"), fuente_normal, 1, "d");
                                                    agregacelda(ref tablaTotales_td, "Total c/IVA", fuente_negrita, 1, "i");
                                                    agregacelda(ref tablaTotales_td, "$ " + totaliva.ToString("#,##0"), fuente_normal, 1, "d");
                                                    agregatabla(ref tablaTotales, tablaTotales_td, 1, "c");
                                                }
                                            }
                                            catch (Exception)
                                            {
                                            }
                                        }
                                        doc.Add(tablaTotales);
                                    }
                                    else
                                    {
                                    }
                                    SaltoLinea(ref doc);
                                    // SERVICIOS
                                    DataTable dt_servicios = new DataTable();
                                    dt_servicios = ctz_cotizaciones_serviciosBO.GetAll(" where id_cotizacion = " + id_cotizacion + " and tipo_servicio = 'POR SEPARADO' ");
                                    if (dt_servicios.Rows.Count > 0)
                                    {
                                        PdfPTable tabla_servicios = new PdfPTable(2);
                                        tabla_servicios.HorizontalAlignment = Element.ALIGN_RIGHT;
                                        tabla_servicios.WidthPercentage     = 40;

                                        agregacelda(ref tabla_servicios, "Servicio", fuente_negrita, 1, "i");
                                        agregacelda(ref tabla_servicios, "Valor", fuente_negrita, 1, "d");
                                        foreach (DataRow dr_servicio in dt_servicios.Rows)
                                        {
                                            agregacelda(ref tabla_servicios, dr_servicio["nombre_servicio"].ToString(), fuente_normal, 1, "i");
                                            agregacelda(ref tabla_servicios, "$" + int.Parse(dr_servicio["valor_servicio"].ToString()).ToString("#,##0"), fuente_normal, 1, "d");;
                                        }
                                        doc.Add(tabla_servicios);
                                    }
                                    //
                                    // FIN
                                    SaltoLinea(ref doc);

                                    //// COMENTARIO AGREGADO AL PDF
                                    //PdfPTable tablacomentario = new PdfPTable(1);
                                    //tablacomentario.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //tablacomentario.WidthPercentage = 100;
                                    //agregacelda(ref tablacomentario, "PRUEBA DE COMENTARIO, VENTA POR SOBRE askldalskdklasdklaskldas", fuente_normal);
                                    //doc.Add(tablacomentario);
                                    ////
                                    ////
                                    //SaltoLinea(ref doc);
                                    doc.NewPage();
                                    doc.Close();
                                    writer.Close();
                                    string pdfPath = Server.MapPath("~/COTIZADOR/COTIZACIONES/" + n_file);
                                    if (enviar_correo)
                                    {
                                        string htmlcorreo = "";
                                        htmlcorreo += "<div style='text-align:center;     display: block !important;' > ";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div> ";
                                        htmlcorreo += "</div>";
                                        htmlcorreo += "<div><img src='http://a58.imgup.net/Sopro4d9d.png' style='    float: right;     width: 90px;'> </div>";

                                        htmlcorreo += "<h4>Cliente: [NOMBRE_CLIENTE] </h4>";
                                        htmlcorreo += "<p>Con fecha: " + DateTime.Now.ToString("dd/MM/yyyy") + " envío la siguiente cotización adjunta. </p>";
                                        htmlcorreo += "<p>Precios válidos hasta: " + DateTime.Now.AddDays(2).ToString("dd/MM/yyyy") + "</p>";
                                        htmlcorreo += "<h4>Vendedor: " + vend.nombre_ + "</h4>";

                                        htmlcorreo += "<br> Para más detalles diríjase a:  <a href='http://www.dereyes.cl/productos.php' > DeReyes.cl  </a> <span style='font:5px; color:gray; float:right;'>No Responder Este Correo</span> <br><br>";
                                        htmlcorreo += "<div style='text-align:center;     display: block !important;' > ";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#DC1510; float:right; width:12.5%; height:6px'></div>";
                                        htmlcorreo += "<div style='background-color:#005D99; float:right; width:12.5%; height:6px'></div> ";
                                        htmlcorreo += "</div>";

                                        Correo cr = new Correo();
                                        cr.EnviarCorreo("*****@*****.**", "*****@*****.**", "Cotización Soprodi", htmlcorreo, "", pdfPath, "SOPRODI");
                                    }
                                    else
                                    {
                                        WebClient client = new WebClient();
                                        Byte[]    buffer = client.DownloadData(pdfPath);
                                        Response.ContentType = "application/pdf";
                                        Response.AddHeader("content-length", buffer.Length.ToString());
                                        Response.BinaryWrite(buffer);
                                        Response.Flush();
                                        Response.End();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    doc.Close();
                                    writer.Close();
                                    ERROR.Text = "Ocurrió un problema al generar PDF";
                                }
                            }
                            else
                            {
                                ERROR.Text = "Esta cotización no es de su propiedad por favor evite ver otras cotizaciones que no le corresponden.";
                            }
                        }
                    }
                }
                else
                {
                    Response.Redirect("Login.aspx");
                }
            }
            catch (Exception ex)
            {
                doc.Close();
                ERROR.Text = "Ocurrió un problema al generar PDF";
            }
        }
예제 #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt_total_resumen_com = (DataTable)Session["dt_total_resumen"];

            DataTable dt_cobranza_com = (DataTable)Session["dt_cobranza_com_resu"];

            string n_file  = "/PDF_SGC.pdf";
            string pdfPath = Server.MapPath(@"~\PDFs\") + n_file;

            string tipo_comision    = Request.QueryString["C"].ToString();
            string MUESTRA_O_NO     = Request.QueryString["H"].ToString();
            string agregar_cobranza = Request.QueryString["T"].ToString().ToUpper();
            bool   agregar_cobr     = false;

            DataTable usuarios_firman = ReporteRNegocio.usuarios_firman(Session["periodo"].ToString());

            if (agregar_cobranza == "TRUE")
            {
                agregar_cobr = true;
            }

            using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
            {
                //step 1
                using (Document pdfDoc = new Document(PageSize.LETTER))
                {
                    try
                    {
                        //pdfDoc.newPage();
                        //// Creamos el documento con el tamaño de página tradicional
                        //Document doc = new Document(PageSize.LETTER);
                        //doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                        //// Indicamos donde vamos a guardar el documento

                        PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                        //pdfWriter.PageEvent = new Common.ITextEvents();

                        ITextEvents PageEventHandler = new ITextEvents();
                        pdfWriter.PageEvent = PageEventHandler;

                        //open the stream
                        pdfDoc.Open();

                        // Creamos la imagen y le ajustamos el tamaño
                        iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/Sopro2.jpg"));
                        //imagen.BorderWidth = 0;
                        imagen.WidthPercentage = 20;
                        imagen.Alignment       = Element.ALIGN_RIGHT;
                        float percentage = 0.0f;
                        percentage = 100 / imagen.Width;
                        imagen.ScalePercent(percentage * 100);


                        ///imagen check para firmas

                        // Creamos la imagen y le ajustamos el tamaño
                        iTextSharp.text.Image imagen2_check = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/accept.png"));
                        imagen.BorderWidth            = 0;
                        imagen2_check.WidthPercentage = 60;
                        imagen2_check.Alignment       = Element.ALIGN_RIGHT;
                        percentage = 10 / imagen2_check.Width;
                        imagen2_check.ScalePercent(percentage * 10);

                        //iTextSharp.text.Image imagen2_uncheck = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/delete.png"));
                        //imagen.BorderWidth = 0;
                        //imagen2_uncheck.WidthPercentage = 60;
                        //imagen2_uncheck.Alignment = Element.ALIGN_RIGHT;
                        //percentage = 10 / imagen2_uncheck.Width;
                        //imagen2_uncheck.ScalePercent(percentage * 10);

                        iTextSharp.text.Image imagen2_uncheck = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/delete.png"));
                        imagen2_uncheck.BorderWidth = 0;
                        imagen2_uncheck.Alignment   = Element.ALIGN_CENTER;
                        //float percentage = 0.0f;
                        percentage = 100 / imagen.Width;
                        imagen2_uncheck.ScalePercent(percentage * 100);



                        //// Creamos la imagen y le ajustamos el tamaño
                        //iTextSharp.text.Image imagen2 = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/Sopro.png"));
                        ////imagen.BorderWidth = 0;
                        //imagen.WidthPercentage = 50;
                        //imagen.Alignment = Element.ALIGN_LEFT;
                        //float percentage2 = 0.0f;
                        //percentage2 = 100 / imagen.Width;
                        //imagen.ScalePercent(percentage2 * 100);

                        //// Creamos la imagen y le ajustamos el tamaño
                        //iTextSharp.text.Image imagen3 = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/Sopro.png"));
                        ////imagen.BorderWidth = 0;
                        //imagen.WidthPercentage = 50;
                        //imagen.Alignment = Element.ALIGN_LEFT;
                        //float percentage3 = 0.0f;
                        //percentage3 = 100 / imagen.Width;
                        //imagen.ScalePercent(percentage3 * 100);


                        PdfPTable tabla_imagen = new PdfPTable(1);
                        tabla_imagen.HorizontalAlignment = Element.ALIGN_RIGHT;
                        tabla_imagen.WidthPercentage     = 50;
                        PdfPCell imagen_td = new PdfPCell(imagen);
                        imagen_td.BorderWidth = 0;
                        tabla_imagen.AddCell(imagen_td);

                        //PdfPCell imagen2_td = new PdfPCell(imagen2);
                        //imagen2_td.BorderWidth = 0;
                        //tabla_imagen.AddCell(imagen2_td);

                        //PdfPCell imagen3_td = new PdfPCell(imagen3);
                        //imagen3_td.BorderWidth = 0;
                        //tabla_imagen.AddCell(imagen3_td);

                        PdfPCell vacio = new PdfPCell(new Phrase("  ", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        vacio.BorderWidth = 0;

                        tabla_imagen.AddCell(vacio);
                        tabla_imagen.AddCell(vacio);
                        tabla_imagen.AddCell(vacio);

                        PdfPTable tabla_titulo = new PdfPTable(1);
                        string    titulo       = "COMISIONES " + Session["periodo"].ToString();
                        PdfPCell  TD_TITULO    = new PdfPCell(new Phrase(titulo, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16)));
                        TD_TITULO.BorderWidth         = 0;
                        TD_TITULO.HorizontalAlignment = Element.ALIGN_CENTER;
                        tabla_titulo.AddCell(TD_TITULO);

                        PdfPTable tabla_fecha_hora = new PdfPTable(1);
                        string    fecha_hora       = DateTime.Now.ToString();
                        PdfPCell  td_fecha_hora    = new PdfPCell(new Phrase(fecha_hora, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 9)));
                        td_fecha_hora.BorderWidth         = 0;
                        td_fecha_hora.HorizontalAlignment = Element.ALIGN_CENTER;
                        tabla_fecha_hora.AddCell(td_fecha_hora);

                        PdfPTable tabla_Vacia = new PdfPTable(1);
                        PdfPCell  td_vacia    = new PdfPCell(new Phrase(" ", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        td_vacia.BorderWidth = 0;
                        tabla_Vacia.AddCell(td_vacia);

                        pdfDoc.Add(imagen);
                        pdfDoc.Add(tabla_titulo);
                        pdfDoc.Add(tabla_fecha_hora);
                        pdfDoc.Add(tabla_Vacia);

                        ////Escribimos el encabezamiento en el documento
                        PdfPTable tabla = new PdfPTable(3);
                        tabla.WidthPercentage = 100;

                        PdfPCell th1 = new PdfPCell(new Phrase("NOMBRE", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        th1.HorizontalAlignment = Element.ALIGN_CENTER;
                        //th1.BorderWidth = 0;
                        tabla.AddCell(th1).BackgroundColor = new BaseColor(229, 229, 229, 229);;

                        PdfPCell th2 = new PdfPCell(new Phrase("NOMBRE REGLA", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        th2.HorizontalAlignment = Element.ALIGN_CENTER;
                        //th2.BorderWidth = 0;
                        tabla.AddCell(th2).BackgroundColor = new BaseColor(229, 229, 229, 229);;

                        PdfPCell th3 = new PdfPCell(new Phrase("TOTAL", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        th3.HorizontalAlignment = Element.ALIGN_CENTER;
                        //th3.BorderWidth = 0;
                        tabla.AddCell(th3).BackgroundColor = new BaseColor(229, 229, 229, 229);;

                        //pdfDoc.Add(tabla);

                        string nombre_vendedor = "";
                        int    cont            = 0;
                        //string tipo_comision = Session["tipo_comision"].ToString();


                        DataTable dt_tolta_resume_com_aux = dt_total_resumen_com.Clone();

                        ///quitar los abarrotes
                        foreach (DataRow r2 in dt_total_resumen_com.Rows)
                        {
                            if (tipo_comision == "2")
                            {
                                if (r2[4].ToString() == "True")
                                {
                                    dt_tolta_resume_com_aux.ImportRow(r2);

                                    string aca = "";
                                    //dt_total_resumen_com.Rows.Remove(r2);
                                    //r2.Delete();
                                }
                            }
                            else if (tipo_comision == "1")
                            {
                                if (r2[4].ToString() != "True")
                                {
                                    dt_tolta_resume_com_aux.ImportRow(r2);

                                    string aca2 = "";
                                    //dt_total_resumen_com.Rows.Remove(r2);
                                    //r2.Delete();
                                }
                            }
                            else
                            {
                                dt_tolta_resume_com_aux.ImportRow(r2);
                            }
                        }

                        foreach (DataRow r in dt_tolta_resume_com_aux.Rows)
                        {
                            cont++;


                            if (nombre_vendedor != r[1].ToString())
                            {
                                if (cont > 1)
                                {
                                    tabla.AddCell(vacio);
                                    tabla.AddCell(vacio);
                                    tabla.AddCell(vacio);


                                    tabla.AddCell(vacio);
                                    tabla.AddCell(vacio);
                                    tabla.AddCell(vacio);
                                }

                                if (r[2].ToString().Contains("ABARROTES"))
                                {
                                    PdfPCell td1 = new PdfPCell(new Phrase(r[1].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td1.BorderWidth = 0;
                                    tabla.AddCell(td1).BackgroundColor = new BaseColor(240, 128, 128);
                                }
                                else
                                {
                                    PdfPCell td1 = new PdfPCell(new Phrase(r[1].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td1.BorderWidth = 0;
                                    tabla.AddCell(td1).BackgroundColor = new BaseColor(135, 206, 235);
                                }

                                nombre_vendedor = r[1].ToString();
                            }

                            else
                            {
                                PdfPCell td1 = new PdfPCell(new Phrase(" ", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                //td1.BorderWidth = 0;
                                tabla.AddCell(td1);
                                nombre_vendedor = r[1].ToString();
                            }


                            PdfPCell td2 = new PdfPCell(new Phrase(r[2].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                            td2.HorizontalAlignment = Element.ALIGN_LEFT;
                            //td2.BorderWidth = 0;
                            tabla.AddCell(td2);

                            PdfPCell td3 = new PdfPCell(new Phrase(r[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                            td3.HorizontalAlignment = Element.ALIGN_LEFT;
                            //td3.BorderWidth = 0;
                            tabla.AddCell(td3);
                            //PdfPTable table_ventas = new PdfPTable(11);
                            //table_ventas.WidthPercentage = 100;

                            //table_ventas.AddCell(dia).BackgroundColor = new BaseColor(229, 229, 229, 229);
                        }

                        tabla.AddCell(vacio);
                        tabla.AddCell(vacio);


                        ////////------------------------------------------------------------------------------COMISION COBRANZA
                        PdfPTable tabla_COBRANZA = new PdfPTable(4);
                        if (agregar_cobr)
                        {
                            tabla_COBRANZA.WidthPercentage = 100;

                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);


                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);


                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);
                            tabla_COBRANZA.AddCell(vacio);

                            cont = 0;
                            bool final = true;
                            foreach (DataRow r3 in dt_cobranza_com.Rows)
                            {
                                if (final)
                                {
                                    tabla_COBRANZA.AddCell(vacio);
                                    tabla_COBRANZA.AddCell(vacio);
                                    tabla_COBRANZA.AddCell(vacio);
                                    tabla_COBRANZA.AddCell(vacio);


                                    PdfPCell td1 = new PdfPCell(new Phrase(r3[0].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td1.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td1).BackgroundColor = new BaseColor(30, 176, 40);

                                    PdfPCell td2 = new PdfPCell(new Phrase(r3[1].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td1.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td2).BackgroundColor = new BaseColor(30, 176, 40);

                                    PdfPCell td3 = new PdfPCell(new Phrase(r3[2].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td1.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td3).BackgroundColor = new BaseColor(30, 176, 40);

                                    PdfPCell td4 = new PdfPCell(new Phrase(r3[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td1.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td4).BackgroundColor = new BaseColor(30, 176, 40);

                                    final = false;
                                }
                                else
                                {
                                    PdfPCell td1 = new PdfPCell(new Phrase(r3[0].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td1.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td2.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td1);

                                    PdfPCell td2 = new PdfPCell(new Phrase(r3[1].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td2.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td2.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td2);

                                    PdfPCell td3 = new PdfPCell(new Phrase(r3[2].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td3.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td2.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td3);

                                    PdfPCell td4 = new PdfPCell(new Phrase(r3[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                    td4.HorizontalAlignment = Element.ALIGN_LEFT;
                                    //td2.BorderWidth = 0;
                                    tabla_COBRANZA.AddCell(td4);
                                }
                                if (r3[0].ToString().Contains("TOTAL"))
                                {
                                    final = true;
                                }
                            }
                        }

                        float[] medidasCeldas = { 0.30f, 0.50f, 0.15f };
                        tabla.SetWidths(medidasCeldas);

                        float[] medidasCeldas_4 = { 0.38f, 0.28f, 0.15f, 0.16f };

                        float[] medidasCeldas_5 = { 0.20f, 0.20f, 0.20f, 0.20f, 0.20f };


                        if (agregar_cobr)
                        {
                            tabla_COBRANZA.SetWidths(medidasCeldas_4);
                        }
                        pdfDoc.Add(tabla);
                        if (agregar_cobr)
                        {
                            pdfDoc.Add(tabla_COBRANZA);
                        }


                        ////////------------------------------------------------------------------------------FIRMAS
                        //PdfPTable tabla_firmas = new PdfPTable(usuarios_firman.Rows.Count);


                        PdfPTable tabla_firmas = new PdfPTable(3);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);
                        tabla_firmas.AddCell(vacio);


                        tabla_firmas.WidthPercentage = 100;

                        PdfPCell th1_F = new PdfPCell(new Phrase("GRUPO", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        th1_F.HorizontalAlignment = Element.ALIGN_CENTER;
                        //th1.BorderWidth = 0;
                        tabla_firmas.AddCell(th1_F).BackgroundColor = new BaseColor(229, 229, 229, 229);;

                        PdfPCell th2_F = new PdfPCell(new Phrase("FIRMA", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        th2_F.HorizontalAlignment = Element.ALIGN_CENTER;
                        //th2.BorderWidth = 0;
                        tabla_firmas.AddCell(th2_F).BackgroundColor = new BaseColor(229, 229, 229, 229);;

                        PdfPCell th3_F = new PdfPCell(new Phrase("NOMBRE", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                        th3_F.HorizontalAlignment = Element.ALIGN_CENTER;
                        //th3.BorderWidth = 0;
                        tabla_firmas.AddCell(th3_F).BackgroundColor = new BaseColor(229, 229, 229, 229);;

                        foreach (DataRow r1 in usuarios_firman.Rows)
                        {
                            PdfPCell td1 = new PdfPCell(new Phrase(r1[0].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                            td1.HorizontalAlignment = Element.ALIGN_LEFT;
                            //td2.BorderWidth = 0;
                            tabla_firmas.AddCell(td1);


                            if (r1[1].ToString().Trim() == "True")
                            {
                                PdfPCell td2 = new PdfPCell(new Phrase("OK", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                td2.HorizontalAlignment = Element.ALIGN_LEFT;
                                //td2.BorderWidth = 0;
                                tabla_firmas.AddCell(td2).BackgroundColor = new BaseColor(59, 134, 50);
                            }
                            else
                            {
                                PdfPCell td2 = new PdfPCell(new Phrase("", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                                td2.HorizontalAlignment = Element.ALIGN_LEFT;
                                //td2.BorderWidth = 0;
                                tabla_firmas.AddCell(td2).BackgroundColor = new BaseColor(239, 36, 36);
                            }

                            PdfPCell td3 = new PdfPCell(new Phrase(r1[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 10)));
                            td3.HorizontalAlignment = Element.ALIGN_LEFT;
                            //td2.BorderWidth = 0;
                            tabla_firmas.AddCell(td3);
                        }


                        //agregamos tabla de las firmas
                        tabla_firmas.SetWidths(medidasCeldas);
                        pdfDoc.Add(tabla_firmas);


                        pdfDoc.NewPage();

                        pdfDoc.Close();
                        //writer.Close();
                        //string pdfPath = Server.MapPath("~/PDF_Ventas/" + n_file);
                        WebClient client = new WebClient();
                        Byte[]    buffer = client.DownloadData(pdfPath);

                        //document.Add(new Paragraph("Hello World!"));

                        if (MUESTRA_O_NO == "0")
                        {
                        }
                        else
                        {
                            Response.ContentType = "application/pdf";
                            Response.AddHeader("content-length", buffer.Length.ToString());
                            Response.BinaryWrite(buffer);
                            Response.Flush();
                            Response.End();
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }