Exemple #1
0
        /*--------------------------------------------------------
         * Exportar um HTML fornecido.
         *    - O HTML.
         *    - Nome do Arquivo.
         * - Link para o CSS.
         * ----------------------------------------------------------*/


        public static void Export(string html, string fileName, string linkCss)
        {
            ////reset response
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/pdf";

            ////define pdf filename
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);



            //Gera o arquivo PDF
            using (var document = new Document(PageSize.A4, 40, 40, 40, 40))
            {
                //html = FormatImageLinks(html);

                //define o  output do  HTML
                var        memStream = new MemoryStream();
                TextReader xmlString = new StringReader(html);

                PdfWriter writer = PdfWriter.GetInstance(document, memStream);
                writer.PageEvent = new PDFWriteEvents();

                document.Open();


                //Registra todas as fontes no computador cliente.
                FontFactory.RegisterDirectories();

                // Set factories
                var htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                // Set css
                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                cssResolver.AddCssFile(HttpContext.Current.Server.MapPath(linkCss), true);

                // Exporta
                IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
                var       worker   = new XMLWorker(pipeline, true);
                var       xmlParse = new XMLParser(true, worker);
                xmlParse.Parse(xmlString);
                xmlParse.Flush();

                document.Close();
                document.Dispose();

                HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
            }

            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Flush();
        }
        public byte[] Render(string htmlText, string pageTitle, string linkCss, bool horizontal)
        {
            byte[] renderedBuffer;
            using (var outputMemoryStream = new MemoryStream())
            {
                using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
                {
                    if (horizontal)
                    {
                        pdfDocument.SetPageSize(PageSize.A4.Rotate());
                    }
                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
                    pdfWriter.CloseStream = false;
                    pdfWriter.PageEvent   = new PrintHeaderFooter {
                        Title = pageTitle
                    };
                    pdfDocument.Open();

                    // register all fonts in current computer
                    FontFactory.RegisterDirectories();


                    // Set factories
                    var htmlContext = new HtmlPipelineContext(null);
                    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                    // Set css
                    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                    cssResolver.AddCssFile(HttpContext.Current.Server.MapPath(linkCss), true);
                    cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true);


                    //Export
                    IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDocument, pdfWriter)));

                    using (var xmlString = new StringReader(htmlText))
                    {
                        var worker   = new XMLWorker(pipeline, true);
                        var xmlParse = new XMLParser(true, worker);
                        xmlParse.Parse(xmlString);
                        xmlParse.Flush();
                    }
                }

                renderedBuffer = new byte[outputMemoryStream.Position];
                outputMemoryStream.Position = 0;
                outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
            }
            return(renderedBuffer);
        }
        public byte[] GetPdfBytesArray(string html)
        {
            var tempHtml = html;
            var cssLinks = html.GetCssLinks().ToList();

            if (cssLinks.Count > 0)
            {
                tempHtml = tempHtml.RemoveCssLink();
            }
            tempHtml = tempHtml.FormatImageLinks();

            using (var ms = new MemoryStream())
                using (var document = new Document(DocPageSize, 10, 10, 5, 0))
                {
                    using (var writer = PdfWriter.GetInstance(document, ms))
                    {
                        document.Open();
                        using (TextReader xmlString = new StringReader(tempHtml))
                        {
                            //Set factories
                            var htmlContext = new HtmlPipelineContext(null);
                            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                            //Set css
                            var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                            foreach (var item in cssLinks)
                            {
                                cssResolver.AddCssFile(item, true);
                            }

                            //Export
                            IPipeline pipeline = new CssResolverPipeline(cssResolver,
                                                                         new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
                            var worker   = new XMLWorker(pipeline, true);
                            var xmlParse = new XMLParser(true, worker);
                            xmlParse.Parse(xmlString);
                            xmlParse.Flush();
                        }
                        document.Close();
                    }
                    return(ms.ToArray());
                }
        }
Exemple #4
0
        private byte[] GetPdf(string html)
        {
            //MemoryStream stream = new MemoryStream();
            //using (Document document = new Document())
            //{
            //    //html - we can provide here any HTML, for example one rendered from Razor view
            //    StringReader htmlReader = new StringReader(html);
            //    PdfWriter writer = PdfWriter.GetInstance(document, stream);
            //    writer.PageEvent = new PdfPageEventHelper();
            //    document.SetPageSize(PageSize.A4);
            //    document.Open();
            //    XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlReader);
            //    document.Close();
            //}
            //return stream.GetBuffer();

            //byte[] bytesArray = null;
            //using (var ms = new MemoryStream())
            //{
            //    using (var document = new Document())
            //    {
            //        using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
            //        {

            //            document.Open();
            //            using (var strReader = new StringReader(html))
            //            {
            //                //Set factories
            //                HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            //                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            //                //Set css
            //                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
            //                cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/bootstrap.min.css"), true);
            //                //Export
            //                IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
            //                var worker = new XMLWorker(pipeline, true);
            //                var xmlParse = new XMLParser(true, worker);
            //                xmlParse.Parse(strReader);
            //                xmlParse.Flush();
            //            }

            //            writer.CloseStream = false;
            //            document.Close();
            //            bytesArray = ms.ToArray();
            //        }
            //    }

            //}
            //return bytesArray;


            //var ms = new MemoryStream();
            ////var XhtmlHelper = new XhtmlToListHelper();
            //var document = new Document();
            //PdfWriter writer = PdfWriter.GetInstance(document, ms);
            //var htmlContext = new HtmlPipelineContext(null);
            //htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
            //var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
            //cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/bootstrap.min.css"), true);
            ////var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new ElementHandlerPipeline(XhtmlHelper, null)));//Here's where we add our IElementHandler
            //var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, null)));
            //var worker = new XMLWorker(pipeline, true);
            //var parser = new XMLParser();
            //parser.AddListener(worker);

            //using (TextReader sr = new StringReader(html))
            //{
            //    parser.Parse(sr);
            //}
            //ms.Position = 0;
            //return ms.ToArray();

            using (var ms = new MemoryStream())
            {
                html = FormatImageLinks(html);
                Document pdfDocument = new Document(PageSize.A3, 45, 5, 5, 5);
                //PdfWriter writer = PdfWriter.GetInstance(pdfDocument, Response.OutputStream);
                PdfWriter writer = PdfWriter.GetInstance(pdfDocument, ms);

                pdfDocument.Open();

                HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                // Set css
                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/print.css"), true);
                IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDocument, writer)));

                XMLWorker worker   = new XMLWorker(pipeline, true);
                XMLParser xmlParse = new XMLParser(true, worker);



                using (TextReader sr = new StringReader(html))
                {
                    xmlParse.Parse(sr);
                }
                xmlParse.Flush();
                pdfDocument.Close();
                return(ms.ToArray());
            }
            //Response.Write(pdfDocument);
        }
        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            try
            {
                string     direccion_logo = "Av. Santa Rosa 4470, San Joaquin, Santiago - Tel: +56225526276";
                TipoMoneda moneda         = new TipoMoneda();
                Usuario    creador        = new Usuario();
                moneda.ID = Convert.ToInt32(Request.Form.Get(txtMoneda.UniqueID));
                moneda.Read();
                Encabezado encabezado    = (Encabezado)Session["encabezado"];
                string     correo        = Request.Form.Get(txtCorreo.UniqueID);
                string     rut           = Request.Form.Get(txtRut.UniqueID);
                string     razon         = Request.Form.Get(txtNombre.UniqueID);
                string     contacto      = Request.Form.Get(txtContacto.UniqueID);
                string     condicionpago = Request.Form.Get(txtCondicionesPago.UniqueID);
                string     entrega       = Request.Form.Get(txtEntrega.UniqueID);
                string     direccion     = Request.Form.Get(txtDireccion.UniqueID);
                string     fecha         = Request.Form.Get(txtFecha_.UniqueID);
                string     neto          = Request.Form.Get(txtNeto.UniqueID);
                string     telefono      = Request.Form.Get(txtTelefono.UniqueID);
                string     total         = Request.Form.Get(txtTotal.UniqueID);
                Detalle    detalle       = new Detalle();
                detalle.Correlativo           = encabezado.Correlativo;
                encabezado.CondicionPago      = condicionpago;
                encabezado.Contacto           = contacto;
                encabezado.Correo             = correo;
                encabezado.Entrega            = entrega;
                encabezado.Direccion          = direccion;
                encabezado.Estado             = "Pendiente";
                encabezado.Observacion_estado = " ";
                //encabezado.Fecha = fecha.ToString("dd/MM/yyyy");
                encabezado.Fecha = fecha;
                //encabezado.Iva = Convert.ToInt32(txtIVA.Value);
                encabezado.Tipo_moneda  = moneda.Nombre;
                encabezado.Iva          = 0;
                encabezado.Neto         = Convert.ToDouble(neto.ToString().Replace(".", ","));
                encabezado.Razon_social = razon;
                encabezado.Rut          = rut;
                encabezado.Telefono     = telefono;
                encabezado.Total        = Convert.ToDouble(total.ToString().Replace(".", ","));
                creador.Usuario_        = encabezado.Codigo_usuario;
                creador.Read();
                if (encabezado.Update())
                {
                    detalle.LimpiarDetalleCorrelativo();
                    List <string> lista       = ListValues();
                    string        correlativo = encabezado.Correlativo.ToString();
                    CreacionDetalle(correlativo, lista);
                    byte[] bytesarray = null;
                    using (var ms = new MemoryStream())
                    {
                        using (var document = new Document(PageSize.A4, 20f, 20f, 45f, 35f)) //PageSize.A4, 20f, 20f, 65f, 35f--PageSize.A4, 20f, 20f, 75f, 35f
                        {
                            using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
                            {
                                document.Open();
                                PdfContentByte canvas = writer.DirectContent;
                                writer.CompressionLevel = 0;
                                canvas.SaveState();
                                canvas.BeginText();
                                canvas.MoveText(118, 773);
                                canvas.SetFontAndSize(BaseFont.CreateFont(), 8);
                                canvas.ShowText(direccion_logo);
                                canvas.EndText();
                                canvas.RestoreState();
                                using (var strreader = new StringReader(HTMLPage(ListValues(), encabezado, correlativo, creador, moneda).ToString()))
                                {
                                    var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/pdf/logo.png"));
                                    logo.ScaleAbsoluteWidth(450);
                                    logo.ScaleAbsoluteHeight(100);
                                    logo.SetAbsolutePosition(0, 750);
                                    document.Add(logo);
                                    //set factories
                                    HtmlPipelineContext htmlcontext = new HtmlPipelineContext(null);
                                    htmlcontext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                                    //set css
                                    ICSSResolver cssresolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                                    cssresolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/pdf/estilo.css"), true);
                                    //export
                                    IPipeline pipeline = new CssResolverPipeline(cssresolver, new HtmlPipeline(htmlcontext, new PdfWriterPipeline(document, writer)));
                                    var       worker   = new XMLWorker(pipeline, true);
                                    var       xmlparse = new XMLParser(true, worker);
                                    //var xmlparse = new XMLParser();
                                    xmlparse.Parse(strreader);
                                    xmlparse.Flush();
                                }
                                document.Close();
                            }
                        }
                        bytesarray = ms.ToArray();
                        ms.Close();
                        // clears all content output from the buffer stream
                        Response.Clear();
                        // gets or sets the http mime type of the output stream.
                        Response.ContentType = "application/pdf";
                        // adds an http header to the output stream
                        Response.AddHeader("content-disposition", "attachment; filename=cotizacion_" + correlativo + ".pdf");

                        //gets or sets a value indicating whether to buffer output and send it after
                        // the complete response is finished processing.
                        Response.Buffer = true;
                        // sets the cache-control header to one of the values of system.web.httpcacheability.
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        // writes a string of binary characters to the http output stream. it write the generated bytes .
                        Response.BinaryWrite(bytesarray);
                        // sends all currently buffered output to the client, stops execution of the
                        // page, and raises the system.web.httpapplication.endrequest event.

                        Response.Flush();                                          // sends all currently buffered output to the client.
                        Response.SuppressContent = true;                           // gets or sets a value indicating whether to send http content to the client.
                        HttpContext.Current.ApplicationInstance.CompleteRequest(); // causes asp.net to bypass all events and filtering in the http pipeline chain of execution and directly execute the endrequest event.
                                                                                   // closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
                        Response.Close();
                    }
                    Session["encabezado"] = null;
                    Session["detalle"]    = null;
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Cotizacion modificada" + "');", true);
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
            }
        }
        /// <summary>
        /// Returns the PDF stream of the given receipt.
        /// </summary>
        /// <param name="userId">User Id.</param>
        /// <param name="receiptId">Receipt Id.</param>
        /// <returns>Stream.</returns>
        public Stream GetReceiptStream(int userId, int receiptId)
        {
            User                  user           = null;
            Stream                ret            = null;
            XMLWorker             worker         = null;
            IPipeline             pipeline       = null;
            XMLParser             xmlParse       = null;
            string                html           = string.Empty;
            ICSSResolver          cssResolver    = null;
            PaymentHistoryEntry   receipt        = null;
            HtmlPipelineContext   htmlContext    = null;
            Func <string, string> valueOrDefault = v => !string.IsNullOrWhiteSpace(v) ? v : "-";

            if (userId > 0 && receiptId > 0)
            {
                receipt = _payments.Select(receiptId);

                if (receipt != null && receipt.UserId == userId)
                {
                    user = Resolver.Resolve <IRepository <User> >().Select(receipt.UserId);

                    if (user != null)
                    {
                        using (var stream = Assembly.GetExecutingAssembly()
                                            .GetManifestResourceStream("Ifly.Resources.PaymentReceiptTemplate.html"))
                        {
                            using (var reader = new StreamReader(stream))
                                html = reader.ReadToEnd();
                        }

                        if (!string.IsNullOrEmpty(html))
                        {
                            html = Utils.Input.FormatWith(html, new
                            {
                                Date             = receipt.Date.ToString("R", _culture),
                                UserName         = string.Format("{0} ({1})", valueOrDefault(user.Name), valueOrDefault(user.Email)),
                                CompanyName      = valueOrDefault(user.CompanyName),
                                CompanyAddress   = valueOrDefault(user.CompanyAddress),
                                SubscriptionType = Enum.GetName(typeof(SubscriptionType), receipt.SubscriptionType),
                                Amount           = receipt.Amount.ToString("F"),
                                ChargedTo        = valueOrDefault(receipt.ChargedTo),
                                TransactionId    = valueOrDefault(receipt.TransactionId)
                            });

                            using (Document doc = new Document(PageSize.A4, 30, 30, 30, 30))
                            {
                                using (var s = new MemoryStream())
                                {
                                    using (var writer = PdfWriter.GetInstance(doc, s))
                                    {
                                        doc.Open();

                                        htmlContext = new HtmlPipelineContext(null);
                                        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                                        cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                                        pipeline    = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));
                                        worker      = new XMLWorker(pipeline, true);

                                        xmlParse = new XMLParser(true, worker);
                                        xmlParse.Parse(new StringReader(html));
                                        xmlParse.Flush();

                                        doc.Close();
                                        doc.Dispose();

                                        ret = new MemoryStream(s.ToArray());
                                        ret.Seek(0, SeekOrigin.Begin);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(ret);
        }
        protected void gvCotizacion_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            Usuario    usuario        = (Usuario)Session["usuario"];
            TipoMoneda moneda         = new TipoMoneda();
            string     direccion_logo = "Av. Santa Rosa 4470, San Joaquin, Santiago - Tel: +56225526276";

            switch (e.CommandName)
            {
            case "Select":
                int              index       = Convert.ToInt32(e.CommandArgument);
                GridViewRow      selectedRow = gvCotizacion.Rows[index];
                TableCell        corr_id     = selectedRow.Cells[0];
                string           correlativo = corr_id.Text;
                Encabezado       encabezado  = new Encabezado();
                Usuario          creador     = new Usuario();
                ColeccionDetalle detalles    = new ColeccionDetalle();
                encabezado.Correlativo = Convert.ToInt32(correlativo);
                encabezado.Read();
                moneda.Nombre = encabezado.Tipo_moneda;
                moneda.ReadNombre();
                creador.Usuario_ = encabezado.Codigo_usuario;
                creador.Read();
                List <Detalle> list = detalles.ListaDetalle(correlativo);
                try
                {
                    byte[] bytesarray = null;
                    using (var ms = new MemoryStream())
                    {
                        using (var document = new Document(PageSize.A4, 20f, 20f, 45f, 35f))     //PageSize.A4, 20f, 20f, 65f, 35f--PageSize.A4, 20f, 20f, 75f, 35f
                        {
                            using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
                            {
                                document.Open();
                                PdfContentByte canvas = writer.DirectContent;
                                writer.CompressionLevel = 0;
                                canvas.SaveState();
                                canvas.BeginText();
                                canvas.MoveText(118, 773);
                                canvas.SetFontAndSize(BaseFont.CreateFont(), 8);
                                canvas.ShowText(direccion_logo);
                                canvas.EndText();
                                canvas.RestoreState();
                                using (var strreader = new StringReader(HTMLPage(list, encabezado, correlativo, creador, moneda).ToString()))
                                {
                                    var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/pdf/logo.png"));
                                    logo.ScaleAbsoluteWidth(450);
                                    logo.ScaleAbsoluteHeight(100);
                                    logo.SetAbsolutePosition(0, 750);
                                    document.Add(logo);
                                    //set factories
                                    HtmlPipelineContext htmlcontext = new HtmlPipelineContext(null);
                                    htmlcontext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                                    //set css
                                    ICSSResolver cssresolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                                    cssresolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/pdf/estilo.css"), true);
                                    //export
                                    IPipeline pipeline = new CssResolverPipeline(cssresolver, new HtmlPipeline(htmlcontext, new PdfWriterPipeline(document, writer)));
                                    var       worker   = new XMLWorker(pipeline, true);
                                    var       xmlparse = new XMLParser(true, worker);
                                    xmlparse.Parse(strreader);
                                    xmlparse.Flush();
                                }
                                document.Close();
                            }
                        }
                        bytesarray = ms.ToArray();
                        ms.Close();
                        Response.Clear();
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-disposition", "attachment; filename=cotizacion_" + correlativo + "_reimpresion.pdf");
                        Response.Buffer = true;
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        Response.BinaryWrite(bytesarray);
                        Response.Flush();
                        Response.SuppressContent = true;
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        Response.Close();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
                    break;
                }
            //case "Edit":
            //    try
            //    {
            //        int index2 = Convert.ToInt32(e.CommandArgument);
            //        GridViewRow selectedRow2 = gvCotizacion.Rows[index2];
            //        TableCell correlativo_id = selectedRow2.Cells[0];
            //        //TableCell razon_social = selectedRow2.Cells[1];
            //        //TableCell rut = selectedRow2.Cells[2];
            //        //TableCell contacto = selectedRow2.Cells[3];
            //        //TableCell fecha = selectedRow2.Cells[4];
            //        TableCell telefono = selectedRow2.Cells[5];
            //        TableCell correo = selectedRow2.Cells[6];
            //        //TableCell condicion_pago = selectedRow2.Cells[7];
            //        //TableCell entrega = selectedRow2.Cells[8];
            //        //TableCell direccion = selectedRow2.Cells[9];
            //        //TableCell tipo_moneda = selectedRow2.Cells[10];
            //        TableCell estado = selectedRow2.Cells[11];
            //        //TableCell codigo_usuario = selectedRow2.Cells[12];
            //        //TableCell neto = selectedRow2.Cells[13];
            //        //TableCell iva = selectedRow2.Cells[14];
            //        //TableCell total = selectedRow2.Cells[15];
            //        Encabezado encabezado2 = new Encabezado();
            //        encabezado2.Correlativo = Convert.ToInt32(correlativo_id.Text);
            //        encabezado2.Read();
            //        encabezado2.Telefono = telefono.Text;
            //        encabezado2.Correo = correo.Text;
            //        encabezado2.Estado = estado.Text;
            //        encabezado2.Update();
            //        break;
            //    }
            //    catch (Exception ex)
            //    {
            //        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
            //        break;
            //    }

            //case "Delete":
            //    int index2 = Convert.ToInt32(e.CommandArgument);
            //    GridViewRow selectedRow2 = gvCotizacion.Rows[index2];
            //    TableCell corr_id2 = selectedRow2.Cells[0];
            //    string correlativo2 = corr_id2.Text;
            //    Encabezado encabezado2 = new Encabezado();
            //    encabezado2.Correlativo = Convert.ToInt32(correlativo2);
            //    encabezado2.Delete();
            //   break;
            case "Details":
                int         index3       = Convert.ToInt32(e.CommandArgument);
                GridViewRow selectedRow3 = gvCotizacion.Rows[index3];
                TableCell   corr_id2     = selectedRow3.Cells[0];
                string      correlativo2 = corr_id2.Text;
                Session["cotizacion"] = correlativo2;
                Response.Redirect("../Cotizacion/RevisionDetalles.aspx", false);
                Context.ApplicationInstance.CompleteRequest();
                break;

            case "Excel":
                int              index4       = Convert.ToInt32(e.CommandArgument);
                GridViewRow      selectedRow4 = gvCotizacion.Rows[index4];
                TableCell        corr_id3     = selectedRow4.Cells[0];
                string           correlativo3 = corr_id3.Text;
                Encabezado       encabezado3  = new Encabezado();
                Usuario          creador2     = new Usuario();
                ColeccionDetalle detalles2    = new ColeccionDetalle();
                encabezado3.Correlativo = Convert.ToInt32(correlativo3);
                encabezado3.Read();
                moneda.Nombre = encabezado3.Tipo_moneda;
                moneda.ReadNombre();
                creador2.Usuario_ = encabezado3.Codigo_usuario;
                creador2.Read();
                List <Detalle> list2 = detalles2.ListaDetalle(correlativo3);
                try
                {
                    XLWorkbook workbook = DocumentoExcel(list2, encabezado3, correlativo3, creador2, moneda);
                    // Prepare the response
                    Response.Clear();
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;filename=\"cotizacion_excel_" + correlativo3 + ".xlsx\"");
                    //Response.AddHeader("content-disposition", "attachment;filename=cotizacion_excel_" + correlativo3 + ".xlsx");
                    //byte[] bytesarray = null;
                    // Flush the workbook to the Response.OutputStream
                    using (var memoryStream = new MemoryStream())
                    {
                        workbook.SaveAs(memoryStream);
                        memoryStream.WriteTo(Response.OutputStream);
                        memoryStream.Close();

                        //bytesarray = memoryStream.ToArray();
                        //Response.End();
                        Response.Buffer = true;
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        //Response.BinaryWrite(bytesarray);
                        Response.Flush();
                        Response.SuppressContent = true;
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        Response.Close();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
                    break;
                }

            case "Cotizacion":
                int         index5       = Convert.ToInt32(e.CommandArgument);
                GridViewRow selectedRow5 = gvCotizacion.Rows[index5];
                TableCell   corr_id4     = selectedRow5.Cells[0];
                string      correlativo4 = corr_id4.Text;
                try
                {
                    Encabezado       encabezado4 = new Encabezado();
                    ColeccionDetalle detalles3   = new ColeccionDetalle();
                    encabezado4.Correlativo = Convert.ToInt32(correlativo4);
                    encabezado4.Read();
                    List <Detalle> list3 = detalles3.ListaDetalle(correlativo4);

                    Session["encabezado"] = encabezado4;
                    Session["detalle"]    = list3;
                    Response.Redirect("../Cotizacion/EditorCotizacion.aspx", false);
                    Context.ApplicationInstance.CompleteRequest();
                    break;
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
                    break;
                }

            default:
                break;
            }
        }
        public void print()
        {
            string rpthtml = bindheader();
            // string rpthtml = "";
            string filename = System.DateTime.UtcNow.ToFileTimeUtc() + ".pdf";
            string html     = readHTML();

            html = rpthtml + html;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/pdf";

            ////define pdf filename
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename);


            //Generate PDF
            using (var document = new Document(iTextSharp.text.PageSize.B4))
            {
                //define output control HTML
                var        memStream = new MemoryStream();
                TextReader xmlString = new StringReader(html);

                PdfWriter writer = PdfWriter.GetInstance(document, memStream);

                //open doc
                document.Open();

                // register all fonts in current computer
                FontFactory.RegisterDirectories();

                // Set factories
                var htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                // Set css
                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);



                //cssResolver.AddCss("th{background-color:#1caf9a;color:#ffffff;font-size:12px;padding:4px;}", true);
                cssResolver.AddCss("th{font-size:12px;padding:4px;color:#1caf9a;}", true);
                cssResolver.AddCss("td{font-size:12px;padding:4px;}", true);

                //  cssResolver.AddCss("table{border-left: solid 1px #dadada;border-top:solid 1px #ffffff;}", true);
                cssResolver.AddCss("img{display:none;}", true);
                cssResolver.AddCss("a{color:#1caf9a;font-size:12px;}", true);
                cssResolver.AddCss("h3{font-size:15px;float:right;text-align:right;width:20%;font-waight:bold;border:2px solid #1caf9a;}", true);
                cssResolver.AddCss("h2{font-size:16px;text-align:left;font-waight:bold;color:#1caf9a;}", true);
                cssResolver.AddCss("h5{font-size:12px;}", true);

                if (Session["css"] != null)
                {
                    if (Session["css"].ToString() == "invlist")
                    {
                        cssResolver.AddCss(".odd td{border-bottom:solid 1px #e0e0e0;padding:4px;}", true);
                        cssResolver.AddCss(".gridheader th{border-bottom:solid 1px #e0e0e0;}", true);
                        cssResolver.AddCss(".even td{border-bottom:solid 1px #e0e0e0;padding:4px;}", true);
                        cssResolver.AddCss(".bordercss{border-left:solid 1px #e0e0e0;}", true);
                        cssResolver.AddCss(".bordercss1{border-right:solid 1px #e0e0e0;}", true);
                    }
                    if (Session["css"].ToString() == "timeexp")
                    {
                        // cssResolver.AddCss(".aright{text-align:right;}", true);
                    }
                }



                // Export
                IPipeline pipeline = new CssResolverPipeline(cssResolver,
                                                             new HtmlPipeline(htmlContext,
                                                                              new PdfWriterPipeline(document, writer)));
                var worker   = new XMLWorker(pipeline, true);
                var xmlParse = new XMLParser(true, worker);
                xmlParse.Parse(xmlString);
                xmlParse.Flush();

                document.Close();
                document.Dispose();

                HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
            }

            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Flush();
        }