public static byte[] Render(string html, List <string> cssFiles = null, Rectangle pageSize = null) { if (pageSize == null) { pageSize = PageSize.A4.Rotate(); } using (var stream = new MemoryStream()) { // create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF using (var document = new Document(pageSize)) { // create a writer that's bound to our PDF abstraction and our stream using (var writer = PdfWriter.GetInstance(document, stream)) { // open the document for writing document.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); ITagProcessorFactory factory = Tags.GetHtmlTagProcessorFactory(); factory.AddProcessor(new CustomImageHTMLTagProcessor(), new string[] { "img" }); htmlContext.SetTagFactory(factory); var isAnyCssFiles = cssFiles != null && cssFiles.Count > 0; //create a cssresolver to apply css ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(!isAnyCssFiles); if (isAnyCssFiles) { foreach (var cssfile in cssFiles) { if (cssfile.StartsWith("http")) { cssResolver.AddCssFile(cssfile, true); } else { cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(cssfile), true); } } } //create and attach pipeline IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser xmlParser = new XMLParser(true, worker); using (var srHtml = new StringReader(html)) { xmlParser.Parse(srHtml); } // close document document.Close(); } } // get bytes from stream byte[] bytes = stream.ToArray(); bytes = AddPageNumbers(bytes, pageSize); // success return(bytes); } }
//private byte[] parseHtml(String html) //{ // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // step 1 // Document document = new Document(); // // step 2 // PdfWriter writer = PdfWriter.getInstance(document, baos); // // step 3 // document.open(); // // step 4 // XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, // new FileInputStream(html)); // // step 5 // document.close(); // // return the bytes of the PDF // return baos.toByteArray(); //} private byte[] ConvertHtmlToPdf(string html, string cssPath) { Document document = new Document(PageSize.A1); byte[] pdfBytes; using (var ms = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); writer.CloseStream = false; document.Open(); HtmlPipelineContext htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(cssPath, true); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, writer))); XMLWorker xmlWorker = new XMLWorker(pipeline, true); XMLParser xmlParser = new XMLParser(xmlWorker); xmlParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(html))); // document.NewPage(); document.Close(); pdfBytes = ms.GetBuffer(); } return(pdfBytes); }
private byte[] BindPdf(string pHTML) { var cssText = "~/Content/css/facture.css"; byte[] bPDF = null; var memoryStream = new MemoryStream(); var input = new MemoryStream(Encoding.UTF8.GetBytes(pHTML)); var document = new Document(PageSize.A4, 10f, 10f, 100f, 0f); var writer = PdfWriter.GetInstance(document, memoryStream); writer.CloseStream = false; document.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(cssText), true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var p = new XMLParser(worker); p.Parse(input); document.Close(); bPDF = memoryStream.ToArray(); return(bPDF); }
public FileResult Export(string GridHtml) { List <string> cssFiles = new List <string>(); cssFiles.Add(@"/Content/bootstrap.css"); var output = new MemoryStream(); var input = new MemoryStream(Encoding.UTF8.GetBytes(GridHtml)); var document = new Document(); var writer = PdfWriter.GetInstance(document, output); writer.CloseStream = false; document.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssFiles.ForEach(i => cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(i), true)); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var p = new XMLParser(worker); p.Parse(input); document.Close(); output.Position = 0; return(File(output.ToArray(), "application/pdf", "Reporte.pdf")); }
/*-------------------------------------------------------- * 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[] GeneratePDF2(string name) { byte[] result; string Path = AppDomain.CurrentDomain.BaseDirectory; Path = Path.Substring(0, Path.Length - 10); var Pathcss = string.Format("{0}{1}", Path, "htmltoPdf\\Content\\bootstrap.min.css"); List <string> cssFile = new List <string>(); cssFile.Add(Pathcss); MemoryStream stream = null; string Html = html(); string ModifiedFileName = string.Empty; using (stream = new MemoryStream()) { Document pdfDoc = new Document(PageSize.A4, 60f, 60f, 50f, 40f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); writer.PageEvent = new NumPage(); pdfDoc.Open(); HtmlPipelineContext htmlcontext = new HtmlPipelineContext(null); htmlcontext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(Pathcss, true); //cssFile.ForEach(x=>cssResolver.AddCssFile(x,true)); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlcontext, new PdfWriterPipeline(pdfDoc, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser xmlparser = new XMLParser(worker); xmlparser.Parse(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(Html))); pdfDoc.Close(); result = stream.GetBuffer(); //PdfReader reader = new PdfReader(stream); //PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting); //reader.Close(); //return File(stream.ToArray(), "application/pdf", "Grid.pdf"); } return(result); }
/// <summary> /// CREATE A PDF FILE FROM BOTH VALID HTML AND CSS SOURCES /// </summary> /// <param name="htmlContent">A Well Formed html Document. IMAGE PATH MUST BE LOADED AT RUNTIME. </param> /// <param name="cssPath">Path to a valid css file</param> /// <param name="resultsFilePath">Output path to the resulting pdf</param> public static void GetPDFFile(string htmlContent, string cssPath, string resultsFilePath) { //----------------------------------------------- // INICIAR VARIABLES //----------------------------------------------- List <string> cssFiles = new List <string>(); cssFiles.Add(cssPath); var output = new MemoryStream(); var input = new MemoryStream(Encoding.UTF8.GetBytes(htmlContent)); var document = new Document(); var writer = PdfWriter.GetInstance(document, output); writer.CloseStream = false; document.Open(); //----------------------------------------------- // AÑADIR Y ANALIZAR CSS + HTML //----------------------------------------------- var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssFiles.ForEach(i => cssResolver.AddCssFile(i, true)); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var p = new XMLParser(worker); p.Parse(input); document.Close(); output.Position = 0; //----------------------------------------------- // GUARDAR ARCHIVO //----------------------------------------------- using (FileStream file = new FileStream(resultsFilePath, FileMode.Create, FileAccess.Write)) { output.WriteTo(file); } }
public ActionResult generaPDF() { using (MemoryStream stream = new MemoryStream()) { StringWriter stringWriter = new StringWriter(); System.Web.HttpContext.Current.Response.Clear(); ViewEngineResult viewEngineResult = ViewEngines.Engines.FindView(controllerContext, vistaReporte, null); ViewContext viewContext = new ViewContext(controllerContext, viewEngineResult.View, new ViewDataDictionary(model), temporalData, stringWriter); viewEngineResult.View.Render(viewContext, stringWriter); String HtmlString = stringWriter.ToString(); List <string> cssFiles = new List <string>(); cssFiles.Add("~/Content/Styles/Site/Site.css"); cssFiles.Add("~/Content/Styles/Account/all.css"); cssFiles.Add("~/Content/Librerias/JQuery.UI/jquery-ui.theme.css"); cssFiles.Add("~/Content/Librerias/JQuery.UI/jquery-ui.structure.css"); cssFiles.Add("~/Content/Styles/Site/ReportesPDF.css"); Document Pdf = new Document(PageSize.A4); StringReader stringReader = new StringReader(HtmlString); PdfWriter write = PdfWriter.GetInstance(Pdf, stream); write.CloseStream = false; Pdf.Open(); HtmlPipelineContext htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver iCSSResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssFiles.ForEach(x => iCSSResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(x), true)); IPipeline pipeline = new CssResolverPipeline(iCSSResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(Pdf, write))); XMLWorker xMLWorkerHelper = new XMLWorker(pipeline, true); XMLParser xMLParse = new XMLParser(xMLWorkerHelper); xMLParse.Parse(new MemoryStream(Encoding.UTF8.GetBytes(HtmlString))); Pdf.Close(); using (FileStream fileStream = System.IO.File.Create(ruta + nombreDeReporte + ".pdf")) { fileStream.Write(stream.ToArray(), 0, stream.ToArray().Length); } return(File(ruta + nombreDeReporte + ".pdf", System.Net.Mime.MediaTypeNames.Application.Octet, nombreDeReporte + ".pdf")); } }
public static byte[] CreatePDF(string htmlContent, string cssPath) { using (MemoryStream stream = new System.IO.MemoryStream()) { Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(cssPath, true); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser parser = new XMLParser(worker); parser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(htmlContent))); pdfDoc.Close(); return(stream.GetBuffer()); } }
public ActionResult CreatePdf2(string idcod) { //var user = ApplicationDbContext.Users.Find(GetActualUserId().Id); //var cert = ApplicationDbContext.Certifications.FirstOrDefault(x => x.Enrollment.Modu_Id == id && x.User_Id == user.Id); //var enrollments = ApplicationDbContext.Enrollments.Single(x => x.Modu_Id == id && x.User_Id == user.Id); Session["idcod"] = idcod; //var Nombrestu = ApplicationDbContext.Personas.First(x=> x.Pers_Cod == idcod ); //ViewBag.Message = nombreestu; //var otro = "Estudiante" + ViewBag.Message; var inputString = @"<html> <body> <div class='form-horizontal'> <br /> <br /> <div class='form-row'> <div class='col-sm-6'> < img src='C:/Users/ADMIN/source/repos/AlianzaPetrolera12/AlianzaPetrolera1/AlianzaPetrolera/Content/images/logo.png'width='200px';height='250px'/> </ div > <div class='col-sm-6' style='margin-top:2em;'> <h5 ALIGN = 'RIGHT' style='font-family:Arial Black, Gadget, sans-serif; font-size: 35px;color:#0A122A;'>N° Recibo: " + Session["idcod"] + @"</h5> </div> </div> <hr /> <br /> <div class='row'> <div class='col-sm-8'> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>Estudiante:" + Session["idcod"] + @"</h6> </div> <div class='col-sm-4'> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>Fecha Y Generalización Recibo</h6> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>" + DateTime.Now + @"</h6> </div> </div> <hr /> <br /> <div class='row'> <div class='col-sm-8'> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>Tipo Cuenta: Ahorros</h6> </div> <div class='col-sm-4'> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>Bancolombia</h6> </div> <div class='col-sm-12'> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>#1215684-154541-12152</h6> </div> </div> <hr /> <br /> <div class='container' style=' border: 1px solid; border - color: #A59D9B; padding:10px 10px 10px 10px;'> <div class='container'> <form method='post'> <table class='egt'> <tr> <th scope='row'>Matricula</th> <th> Poliza Accidentes: </th> <th> Uniforme : </th> <th> Mensualidad : </th> </ tr > <tr> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>$ 80.000</h6> </td> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>$ 10.000</h6> </td> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>$ 50.000</h6> </td> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>$ 80.000</h6> </td> </tr> <tr> <th>Descuento </th> <th>Descuento </th> <th>Descuento </th> <th>Descuento </th> </tr> <tr> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>5 %</h6> </td> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>10 %</h6> </td> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>15 %</h6> </td> <td> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>20 %</h6> </td> </tr> </table> <div class='col-sm-12'> <h6 style='font-family:Arial Black, Gadget, sans-serif; font-size: 15px;color:#0A122A;'>Total a Pagar: ""</h6> </div> </form > </div> </div> </div> </body> </html>"; // < div style = 'float:left;width:550px;height='200px; '> // < h4 style = 'font-family:Arial Black, Gadget, sans-serif; font-size: 70px;color:#0A122A;' > CERTIFICADO </ h4 > // </ div > // < div style = 'float:right;' > // < img src = 'http://localhost/SaludVida/Recursos/logo-campana.png'width = '150px'; height = '150px' /> // </ div > // < H3 ALIGN = 'center'style = 'font-family:Arial Black, Gadget, sans-serif; font-size: 40px; margin: -20px;color:#0A122A;' >< strong > Otorgado a:</ strong > </ H3 > // < br ></ br > // < h3 ALIGN = 'center' style = 'font-family:Britannic Bold; font-size: 30px;color:#FF9800;' ></ h3 > // < h4 ALIGN = 'center'style = 'font-family:Britannic Bold;' > Identificado(a) con cédula de ciudadanía número </ h4 > // < H4 ALIGN = 'center'style = 'font-family:Britannic Bold;' > Por haber aprobado el curso virtual de:</H4> // < H4 ALIGN = 'center'style='font-family:Arial Black,Gadget,sans-serif; font-size: 60px;color:#0A122A;' > </ H4 > // < h4 ALIGN = 'center'style='font-family:Britannic Bold;'>En testimonio de lo anterior se firma en</h4> // <div ALIGN = 'center' > // < br ></ br >< br ></ br > // < h3 ALIGN= 'center'style= 'font-family:Arial Black, Gadget, sans-serif;color:#000;' > ________________________ </ h3 > // < h3 ALIGN= 'center'style= 'font-family:Arial Black, Gadget, sans-serif;color:#000;' > Camilo Jaramillo Botero</h3> // <h5 ALIGN = 'center'style= 'font-family:Arial Black, Gadget, sans-serif;color:#000;' > Gerente de Ventas y Mercadeo</h5> // </div> // <div style = 'float:left' > // </ div > // List <string> cssFiles = new List <string>(); cssFiles.Add(@"/Content/bootstrap.css"); var output = new MemoryStream(); var input = new MemoryStream(Encoding.UTF8.GetBytes(inputString)); Document document = new Document(PageSize.A4); var writer = PdfWriter.GetInstance(document, output); writer.CloseStream = false; document.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssFiles.ForEach(i => cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(i), true)); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var p = new XMLParser(worker); p.Parse(input); document.Close(); output.Position = 0; Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment; filename=Certificado.pdf"); Response.BinaryWrite(output.ToArray()); Response.Flush(); Response.Close(); Response.End(); return(RedirectToAction("Report_Person")); }
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); } }
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 static void GeneratePdf(IList <SqlPdfFormat> data, string pdfFullFileName, string cssFullFileName) { data.OrderBy(x => x.SoldDate); DateTime oldDate = data[0].SoldDate; StringBuilder sb = new StringBuilder(); decimal subSum = 0; decimal totalSum = 0; sb.Append("<table>"); sb.Append("<tr>"); sb.Append("<th colspan=\"5\" class=\"title\">Aggregated Sales Report </th>"); sb.Append("</tr>"); sb.Append("<tr class=\"grayBack\" >"); sb.AppendFormat("<th colspan=\"5\" class=\"date\">Date: {0}</th>", oldDate.ToShortDateString()); sb.Append("</tr>"); sb.Append("<tr class=\"grayBack\" >"); sb.Append("<th class=\"th\">Product</th>"); sb.Append("<th class=\"th\">Quantity</th>"); sb.Append("<th class=\"th\">Unit Price</th>"); sb.Append("<th class=\"th\">Location</th>"); sb.Append("<th class=\"th\">Sum</th>"); sb.Append("</tr>"); for (int i = 0; i < data.Count; i++) { if (data[i].SoldDate > oldDate) { sb.Append("<tr>"); sb.AppendFormat("<td colspan=\"4\" class=\"sum\">Total sum for {0}: </td>", oldDate.ToShortDateString()); sb.AppendFormat("<td class=\"bold\">{0}</td>", subSum); sb.Append("</tr>"); oldDate = data[i].SoldDate; totalSum += subSum; subSum = 0; sb.Append("<tr class=\"grayBack\">"); sb.AppendFormat("<th colspan=\"5\" class=\"date\">Date: {0}</th>", oldDate.ToShortDateString()); sb.Append("</tr>"); sb.Append("<tr class=\"grayBack\">"); sb.Append("<th class=\"th\">Product</th>"); sb.Append("<th class=\"th\">Quantity</th>"); sb.Append("<th class=\"th\">Unit Price</th>"); sb.Append("<th class=\"th\">Location</th>"); sb.Append("<th class=\"th\">Sum</th>"); sb.Append("</tr>"); } subSum += data[i].Sum; sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", data[i].ProductName); sb.AppendFormat("<td>{0}</td>", data[i].Quantity + " " + data[i].Measure); sb.AppendFormat("<td>{0}</td>", data[i].UnitPrice); sb.AppendFormat("<td>{0}</td>", data[i].SupermarketName); sb.AppendFormat("<td>{0}</td>", data[i].Sum); sb.Append("</tr>"); } sb.Append("<tr>"); sb.AppendFormat("<td colspan=\"4\" class=\"sum\">Total sum for {0}: </td>", oldDate.ToShortDateString()); sb.AppendFormat("<td class=\"bold\">{0}</td>", subSum); sb.Append("</tr>"); totalSum += subSum; sb.Append("<tr>"); sb.Append("<td colspan=\"4\" class=\"sum\">Grand Total: </td>"); sb.AppendFormat("<td class=\"bold\">{0}</td>", totalSum); sb.Append("</tr>"); sb.Append("</table>"); using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFullFileName, FileMode.Create)); document.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); //change this to your CCS file location cssResolver.AddCssFile(cssFullFileName, true); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(worker); //p.Parse((TextReader)File.OpenText(@"G:\Template.html")); p.Parse(new StringReader(sb.ToString())); } }