public static ElementList ParseToElementList(string html, string css) { ICSSResolver iCSSResolver = new StyleAttrCSSResolver(); if (css != null) { ICssFile cSS = XMLWorkerHelper.GetCSS(new MemoryStream(Encoding.Default.GetBytes(css))); iCSSResolver.AddCss(cSS); } MyFontsProvider fontProvider = new MyFontsProvider(); CssAppliers cssAppliers = new CssAppliersImpl(fontProvider); //CssAppliers cssAppliers = new CssAppliersImpl(FontFactory.FontImp); HtmlPipelineContext htmlPipelineContext = new HtmlPipelineContext(cssAppliers); htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlPipelineContext.AutoBookmark(false); ElementList elementList = new ElementList(); ElementHandlerPipeline next = new ElementHandlerPipeline(elementList, null); HtmlPipeline next2 = new HtmlPipeline(htmlPipelineContext, next); CssResolverPipeline pipeline = new CssResolverPipeline(iCSSResolver, next2); XMLWorker listener = new XMLWorker(pipeline, true); XMLParser xMLParser = new XMLParser(listener); //因为XMLWork不支持html的单标签,所以要对单标签进行过滤。不然就会报错:Invalid nested tag div found, expected closing tag br html = html.Replace("<br>", "").Replace("<hr>", "").Replace("<img>", "").Replace("<param>", "") .Replace("<link>", ""); //xMLParser.Parse(new MemoryStream(Encoding.Default.GetBytes(html))); xMLParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(html))); return(elementList); }
public void ConvertHtmlToPdf() { using (var stream = new FileStream(OUTPUT_FILE, FileMode.Create)) { using (var document = new Document()) { var writer = PdfWriter.GetInstance(document, stream); document.Open(); var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory(); // custom tag processor above tagProcessorFactory.AddProcessor( new CustomHorizontalRule(), new string[] { HTML.Tag.HR } ); var htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(tagProcessorFactory); var pdfWriterPipeline = new PdfWriterPipeline(document, writer); var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); var cssResolverPipeline = new CssResolverPipeline( cssResolver, htmlPipeline ); var worker = new XMLWorker(cssResolverPipeline, true); var parser = new XMLParser(worker); var xHtml = "<hr style='border:1px dotted red' />"; using (var stringReader = new StringReader(xHtml)) { parser.Parse(stringReader); } } } }
/** * Parses an HTML string and a string containing CSS into a list of Element objects. * The FontProvider will be obtained from iText's FontFactory object. * * @param html a String containing an XHTML snippet * @param css a String containing CSS * @return an ElementList instance */ public static ElementList ParseToElementList(String html, String css) { // CSS ICSSResolver cssResolver = new StyleAttrCSSResolver(); if (css != null) { ICssFile cssFile = XMLWorkerHelper.GetCSS(new MemoryStream(Encoding.Default.GetBytes(css))); cssResolver.AddCss(cssFile); } // HTML CssAppliers cssAppliers = new CssAppliersImpl(FontFactory.FontImp); HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.AutoBookmark(false); // Pipelines ElementList elements = new ElementList(); ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null); HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end); CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline); // XML Worker XMLWorker worker = new XMLWorker(cssPipeline, true); XMLParser p = new XMLParser(worker); p.Parse(new MemoryStream(Encoding.Default.GetBytes(html))); return(elements); }
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 void ConvertHtmlToPdf(string xHtml, string css) { // instantiate custom tag processor and add to `HtmlPipelineContext`. var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory(); //tagProcessorFactory.AddProcessor( // new TableDataProcessor(), // new string[] { HTML.Tag.TD } //); var htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(tagProcessorFactory); var pdfWriterPipeline = new PdfWriterPipeline(this.PdfDoc, this.Writer); var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline); // get an ICssResolver and add the custom CSS var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); cssResolver.AddCss(css, "utf-8", true); var cssResolverPipeline = new CssResolverPipeline( cssResolver, htmlPipeline ); var worker = new XMLWorker(cssResolverPipeline, true); var parser = new XMLParser(worker); using (var stringReader = new StringReader(xHtml)) { parser.Parse(stringReader); } }
public static byte[] ConvertHtmltoPdf(ClientContext context, Microsoft.SharePoint.Client.List documentLibrary, string result, string nameOfTheFile) { using (var msOutput = new MemoryStream()) { using (var stringReader = new StringReader(result)) { using (Document document = new Document()) { var pdfWriter = PdfWriter.GetInstance(document, msOutput); pdfWriter.InitialLeading = 12.5f; document.Open(); var xmlWorkerHelper = XMLWorkerHelper.GetInstance(); var cssResolver = new StyleAttrCSSResolver(); var xmlWorkerFontProvider = new XMLWorkerFontProvider(); //foreach (string font in fonts) //{ // xmlWorkerFontProvider.Register(font); //} var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider); var htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); PdfWriterPipeline pdfWriterPipeline = new PdfWriterPipeline(document, pdfWriter); HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfWriterPipeline); CssResolverPipeline cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker xmlWorker = new XMLWorker(cssResolverPipeline, true); XMLParser xmlParser = new XMLParser(xmlWorker); xmlParser.Parse(stringReader); } } return(msOutput.ToArray()); } }
public byte[] GetPDF(string conteudo, string cssFile) { Document doc = new Document(PageSize.A4, 50, 50, 50, 50); using (var ms = new MemoryStream()) { var writer = PdfWriter.GetInstance(doc, ms); writer.CloseStream = false; doc.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); var cssResolver = XMLWorkerHelper.GetInstance() .GetDefaultCssResolver(false); cssResolver.AddCssFile(cssFile, true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer))); var worker = new XMLWorker(pipeline, true); var xmlParser = new XMLParser(worker); xmlParser.Parse(new MemoryStream(Encoding.UTF8 .GetBytes(conteudo))); doc.Close(); return(ms.GetBuffer()); } }
public static string ConvertHtmlToPdf(string htmlContent, string fileNameWithoutExtension, string filePath, string cssContent = "") { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } var fileNameWithPath = Path.Combine(filePath, fileNameWithoutExtension + ".pdf"); using (var stream = new FileStream(fileNameWithPath, FileMode.Create)) { using (var document = new Document()) { var writer = PdfWriter.GetInstance(document, stream); document.Open(); // instantiate custom tag processor and add to `HtmlPipelineContext`. var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory(); tagProcessorFactory.AddProcessor(new TableData(), new string[] { HTML.Tag.TD }); var htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(tagProcessorFactory); var pdfWriterPipeline = new PdfWriterPipeline(document, writer); var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline); // get an ICssResolver and add the custom CSS var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); cssResolver.AddCss(cssContent, "utf-8", true); var cssResolverPipeline = new CssResolverPipeline( cssResolver, htmlPipeline); var worker = new XMLWorker(cssResolverPipeline, true); var parser = new XMLParser(worker); using (var stringReader = new StringReader(htmlContent)) { parser.Parse(stringReader); } } } return(fileNameWithPath); }
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")); }
private MemoryStream GetPDFStream(string htmlContent, string CSSContent) { iTextSharp.text.Document document = new iTextSharp.text.Document(); try { MemoryStream memStream = new System.IO.MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, memStream); document.Open(); var interfaceProps = new Dictionary <string, Object>(); var ih = new ImageHander() { BaseUri = Request.Url.ToString() }; interfaceProps.Add(HTMLWorker.IMG_PROVIDER, ih); var cssResolver = new StyleAttrCSSResolver(); var CSSStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(CSSContent)); var cssFile = XMLWorkerHelper.GetCSS(CSSStream); cssResolver.AddCss(cssFile); CssAppliers ca = new CssAppliersImpl(); HtmlPipelineContext hpc = new HtmlPipelineContext(ca); hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer); CssResolverPipeline css = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, pdf)); XMLWorker xworker = new XMLWorker(css, true); XMLParser p = new XMLParser(xworker); var HTMLStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlContent)); var CSSStream1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(CSSContent)); using (TextReader sr = new StringReader(htmlContent)) { XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, HTMLStream, CSSStream1); //p.Parse(sr); } writer.CloseStream = false; document.Close(); return(memStream); } catch (Exception ex) { document.Close(); litPdfViewMsg.Text = ex.Message; //throw ex; return(null); } }
private byte[] InternalGeneratePdf <T>(Action <PdfWriter, Document> configureSettings, T model = null, string viewName = null, List <BasePageSnippet> pageSnippets = null, Margins margins = null) where T : class { ControllerContext.Controller.ViewData.Model = model; byte[] output; var document = margins == null ? new Document() : new Document(margins.PageSize, margins.Left, margins.Right, margins.Top, margins.Bottom); using (document) { using (var workStream = new MemoryStream()) { var writer = PdfWriter.GetInstance(document, workStream); writer.CloseStream = false; if (pageSnippets != null) { var aggregateHelper = new AggregateHelper(pageSnippets, InternalGeneratePdf); writer.PageEvent = aggregateHelper; } configureSettings?.Invoke(writer, document); document.Open(); using (var reader = new StringReader(RenderRazorView(viewName))) { var workerInstance = XMLWorkerHelper.GetInstance(); var tagProcessors = Tags.GetHtmlTagProcessorFactory(); if (!string.IsNullOrEmpty(ImageBasePath)) { tagProcessors.RemoveProcessor(HTML.Tag.IMG); tagProcessors.AddProcessor(new ImageTagProcessor(ImageBasePath), new[] { HTML.Tag.IMG }); } var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(tagProcessors); var cssResolver = workerInstance.GetDefaultCssResolver(true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(worker); parser.Parse(reader); document.Close(); output = workStream.ToArray(); } } } return(output); }
/*-------------------------------------------------------- * 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[] GeneratePdf <T>(Action <PdfWriter, Document> configureSettings, T model = null, string viewName = null) where T : class { byte[] output; var document = Margins == null ? new Document() : new Document(Margins.PageSize, Margins.Left, Margins.Right, Margins.Top, Margins.Bottom); using (document) { using (var workStream = new MemoryStream()) { var writer = PdfWriter.GetInstance(document, workStream); writer.CloseStream = false; configureSettings?.Invoke(writer, document); document.Open(); var renderedView = Parser.RenderView(viewName, model, Templates); using (var reader = new StringReader(renderedView)) { var workerInstance = XMLWorkerHelper.GetInstance(); var tagProcessors = Tags.GetHtmlTagProcessorFactory(); if (!string.IsNullOrEmpty(ImageBasePath)) { tagProcessors.RemoveProcessor(HTML.Tag.IMG); tagProcessors.AddProcessor(new ImageTagProcessor(ImageBasePath), new[] { HTML.Tag.IMG }); } var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(tagProcessors); var cssResolver = workerInstance.GetDefaultCssResolver(true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(worker); parser.Parse(reader); document.Close(); output = workStream.ToArray(); } } } return(output); }
private static bool GeneratePdf(string htmlText, string fileFullName, string watermarkText, PdfFont font) { if (string.IsNullOrEmpty(htmlText)) { return(false); } htmlText = "<p>" + htmlText + "</p>"; var document = new Document(); var writer = PdfWriter.GetInstance(document, new FileStream(fileFullName, FileMode.Create)); if (!string.IsNullOrEmpty(watermarkText)) { writer.PageEvent = new PdfWatermarkPageEvent(watermarkText); } document.Open(); //pipeline var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.SetImageProvider(new ChannelImageProvider()); htmlContext.SetCssAppliers(new CssAppliersImpl(GetFontProviderBy(font))); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); //parse byte[] data = Encoding.UTF8.GetBytes(htmlText); var msInput = new MemoryStream(data); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(worker); parser.Parse(msInput); //XMLWorkerHelper.GetInstance().ParseXHtml(..) var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, document.PageSize.Height, 1f); var action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); //close document.Close(); msInput.Close(); return(true); }
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); }
public static byte[] WriteHtmlToPdf(string htmlString, string css) { byte[] bytes; //Boilerplate iTextSharp setup here //Create a stream that we can write to, in this case a MemoryStream using (var ms = new MemoryStream()) { //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF using (var doc = new Document()) { //Create a writer that's bound to our PDF abstraction and our stream using (var writer = PdfWriter.GetInstance(doc, ms)) { doc.Open(); var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory(); var htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(tagProcessorFactory); var pdfWriterPipeline = new PdfWriterPipeline(doc, writer); var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline); // get an ICssResolver and add the custom CSS var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); cssResolver.AddCss(css, "utf-8", true); var cssResolverPipeline = new CssResolverPipeline( cssResolver, htmlPipeline ); var worker = new XMLWorker(cssResolverPipeline, true); var parser = new XMLParser(worker); using (var sr = new StringReader(htmlString)) { parser.Parse(sr); //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr); } doc.Close(); } bytes = ms.ToArray(); } return(bytes); } }
/// <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); } }
protected byte[] RenderHtmlToPDF(string Html) { // http://stackoverflow.com/questions/36180131/using-itextsharp-xmlworker-to-convert-html-to-pdf-and-write-text-vertically // http://stackoverflow.com/questions/20488045/change-default-font-and-fontsize-in-pdf-using-itextsharp Document document = new Document(PageSize.A4, 50f, 30f, 40f, 90f); if (Html.Contains("class=\"landscape\"")) { document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); } MemoryStream stream = new MemoryStream(); TextReader reader = new StringReader(Html); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.AddTitle("muster ag"); XMLWorkerFontProvider fonts = new XMLWorkerFontProvider(); CssAppliers appliers = new CssAppliersImpl(fonts); HtmlPipelineContext context = new HtmlPipelineContext(appliers); context.SetAcceptUnknown(true); context.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); PdfWriterPipeline pdfpipeline = new PdfWriterPipeline(document, writer); HtmlPipeline htmlpipeline = new HtmlPipeline(context, pdfpipeline); var resolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); resolver.AddCssFile(Server.MapPath("~/Content/inv.pdf.css"), true); CssResolverPipeline csspipeline = new CssResolverPipeline(resolver, htmlpipeline); XMLWorker worker = new XMLWorker(csspipeline, true); XMLParser parser = new XMLParser(worker); document.Open(); parser.Parse(reader); worker.Close(); document.Close(); return(stream.ToArray()); }
virtual public void SetupDefaultProcessingYourself() { Document doc = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(TARGET + "columbus2.pdf", FileMode.Create)); doc.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.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(); }
private XMLWorker CreateXmlWorker(Document doc, PdfWriter writer) { var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); cssResolver.AddCss(content: css, isPersistent: true); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.SetImageProvider(imageProvider); var pdfPipeline = new PdfWriterPipeline(doc, writer); var htmlPipeline = new HtmlPipeline(htmlContext, pdfPipeline); var cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline); var worker = new XMLWorker(cssPipeline, true); return(worker); }
private void CreatePdfFromHtmlString(string HtmlTemplate, string DestinationPath) { Document doc = new Document(); var fontFile = Server.MapPath("~/fonts/ARIALUNI.ttf"); try { var FS = new System.IO.FileStream(DestinationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); var document = new Document(); var writer = PdfWriter.GetInstance(document, FS); document.Open(); var cssResolver = new StyleAttrCSSResolver(); var fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); fontProvider.Register(fontFile); var cssAppliers = new CssAppliersImpl(fontProvider); var htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); var pdf = new PdfWriterPipeline(document, writer); var html = new HtmlPipeline(htmlContext, pdf); var css = new CssResolverPipeline(cssResolver, html); var worker = new XMLWorker(css, true); var p = new XMLParser(worker); var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(HtmlTemplate)); var sr = new StreamReader(ms); p.Parse(sr); document.Close(); } catch (Exception e) { throw; } }
public byte[] GetPdfBytesArray(string html) { var tempHtml = html; var cssLinks = html.GetCssLinks().ToList(); if (cssLinks.Count > 0) { tempHtml = tempHtml.RemoveCssLink(); } tempHtml = tempHtml.FormatImageLinks(); using (var ms = new MemoryStream()) using (var document = new Document(DocPageSize, 10, 10, 5, 0)) { using (var writer = PdfWriter.GetInstance(document, ms)) { document.Open(); using (TextReader xmlString = new StringReader(tempHtml)) { //Set factories var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); //Set css var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); foreach (var item in cssLinks) { cssResolver.AddCssFile(item, true); } //Export IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var xmlParse = new XMLParser(true, worker); xmlParse.Parse(xmlString); xmlParse.Flush(); } document.Close(); } return(ms.ToArray()); } }
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")); } }
/// <summary> /// Creates a <see cref="PdfTable"/> object from specified <b>HTML</b> code. /// </summary> /// <param name="html">A reference to input html code to convert.</param> /// <param name="css">A reference to css styles to apply.</param> /// <param name="config">Table configuration reference.</param> /// <returns> /// A new <see cref="PdfPTable"/> that contains a /// </returns> public static PdfTable CreateFromHtml(string html, string css = default, PdfTableConfig config = null) { var hasCss = !string.IsNullOrEmpty(css); if (!hasCss) { css = " "; } // css StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(); ICssFile cssFile = XMLWorkerHelper.GetCSS(css.AsStream()); cssResolver.AddCss(cssFile); // html XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts))); CssAppliers cssAppliers = new CssAppliersImpl(fontProvider); HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); // pipelines ElementList elements = new ElementList(); ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null); HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdf); CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline); // XML Worker XMLWorker worker = new XMLWorker(cssPipeline, true); XMLParser parser = new XMLParser(worker, Encoding.UTF8); parser.Parse(html.AsStream(Encoding.UTF8)); PdfPTable nativeTable = (PdfPTable)elements[0]; return(new PdfTable(nativeTable, config)); }
public void Go() { using (var stream = new FileStream(OUTPUT_FILE, FileMode.Create)) { using (var document = new Document()) { PdfWriter writer = PdfWriter.GetInstance( document, stream ); document.Open(); // instantiate custom tag processor and add to `HtmlPipelineContext`. var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory(); tagProcessorFactory.AddProcessor( new TableProcessor(), new string[] { HTML.Tag.TABLE } ); var htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(tagProcessorFactory); var pdfWriterPipeline = new PdfWriterPipeline(document, writer); var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); var cssResolverPipeline = new CssResolverPipeline( cssResolver, htmlPipeline ); var worker = new XMLWorker(cssResolverPipeline, true); var parser = new XMLParser(worker); using (var stringReader = new StringReader(GetHtml())) { parser.Parse(stringReader); } } } }
private static void AddHTMLText(PdfWriter writer, Document document, string htmlString, List <string> stylesheetFilePath) { var cssResolver = new StyleAttrCSSResolver(); Stream cssStream = null; if (stylesheetFilePath != null) { foreach (var stylesheetPath in stylesheetFilePath) { cssStream = new FileStream(stylesheetPath, FileMode.Open, FileAccess.Read); var cssFile = XMLWorkerHelper.GetCSS(cssStream); cssResolver.AddCss(cssFile); } } var cssAppliersImpl = new CssAppliersImpl(); var htmlPipelineContext = new HtmlPipelineContext(cssAppliersImpl); htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlPipelineContext.SetImageProvider(new DownloadImageProvider()); var pdfWriterPipeline = new PdfWriterPipeline(document, writer); var htmlPipe = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline); var cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipe); var worker = new XMLWorker(cssResolverPipeline, true); var parser = new XMLParser(worker); var stringReader = new StringReader(htmlString); parser.Parse(stringReader); if (cssStream != null) { cssStream.Dispose(); } }