//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 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); } }
protected override void TransformHtml2Pdf(Document doc, PdfWriter pdfWriter, IImageProvider imageProvider, IFontProvider fontProvider, Stream cssFile) { ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); HtmlPipelineContext hpc; if (fontProvider != null) { hpc = new HtmlPipelineContext(new CssAppliersImpl(fontProvider)); } else { hpc = new HtmlPipelineContext(null); } hpc.SetImageProvider(imageProvider); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory()); HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter)); IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser xmlParse = new XMLParser(true, worker, Encoding.UTF8); xmlParse.Parse(new FileStream(inputHtml, FileMode.Open), Encoding.UTF8); }
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); }
/* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.ITagProcessor#content(com.itextpdf.tool.xml.Tag, * java.lang.String) */ public override IList <IElement> Content(IWorkerContext ctx, Tag tag, String content) { try { ICSSResolver cssResolver = GetCSSResolver(ctx); cssResolver.AddCss(content, false); } catch (CssResolverException e) { LOG.Error(LocaleMessages.GetInstance().GetMessage(LocaleMessages.STYLE_NOTPARSED), e); if (LOG.IsLogging(Level.TRACE)) { LOG.Trace(content); } } catch (NoCustomContextException) { LOG.Warn(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.CUSTOMCONTEXT_404_CONTINUE), typeof(CssResolverPipeline).FullName)); } return(new List <IElement>(0)); }
virtual public void AddingALinkProvider() { Document doc = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(TARGET + "columbus3.pdf", FileMode.Create)); doc.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetLinkProvider(new CustomLinkProvider()).SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(worker); p.Parse(File.OpenRead(RESOURCES + @"\examples\columbus.html")); doc.Close(); }
/// <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 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 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")); } }
/** * @param next the next pipeline. * @param cssResolver the {@link CSSResolver} to use in this IPipeline, it * will be stored in a ThreadLocal variable. */ public CssResolverPipeline(ICSSResolver cssResolver, IPipeline next) : base(next) { this.resolver = cssResolver; }
/** * Stores the cssResolver for the calling thread. * * @param resolver the CSSResolver to use. */ virtual public void SetResolver(ICSSResolver resolver) { this.resolver = resolver; }
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")); }
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())); } }
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(); }
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 ActionResult ExportToPDF(string id) { //downloadPDFID = id.ToString(); //NEW VERSION StringBuilder resultContainer = new StringBuilder(); StringWriter sw = new StringWriter(resultContainer); ViewContext viewContext = new ViewContext(ControllerContext, new WebFormView(ControllerContext, "~/Views/Document/PDFFormat.cshtml"), ViewData, TempData, sw); HtmlHelper helper = new HtmlHelper(viewContext, new ViewPage()); helper.RenderAction("PDFTemplate", new { vID = id }); sw.Flush(); sw.Close(); resultContainer.ToString(); //"This is output from other action" string html = resultContainer.ToString(); //string port = ""; //if (Request.Url.Port != null && Request.Url.Port != 0) //{ // port = ":" + Request.Url.Port.ToString(); //} ////string pdfTemplateURL = Request.Url.Scheme + "://" + Request.Url.Host + port + "/document/PDFTemplate/" + id; //string pdfTemplateURL = "http://" + Request.Url.Host + port + "/document/PDFTemplate/" + id; //WebRequestHelper reqHelper = new WebRequestHelper(pdfTemplateURL); //html = reqHelper.GetResponse(); /* * StringReader srdr = new StringReader(html); * Document pdfDoc = new Document(PageSize.A4, 15F, 15F, 75F, 0.2F); * * // HTML Worker allows us to parse the HTML Content to the PDF Document.To do this we will pass the object of Document class as a Parameter. * HTMLWorker hparse = new HTMLWorker(pdfDoc); * System.IO.MemoryStream ms = new System.IO.MemoryStream(); * // Finally we write data to PDF and open the Document * PdfWriter writer = PdfWriter.GetInstance(pdfDoc, ms); * pdfDoc.Open(); * * * var htmlContext = new HtmlPipelineContext(null); * htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); * * // Set css * ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); * cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/bootstrap.css"), true); * IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer))); * * var worker = new XMLWorker(pipeline, true); * var xmlParse = new XMLParser(true, worker); * * // Now we will pass the entire content that is stored in String reader to HTML Worker object to achieve the data from to String to HTML and then to PDF. * hparse.Parse(srdr); * * pdfDoc.Close(); * // Now finally we write to the PDF Document using the Response.Write method. * //Response.Write(pdfDoc); * // Response.End(); * * byte[] fileBytes = ms.ToArray(); * return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, "test.pdf"); */ var cssFiles = new List <string> { "~/Css/sitebootstrap.css", "~/Css/sitemain.css" }; var output = new MemoryStream(); var input = new MemoryStream(Encoding.UTF8.GetBytes(html)); 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); foreach (var file in cssFiles) { string path = Server.MapPath(file); ///cssResolver.AddCssFile(path, true); } //cssFiles.ForEach(i => cssResolver.AddCssFile(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; byte[] fileBytes = output.ToArray(); return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, "document-details.pdf")); }
/// <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); }
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); }
/** * Stores the cssResolver for the calling thread. * * @param resolver the CSSResolver to use. */ public void SetResolver(ICSSResolver resolver) { this.resolver = resolver; }
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); } }
public bool ConvertToPDF(string inputFile, string outputFile) { bool converted = false; try { HtmlDocument doc = new HtmlDocument(); doc.OptionFixNestedTags = true; doc.OptionWriteEmptyNodes = true; doc.OptionAutoCloseOnEnd = true; doc.Load(inputFile); string rootInner = doc.DocumentNode.InnerHtml; if (!rootInner.Contains("<html")) { doc.DocumentNode.InnerHtml = "<!DOCTYPE html>" + "\r\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">" + "\r\n\t<head>" + "\r\n\t\t<title>HTML to PDF</title>" + "\r\n\t</head>" + "\r\n\t<body>\r\n" + rootInner + "\r\n\t</body>" + "\r\n</html>"; } rootInner = doc.DocumentNode.InnerHtml; // Remove <meta> tag. string metaTag = @"<\s*(meta)(\s[^>]*)?>\s*"; while (Regex.IsMatch(rootInner, metaTag)) { string metaMatch = Regex.Match(rootInner, metaTag).Value; rootInner = rootInner.Replace(metaMatch, string.Empty); } rootInner = rootInner.Replace("</meta>", string.Empty); // Remove <form> tag. string formTag = @"<\s*(form)(\s[^>]*)?>\s*"; while (Regex.IsMatch(rootInner, formTag)) { string formMatch = Regex.Match(rootInner, formTag).Value; rootInner = rootInner.Replace(formMatch, string.Empty); } rootInner = rootInner.Replace("</form>", string.Empty); // Close br tag. string brTag = @"<\s*(br)(\s[^>]*)?>"; MatchCollection brMatches = Regex.Matches(rootInner, brTag); if (brMatches != null) { foreach (Match match in brMatches) { rootInner = rootInner.Replace(match.Value, "<br />"); } } // Replace <font> tag with div. string fontTag = @"<\s*(font)(\s[^>]*)?>"; while (Regex.IsMatch(rootInner, fontTag)) { string fontMatch = Regex.Match(rootInner, fontTag).Value; string toSpan = fontMatch.Replace("font", "div"); rootInner = rootInner.Replace(fontMatch, toSpan); } rootInner = rootInner.Replace("</font>", "</div>"); doc.DocumentNode.InnerHtml = rootInner; // Table elements var tableNodes = doc.DocumentNode.SelectNodes("//table"); if (tableNodes != null) { foreach (HtmlNode node in tableNodes) { bool isValidTable = false; if (node.HasChildNodes) { if ((node.SelectSingleNode("thead/tr/th") != null) || (node.SelectSingleNode("tbody/tr/td") != null) || (node.SelectSingleNode("tr/td") != null)) { isValidTable = true; } } // Remove invalid table (no tr, td tags). if (!isValidTable) { HtmlNode parent = node.ParentNode; parent.InnerHtml = " "; } bool hasStyle = node.Attributes.Contains("style"); if (!hasStyle) { node.Attributes.Add("style", string.Empty); } StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim()); if (!string.IsNullOrEmpty(styleValue.ToString())) { if (!styleValue.ToString().EndsWith(";")) { styleValue.Append(";"); } } if (node.Attributes.Contains("cellspacing")) { if (!styleValue.ToString().Contains("border-collapse")) { styleValue.Append("border-collapse: collapse; "); } node.Attributes.Remove("cellspacing"); } if (node.Attributes.Contains("cellpadding")) { if (!styleValue.ToString().Contains("cellpadding")) { styleValue.Append("padding: " + node.Attributes["cellpadding"].Value + "px; "); } node.Attributes.Remove("cellpadding"); } if (node.Attributes.Contains("border")) { if (!styleValue.ToString().Contains("border")) { styleValue.Append("border: " + node.Attributes["border"].Value + "; "); } node.Attributes.Remove("border"); } if (node.Attributes.Contains("width")) { string width = node.Attributes["width"].Value; if (node.Attributes["width"].Value.EndsWith("%")) { width = node.Attributes["width"].Value; } else { if (node.Attributes["width"].Value.EndsWith("px")) { width = node.Attributes["width"].Value; } else { width = node.Attributes["width"].Value + "px"; } } styleValue.Append("width: " + width + "; "); node.Attributes.Remove("width"); } if (node.Attributes.Contains("height")) { string height = node.Attributes["height"].Value.EndsWith("px") ? node.Attributes["height"].Value : node.Attributes["height"].Value + "px; "; styleValue.Append("height: " + height); node.Attributes.Remove("height"); } if (node.Attributes.Contains("align")) { styleValue.Append("text-align: " + node.Attributes["align"].Value + "; "); node.Attributes.Remove("align"); } node.Attributes["style"].Value = styleValue.ToString(); } } // Remove div from /div/img path. var imgNodes = doc.DocumentNode.SelectNodes("//div/img"); while (imgNodes != null) { foreach (HtmlNode node in imgNodes) { node.InnerHtml = " "; HtmlNode td = node.ParentNode.ParentNode; td.RemoveChild(node.ParentNode, true); } imgNodes = doc.DocumentNode.SelectNodes("//div/img"); } // Remove div with class="Top_Hidden". var divHiddenNodes = doc.DocumentNode.SelectNodes("//div[@class='Top_Hidden']"); while (divHiddenNodes != null) { foreach (HtmlNode node in divHiddenNodes) { HtmlNode tatay = node.ParentNode; tatay.RemoveChild(node, false); } divHiddenNodes = doc.DocumentNode.SelectNodes("//div[@class='Top_Hidden']"); } // Remove children for div with class="blank". var divBlankNodes = doc.DocumentNode.SelectNodes("//div[@class='blank']"); if (divBlankNodes != null) { foreach (HtmlNode node in divBlankNodes) { node.RemoveAllChildren(); } } // Close img tag from /td/img path. var tdImgNodes = doc.DocumentNode.SelectNodes("//td/img"); if (tdImgNodes != null) { foreach (HtmlNode node in tdImgNodes) { node.InnerHtml = " "; } } // Add style to div tag. var divNodes = doc.DocumentNode.SelectNodes("//div"); if (divNodes != null) { foreach (HtmlNode node in divNodes) { if (node.HasAttributes) { bool hasStyle = node.Attributes.Contains("style"); if (!hasStyle) { node.Attributes.Add("style", string.Empty); } StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim()); if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";")) { styleValue.Append(";"); } if (node.Attributes.Contains("face")) { string fontFamily = node.Attributes["face"].Value; styleValue.Append("font-family: " + fontFamily.ToLower() + ";"); node.Attributes.Remove("face"); } if (node.Attributes.Contains("size")) { string fontSize = node.Attributes["size"].Value; string size = "9pt"; switch (fontSize) { case "1": { size = "7pt"; break; } case "2": { size = "9pt"; break; } case "3": { size = "10pt"; break; } case "4": { size = "12pt"; break; } case "5": { size = "16pt"; break; } case "6": { size = "20pt"; break; } case "7": { size = "30pt"; break; } default: break; } styleValue.Append("font-size: " + size.ToLower() + ";"); node.Attributes.Remove("size"); } node.Attributes["style"].Value = styleValue.ToString(); } } } // Add td style. var tdNodes = doc.DocumentNode.SelectNodes("//td"); if (tdNodes != null) { foreach (HtmlNode node in tdNodes) { bool hasStyle = node.Attributes.Contains("style"); if (!hasStyle) { node.Attributes.Add("style", string.Empty); } StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim()); if (!string.IsNullOrEmpty(styleValue.ToString())) { if (!styleValue.ToString().EndsWith(";")) { styleValue.Append("; "); } } if (node.Attributes.Contains("align")) { styleValue.Append("text-align: " + node.Attributes["align"].Value + "; "); node.Attributes.Remove("align"); } else { styleValue.Append("text-align: left;"); } if (node.Attributes.Contains("valign")) { styleValue.Append("vertical-align: " + node.Attributes["valign"].Value + "; "); node.Attributes.Remove("valign"); } if (node.Attributes.Contains("width")) { string width = node.Attributes["width"].Value; if (node.Attributes["width"].Value.EndsWith("%")) { width = node.Attributes["width"].Value; } else { if (node.Attributes["width"].Value.EndsWith("px")) { width = node.Attributes["width"].Value; } else { width = node.Attributes["width"].Value + "px"; } } styleValue.Append("width: " + width + "; "); node.Attributes.Remove("width"); } if (!string.IsNullOrEmpty(styleValue.ToString())) { node.Attributes["style"].Value = styleValue.ToString(); } } } // Add style to p tag. var pNodes = doc.DocumentNode.SelectNodes("//p"); if (pNodes != null) { foreach (HtmlNode node in pNodes) { if (node.HasAttributes) { bool hasStyle = node.Attributes.Contains("style"); if (!hasStyle) { node.Attributes.Add("style", string.Empty); } StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim()); if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";")) { styleValue.Append(";"); } if (node.Attributes.Contains("align")) { string value = node.Attributes["align"].Value; styleValue.Append("text-align: " + value.ToLower() + ";"); node.Attributes.Remove("align"); } node.Attributes["style"].Value = styleValue.ToString(); } } } // Remove u tag from //u/div path but put underline in div tag. var uDivNodes = doc.DocumentNode.SelectNodes("//u/div"); while (uDivNodes != null) { foreach (HtmlNode node in uDivNodes) { bool hasStyle = node.Attributes.Contains("style"); if (!hasStyle) { node.Attributes.Add("style", string.Empty); } StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim()); if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";")) { styleValue.Append(";"); } styleValue.Append("text-decoration: underline;"); node.Attributes["style"].Value = styleValue.ToString(); HtmlNode lolo = node.ParentNode.ParentNode; lolo.RemoveChild(node.ParentNode, true); } uDivNodes = doc.DocumentNode.SelectNodes("//u/div"); } // Remove strong tag from //strong/div path but put bold in div tag. var strongDivNodes = doc.DocumentNode.SelectNodes("//strong/div"); while (strongDivNodes != null) { foreach (HtmlNode node in strongDivNodes) { bool hasStyle = node.Attributes.Contains("style"); if (!hasStyle) { node.Attributes.Add("style", string.Empty); } StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim()); if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";")) { styleValue.Append(";"); } styleValue.Append("font-weight: bold;"); node.Attributes["style"].Value = styleValue.ToString(); HtmlNode lolo = node.ParentNode.ParentNode; lolo.RemoveChild(node.ParentNode, true); } strongDivNodes = doc.DocumentNode.SelectNodes("//strong/div"); } // Replace p tag with div from //p/div path. var pDivNodes = doc.DocumentNode.SelectNodes("//p/div"); while (pDivNodes != null) { foreach (HtmlNode node in pDivNodes) { node.ParentNode.Name = "div"; } pDivNodes = doc.DocumentNode.SelectNodes("//p/div"); } // Remove div tag from //ol/div path. var olDivNodes = doc.DocumentNode.SelectNodes("//ol/div"); while (olDivNodes != null) { foreach (HtmlNode node in olDivNodes) { HtmlNode tatay = node.ParentNode; bool hasStyle = node.Attributes.Contains("style"); if (hasStyle) { tatay.Attributes.Add(node.Attributes["style"]); } tatay.RemoveChild(node, true); } olDivNodes = doc.DocumentNode.SelectNodes("//ol/div"); } // Remove div tag from //ul/div path. var ulDivNodes = doc.DocumentNode.SelectNodes("//ul/div"); while (ulDivNodes != null) { foreach (HtmlNode node in ulDivNodes) { HtmlNode tatay = node.ParentNode; bool hasStyle = node.Attributes.Contains("style"); if (hasStyle) { tatay.Attributes.Add(node.Attributes["style"]); } tatay.RemoveChild(node, true); } ulDivNodes = doc.DocumentNode.SelectNodes("//ul/div"); } // Remove div tag from //li/div path. var liDivNodes = doc.DocumentNode.SelectNodes("//li/div"); while (liDivNodes != null) { foreach (HtmlNode node in liDivNodes) { HtmlNode tatay = node.ParentNode; bool hasStyle = node.Attributes.Contains("style"); if (hasStyle) { tatay.Attributes.Add(node.Attributes["style"]); } tatay.RemoveChild(node, true); } liDivNodes = doc.DocumentNode.SelectNodes("//li/div"); } // Save the modified html to a new name. string formattedHTMLFile = outputFile.Replace(".pdf", string.Empty) + "_TEMP.html"; doc.Save(formattedHTMLFile); HtmlDocument docCPM = new HtmlDocument(); docCPM.OptionFixNestedTags = true; docCPM.OptionWriteEmptyNodes = true; docCPM.OptionAutoCloseOnEnd = true; string newHTML = outputFile.Replace(".pdf", string.Empty) + "_PDF.html"; docCPM.Load(formattedHTMLFile); docCPM.Save(newHTML); FontFactory.RegisterDirectories(); Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFile, FileMode.Create)); try { document.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); CustomImageProvider imageProvider = new CustomImageProvider(); htmlContext.SetImageProvider(imageProvider); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(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(new StreamReader(newHTML)); //XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, new StreamReader(newHTMLFile)); converted = true; } catch { converted = false; throw; } finally { if (document.IsOpen()) { document.Close(); } if (writer != null) { writer.Close(); } File.Delete(formattedHTMLFile); File.Delete(newHTML); } } catch { converted = false; throw; } finally { } return(converted); }