/** * 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); }
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); } }
public void VerifyBreakChunk() { Break br = new Break(); WorkerContextImpl workerContextImpl = new WorkerContextImpl(); CssAppliersImpl cssAppliers = new CssAppliersImpl(); workerContextImpl.Put(typeof(HtmlPipeline).FullName, new HtmlPipelineContext(cssAppliers)); br.SetCssAppliers(cssAppliers); IList <IElement> end = br.End(workerContextImpl, new Tag("span"), null); Assert.AreEqual(Chunk.NEWLINE.Content, end[0].Chunks[0].Content); }
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()); }
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; } }
virtual public void SetUp() { LoggerFactory.GetInstance().SetLogger(new SysoLogger(3)); root = new Tag("body"); p = new Tag("p"); ul = new Tag("ul"); first = new Tag("li"); last = new Tag("li"); single = new ListItem("Single"); start = new ListItem("Start"); end = new ListItem("End"); listWithOne = new List <IElement>(); listWithTwo = new List <IElement>(); orderedUnorderedList = new OrderedUnorderedList(); CssAppliersImpl cssAppliers = new CssAppliersImpl(); orderedUnorderedList.SetCssAppliers(cssAppliers); workerContextImpl = new WorkerContextImpl(); HtmlPipelineContext context2 = new HtmlPipelineContext(cssAppliers); workerContextImpl.Put(typeof(HtmlPipeline).FullName, context2); root.AddChild(p); root.AddChild(ul); ul.AddChild(first); ul.AddChild(last); p.CSS["font-size"] = "12pt"; p.CSS["margin-top"] = "12pt"; p.CSS["margin-bottom"] = "12pt"; new ParagraphCssApplier(cssAppliers).Apply(new Paragraph("paragraph"), p, context2); first.CSS["margin-top"] = "50pt"; first.CSS["padding-top"] = "25pt"; first.CSS["margin-bottom"] = "50pt"; first.CSS["padding-bottom"] = "25pt"; last.CSS["margin-bottom"] = "50pt"; last.CSS["padding-bottom"] = "25pt"; listWithOne.Add(single); listWithTwo.Add(start); listWithTwo.Add(end); }
/// <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)); }
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(); } }
public async Task <Guid> SubmitWorkItem(HTMLtoPDFJob job) { iTextSharp.text.Rectangle pageSize = PageSize.A4; if (job == null) { throw new Exception("html to pdf job is null"); } switch (job.paperSize) { case PaperSize.a1: pageSize = PageSize.A1; break; case PaperSize.a2: pageSize = PageSize.A2; break; case PaperSize.a3: pageSize = PageSize.A3; break; case PaperSize.a4: pageSize = PageSize.A4; break; case PaperSize.a5: pageSize = PageSize.A5; break; case PaperSize.a6: pageSize = PageSize.A6; break; case PaperSize.a7: pageSize = PageSize.A7; break; case PaperSize.a8: pageSize = PageSize.A8; break; case PaperSize.a9: pageSize = PageSize.A9; break; case PaperSize.letter: pageSize = PageSize.LETTER; break; default: pageSize = PageSize.A4; break; } try { _context.Jobs.Add(job); _context.SaveChanges(); } catch (DbEntityValidationException ex) { string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage)); throw new DbEntityValidationException(errorMessages); } var task = Task.Factory.StartNew(t => { HTMLtoPDFJob ebJob = (HTMLtoPDFJob)t; string htmlStream = ""; string outputFileName = Guid.NewGuid().ToString("N") + ".pdf"; string tempfile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { File.WriteAllBytes(tempfile + ".html", job.FileContent); htmlStream = new StreamReader(tempfile + ".html").ReadToEnd(); if (!string.IsNullOrEmpty(htmlStream)) { var fsOut = new MemoryStream(); var stringReader = new StringReader(htmlStream); Document document = new Document(pageSize, 5, 5, 5, 5); //Document setup var pdfWriter = PdfAWriter.GetInstance(document, fsOut); pdfWriter.SetTagged(); pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); pdfWriter.CreateXmpMetadata(); pdfWriter.AddViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE); pdfWriter.Info.Put(new PdfName("Producer"), new PdfString("©" + DateTime.Now.Year.ToString() + " Robobraille.org")); //PDF/A-1A Conformance //pdfWriter = PdfAWriter.GetInstance(document, fsOut, PdfAConformanceLevel.PDF_A_1A); document.Open(); document.AddCreationDate(); //Custom tag processor var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory(); tagProcessors.AddProcessor(HTML.Tag.HTML, new HTMLTagProcessor(document)); tagProcessors.AddProcessor(HTML.Tag.TITLE, new HTMLTagProcessor(document)); tagProcessors.AddProcessor(HTML.Tag.TABLE, new TableTagProcessor()); tagProcessors.AddProcessor(HTML.Tag.TH, new THTagProcessor()); string colorProfilePath = null; string defaultCSSPath = null; try { colorProfilePath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/colors/sRGB.profile"); defaultCSSPath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/css/default.css"); } catch (Exception e) { colorProfilePath = Path.Combine(ConfigurationManager.AppSettings.Get("ProjectDirectory"), "App_Data/colors/sRGB.profile"); defaultCSSPath = Path.Combine(ConfigurationManager.AppSettings.Get("ProjectDirectory"), "App_Data/css/default.css"); } //Setup color profile var cssResolver = new StyleAttrCSSResolver(); if (colorProfilePath != null && defaultCSSPath != null) { ICC_Profile icc = ICC_Profile.GetInstance(new FileStream(colorProfilePath, FileMode.Open, FileAccess.Read)); pdfWriter.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); var xmlWorkerHelper = XMLWorkerHelper.GetInstance(); cssResolver.AddCssFile(defaultCSSPath, true);// CSS with default style for all converted docs } //Register system fonts var xmlWorkerFontProvider = new XMLWorkerFontProvider(); Environment.SpecialFolder specialFolder = Environment.SpecialFolder.Fonts; string path = Environment.GetFolderPath(specialFolder); DirectoryInfo directoryInfo = new DirectoryInfo(path); FileInfo[] fontFiles = directoryInfo.GetFiles(); foreach (var fontFile in fontFiles) { if (fontFile.Extension == ".ttf") { xmlWorkerFontProvider.Register(fontFile.FullName); } } //HTML & CSS parsing var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider); var htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); 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); document.Close(); //Data as byte array byte[] fileData = fsOut.ToArray(); try { string mime = "application/pdf"; string fileExtension = ".pdf"; ebJob.DownloadCounter = 0; ebJob.ResultFileExtension = fileExtension; ebJob.ResultMimeType = mime; ebJob.ResultContent = fileData; ebJob.Status = JobStatus.Done; ebJob.FinishTime = DateTime.Now; _context.Jobs.Attach(ebJob); _context.Entry(job).State = EntityState.Modified; _context.SaveChanges(); } catch (Exception ex) { RoboBrailleProcessor.SetJobFaulted(job, _context); throw ex; } } else { RoboBrailleProcessor.SetJobFaulted(job, _context); //Error No HTML file to convert throw new Exception("Error No HTML file to convert"); } } catch (Exception e) { RoboBrailleProcessor.SetJobFaulted(job, _context); //ignore throw e; } }, job); return(job.Id); }