public byte[] GeneratePdfFromView(string viewString, string[] cssPaths, string fontPath) { using (var memoryStream = new MemoryStream()) { var doc = new Document(PageSize.A4); var writer = PdfWriter.GetInstance(doc, memoryStream); doc.Open(); var tagProcessors = InitializeTagProcessor(); var cssResolver = InitializeCssFiles(cssPaths); var fontProvider = new CustomFontFactory(fontPath); var hpc = new HtmlPipelineContext(new CssAppliersImpl(fontProvider)); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)); var pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); var worker = new XMLWorker(pipeline, true); var xmlParser = new XMLParser(true, worker, Encoding.Unicode); xmlParser.Parse(new StringReader(viewString)); doc.Close(); return memoryStream.ToArray(); } }
protected override void TransformHtml2Pdf() { Document doc = new Document(PageSize.A1.Rotate()); PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create)); doc.SetMargins(doc.LeftMargin - 10, doc.RightMargin - 10, doc.TopMargin, doc.BottomMargin); doc.Open(); CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add( XMLWorkerHelper.GetCSS( File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + testName + Path.DirectorySeparatorChar + "complexDiv02_files" + Path.DirectorySeparatorChar + "minimum0.css"))); cssFiles.Add( XMLWorkerHelper.GetCSS( File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + testName + Path.DirectorySeparatorChar + "complexDiv02_files" + Path.DirectorySeparatorChar + "print000.css"))); cssFiles.Add(XMLWorkerHelper.GetCSS(File.OpenRead(RESOURCES + @"\tool\xml\examples\" + "sampleTest.css"))); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext( new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts"))); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory()); hpc.SetImageProvider(new SampleTestImageProvider()); HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter)); IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8")); p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8")); doc.Close(); }
virtual public void ParseXfaOnlyXML() { StreamReader bis = File.OpenText(RESOURCE_TEST_PATH + SNIPPETS + TEST + "snippet.html"); Document doc = new Document(PageSize.A4); float margin = utils.ParseRelativeValue("10%", PageSize.A4.Width); doc.SetMargins(margin, margin, margin, margin); PdfWriter writer = null; try { writer = PdfWriter.GetInstance(doc, new FileStream( TARGET + TEST + "_charset.pdf", FileMode.Create)); } catch (DocumentException e) { Console.WriteLine(e); } CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS()); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext(null); hpc.SetAcceptUnknown(true) .AutoBookmark(true) .SetTagFactory(Tags.GetHtmlTagProcessorFactory()) .CharSet(Encoding.GetEncoding("ISO-8859-1")); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer))); XMLWorker worker = new XMLWorker(pipeline, true); doc.Open(); XMLParser p = new XMLParser(true, worker); p.Parse(bis); doc.Close(); }
protected override void MakePdf(string outPdf) { Document doc = new Document(PageSize.A4.Rotate()); PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create)); doc.SetMargins(45, 45, 0, 100); doc.Open(); CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add( XMLWorkerHelper.GetCSS( File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName + Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar + "main.css"))); cssFiles.Add( XMLWorkerHelper.GetCSS( File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName + Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar + "widget082.css"))); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext( new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts"))); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory()); hpc.SetImageProvider(new SampleTestImageProvider()); hpc.SetPageSize(doc.PageSize); HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter)); IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8")); p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8")); doc.Close(); }
public void HtmlToPdf(string htmlFile, string pdfFile, string htmlImageDirectory) { using (FileStream pdfStream = new FileStream(pdfFile, FileMode.OpenOrCreate)) { Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, pdfStream); doc.Open(); //TODO: apply external css ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); //HTML HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.SetImageProvider(new ImageProvider(htmlImageDirectory)); htmlContext.SetLinkProvider(new LinkProvider("/")); //pipelines PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer); HtmlPipeline html = new HtmlPipeline(htmlContext, pdf); CssResolverPipeline css = new CssResolverPipeline(cssResolver, html); XMLWorker worker = new XMLWorker(css, true); XMLParser p = new XMLParser(true, worker, Encoding.UTF8); using (TextReader reader = File.OpenText(htmlFile)) { p.Parse(reader); } doc.Close(); } }
virtual public void SetUp() { parent = new Tag("body"); parent.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; parent.CSS[CSS.Property.FONT_SIZE] = "12pt"; first = new Tag(null); first.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; first.CSS[CSS.Property.FONT_SIZE] = "12pt"; second = new Tag(null); second.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; second.CSS[CSS.Property.FONT_SIZE] = "12pt"; child = new Tag(null); child.CSS[CSS.Property.FONT_FAMILY] = "Helvetica"; child.CSS[CSS.Property.FONT_SIZE] = "12pt"; parent.AddChild(first); first.Parent = parent; second.Parent = parent; first.AddChild(child); second.AddChild(child); parent.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(parent) + "pt"; first.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(first) + "pt"; first.CSS[CSS.Property.TEXT_ALIGN] = CSS.Value.LEFT; second.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(second) + "pt"; child.CSS[CSS.Property.FONT_SIZE] = fst.TranslateFontSize(child) + "pt"; firstPara = new Paragraph(new Chunk("default text for chunk creation")); secondPara = new Paragraph(new Chunk("default text for chunk creation")); configuration = new HtmlPipelineContext(null); applier.Apply(firstPara, first, configuration); }
virtual public void TestContentToChunk() { Anchor a = new Anchor(); Tag t = new Tag("dummy"); String content2 = "some content"; WorkerContextImpl ctx = new WorkerContextImpl(); HtmlPipelineContext htmlPipelineContext = new HtmlPipelineContext(null); ctx.Put(typeof (HtmlPipeline).FullName, htmlPipelineContext); a.SetCssAppliers(new CssAppliersImpl()); IList<IElement> ct = a.Content(ctx, t, content2); Assert.AreEqual(content2, ct[0].Chunks[0].Content); }
public void SetUp() { LoggerFactory.GetInstance().SetLogger(new SysoLogger(3)); cssFiles = new CssFilesImpl(); String path = RESOURCES + @"\css\test.css"; path = path.Substring(0, path.LastIndexOf("test.css")); FileRetrieveImpl r = new FileRetrieveImpl(new String[] {path}); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles, r); HtmlPipelineContext hpc = new HtmlPipelineContext(null); hpc.SetAcceptUnknown(false).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory()); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, null)); XMLWorker worker = new XMLWorker(pipeline, true); p = new XMLParser(worker); }
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(); }
/* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.pipeline.IPipeline#open(com.itextpdf.tool. * xml.Tag, com.itextpdf.tool.xml.pipeline.ProcessObject) */ public override IPipeline Open(IWorkerContext context, Tag t, ProcessObject po) { HtmlPipelineContext hcc = (HtmlPipelineContext)GetLocalContext(context); try { Object lastMarginBottom = null; if (hcc.GetMemory().TryGetValue(HtmlPipelineContext.LAST_MARGIN_BOTTOM, out lastMarginBottom)) { t.LastMarginBottom = lastMarginBottom; hcc.GetMemory().Remove(HtmlPipelineContext.LAST_MARGIN_BOTTOM); } ITagProcessor tp = hcc.ResolveProcessor(t.Name, t.NameSpace); if (tp.IsStackOwner()) { hcc.AddFirst(new StackKeeper(t)); } IList <IElement> content = tp.StartElement(context, t); if (content.Count > 0) { if (tp.IsStackOwner()) { StackKeeper peek; try { peek = hcc.Peek(); foreach (IElement elem in content) { peek.Add(elem); } } catch (NoStackException e) { throw new PipelineException(String.Format(LocaleMessages.STACK_404, t.ToString()), e); } } else { foreach (IElement elem in content) { hcc.CurrentContent().Add(elem); } } } } catch (NoTagProcessorException e) { if (!hcc.AcceptUnknown()) { throw e; } } return(GetNext()); }
public void SetUp() { body = new Tag("body", new Dictionary<String, String>()); table = new Tag("table", new Dictionary<String, String>()); row = new Tag("tr", new Dictionary<String, String>()); cell = new Tag("td", new Dictionary<String, String>()); config = new HtmlPipelineContext(null); calc = new WidthCalculator(); LoggerFactory.GetInstance().SetLogger(new SysoLogger(3)); body.AddChild(table); table.Parent = body; table.AddChild(row); row.Parent = table; row.AddChild(cell); cell.Parent = row; }
/* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.pipeline.IPipeline#close(com.itextpdf.tool * .xml.Tag, com.itextpdf.tool.xml.pipeline.ProcessObject) */ public override IPipeline Close(IWorkerContext context, Tag t, ProcessObject po) { HtmlPipelineContext hcc = (HtmlPipelineContext)GetLocalContext(context); ITagProcessor tp; try { tp = hcc.ResolveProcessor(t.Name, t.NameSpace); IList <IElement> elems = null; if (tp.IsStackOwner()) { // remove the element from the StackKeeper Queue if end tag is // found StackKeeper tagStack; try { tagStack = hcc.Poll(); } catch (NoStackException e) { throw new PipelineException(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.STACK_404), t.ToString()), e); } elems = tp.EndElement(context, t, tagStack.GetElements()); } else { elems = tp.EndElement(context, t, hcc.CurrentContent()); hcc.CurrentContent().Clear(); } if (elems.Count > 0) { try { StackKeeper stack = hcc.Peek(); foreach (IElement elem in elems) { stack.Add(elem); } } catch (NoStackException) { WritableElement writableElement = new WritableElement(); po.Add(writableElement); writableElement.AddAll(elems); } } } catch (NoTagProcessorException e) { if (!hcc.AcceptUnknown()) { throw e; } } return(GetNext()); }
/** * Create a clone of this HtmlPipelineContext, the clone only contains the * initial values, not the internal values. Beware, the state of the current * Context is not copied to the clone. Only the configurational important * stuff like the LinkProvider (same object), ImageProvider (new * {@link AbstractImageProvider} with same ImageRootPath) , * TagProcessorFactory (same object), acceptUnknown (primitive), charset * (Charset.forName to get a new charset), autobookmark (primitive) are * copied. */ public object Clone() { HtmlPipelineContext newCtx = new HtmlPipelineContext(); if (this.imageProvider != null) { String rootPath = imageProvider.GetImageRootPath(); newCtx.SetImageProvider(new CloneImageProvider(rootPath)); } if (null != this.charset) { newCtx.CharSet(Encoding.GetEncoding(this.charset.CodePage)); } newCtx.SetPageSize(new Rectangle(this.pageSize)).SetLinkProvider(this.linkprovider) .SetRootTags(new List <String>(this.roottags)).AutoBookmark(this.autoBookmark) .SetTagFactory(this.tagFactory).SetAcceptUnknown(this.acceptUnknown); return(newCtx); }
virtual public void SetUp() { cells = new List<Element>(); tag = new Tag("td", new Dictionary<String, String>()); basicPara = new NoNewLineParagraph(); basic = new Chunk("content"); cell = new HtmlCell(); applier = new HtmlCellCssApplier(); LoggerFactory.GetInstance().SetLogger(new SysoLogger(3)); Tag parent = new Tag("tr"); parent.Parent = new Tag("table"); tag.Parent = parent; basicPara.Add(basic); cell.AddElement(basicPara); cells.Add(cell); config = new HtmlPipelineContext(null); }
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); }
/* * (non-Javadoc) * * @see com.itextpdf.tool.xml.pipeline.IPipeline#content(com.itextpdf.tool * .xml.Tag, java.lang.String, com.itextpdf.tool.xml.pipeline.ProcessObject) */ public override IPipeline Content(IWorkerContext context, Tag t, string text, ProcessObject po) { HtmlPipelineContext hcc = (HtmlPipelineContext)GetLocalContext(context); ITagProcessor tp; try { tp = hcc.ResolveProcessor(t.Name, t.NameSpace); //String ctn = null; //if (null != hcc.CharSet()) { // ctn = hcc.CharSet().GetString(b); //} else { // ctn = Encoding.Default.GetString(b); //} IList <IElement> elems = tp.Content(context, t, text); if (elems.Count > 0) { StackKeeper peek = hcc.Peek(); if (peek != null) { foreach (IElement e in elems) { peek.Add(e); } } else { WritableElement writableElement = new WritableElement(); foreach (IElement elem in elems) { writableElement.Add(elem); } po.Add(writableElement); } } } catch (NoTagProcessorException e) { if (!hcc.AcceptUnknown()) { throw e; } } return(GetNext()); }
/** * Create a clone of this HtmlPipelineContext, the clone only contains the * initial values, not the internal values. Beware, the state of the current * Context is not copied to the clone. Only the configurational important * stuff like the LinkProvider (same object), ImageProvider (new * {@link AbstractImageProvider} with same ImageRootPath) , * TagProcessorFactory (same object), acceptUnknown (primitive), charset * (Charset.forName to get a new charset), autobookmark (primitive) are * copied. */ virtual public object Clone() { CssAppliers cloneCssApliers = this.cssAppliers.Clone(); HtmlPipelineContext newCtx = new HtmlPipelineContext(cloneCssApliers); if (this.imageProvider != null) { newCtx.SetImageProvider(imageProvider); } if (resourcePath != null) { newCtx.ResourcePath = resourcePath; } if (null != this.charset) { newCtx.CharSet(Encoding.GetEncoding(this.charset.CodePage)); } newCtx.SetPageSize(new Rectangle(this.pageSize)).SetLinkProvider(this.linkprovider) .SetRootTags(new List <String>(this.roottags)).AutoBookmark(this.autoBookmark) .SetTagFactory(this.tagFactory).SetAcceptUnknown(this.acceptUnknown); return(newCtx); }
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); }
protected override void MakePdf(string outPdf) { Document doc = new Document(PageSize.A3.Rotate()); PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create)); pdfWriter.CreateXmpMetadata(); doc.SetMargins(200, 200, 0, 0); doc.Open(); CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add( XMLWorkerHelper.GetCSS( File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName + Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar + "main.css"))); cssFiles.Add( XMLWorkerHelper.GetCSS( File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName + Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar + "widget082.css"))); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext( new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts"))); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory()); hpc.SetImageProvider(new SampleTestImageProvider()); hpc.SetPageSize(doc.PageSize); HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter)); IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8")); p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8")); //ICC_Profile icc = ICC_Profile.getInstance(ComplexDiv01Test.class.getResourceAsStream("sRGB Color Space Profile.icm")); //pdfWriter.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); doc.Close(); }
/* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.pipeline.AbstractPipeline#close(com.itextpdf.tool * .xml.Tag, com.itextpdf.tool.xml.pipeline.ProcessObject) */ public override IPipeline Close(IWorkerContext context, Tag t, ProcessObject po) { String tagName = t.Name; if (tag.Equals(tagName)) { MapContext cc; try { cc = (MapContext)context.Get(typeof(PdfWriterPipeline).FullName); Document d = (Document)cc[PdfWriterPipeline.DOCUMENT]; d.Close(); } catch (NoCustomContextException e) { throw new PipelineException("AutoDocPipeline depends on PdfWriterPipeline.", e); } try { HtmlPipelineContext hpc = (HtmlPipelineContext)context.Get(typeof(HtmlPipeline).FullName); HtmlPipelineContext clone = (HtmlPipelineContext)hpc.Clone(); clone.SetPageSize(pagesize); ((WorkerContextImpl)context).Put(typeof(HtmlPipeline).FullName, clone); } catch (NoCustomContextException) { } } return(GetNext()); }
/** * @param d the ElementHandler * @param inp the Stream * @throws IOException if something went seriously wrong with IO. */ public void ParseXHtml(IElementHandler d, Stream inp, Encoding charset) { CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(GetDefaultCSS()); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext(null); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(GetDefaultTagProcessorFactory()); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, new ElementHandlerPipeline(d, null))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(true, worker, charset); if (charset != null) { p.Parse(inp, charset); } else { p.Parse(inp); } }
public void ParseXHtml(PdfWriter writer, Document doc, Stream inp, Stream inCssFile, Encoding charset, IFontProvider fontProvider) { CssFilesImpl cssFiles = new CssFilesImpl(); if (inCssFile != null) cssFiles.Add(GetCSS(inCssFile)); else cssFiles.Add(GetDefaultCSS()); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(fontProvider)); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(GetDefaultTagProcessorFactory()); HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)); IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(true, worker, charset); if (charset != null) { p.Parse(inp, charset); } else { p.Parse(inp); } }
/** * Parses the xml data. This method configures the XMLWorker to parse * (X)HTML/CSS and accept unknown tags. Writes the output in the given * PdfWriter with the given document. * * @param writer the PdfWriter * @param doc the Document * @param inp the reader * @throws IOException thrown when something went wrong with the IO */ public void ParseXHtml(PdfWriter writer, Document doc, TextReader inp) { CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(GetDefaultCSS()); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext(null); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(GetDefaultTagProcessorFactory()); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(); p.AddListener(worker); p.Parse(inp); }
static protected void TransformHtml2Pdf(FileStream inputHtml, Document doc, PdfWriter pdfWriter) { CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS()); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); String Css1 = "https://specialtyonlinestg.cardinalhealth.com/CardinalHealthSpecialty/themes/html/SS_SPDCardinalHealth/css/globalStyles.css?version=RI_20121023"; String Css2 = "https://specialtyonlinestg.cardinalhealth.com/CardinalHealthSpecialty/themes/html/SS_SPDCardinalHealth/css/SPDCSS/CAHPHReconciliationPortletView.css?version=AC_20120717"; try { cssResolver.AddCssFile(Css1, true); cssResolver.AddCssFile(Css2, true); } catch (CssResolverException e) { // TODO Auto-generated catch block } HtmlPipelineContext htmlContext = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider())); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.SetPageSize(new Rectangle(doc.Left, doc.Bottom, doc.Right, doc.Top)); // Pipelines PdfWriterPipeline pdf = new PdfWriterPipeline(doc, pdfWriter); HtmlPipeline html = new HtmlPipeline(htmlContext, pdf); CssResolverPipeline css = new CssResolverPipeline(cssResolver, html); XMLWorker worker = new XMLWorker(css, true); XMLParser parser = new XMLParser(worker, Encoding.UTF8); parser.Parse(inputHtml, Encoding.UTF8); }
private void iTextSharp(string html) { System.Web.HttpContext.Current.Response.ContentType = "application/pdf"; System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=BookingDetails.pdf"); System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); Document pdfDoc = new Document(new Rectangle(922, 1296), 7f, 7f, 7f, 0f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream); pdfDoc.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICssFile cfile = new CssFileImpl(); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"App_Data\PDF.all.min.css", true); //Pipeline IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer))); //XMLWorker XMLWorker worker = new XMLWorker(pipeline, true); XMLParser parser = new XMLParser(); parser.AddListener(worker); using (TextReader sr = new StringReader(html)) { parser.Parse(sr); } parser.Flush(); pdfDoc.Close(); System.Web.HttpContext.Current.Response.Write(pdfDoc); System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); }
virtual public PdfDiv Apply(PdfDiv div, Tag t, IMarginMemory memory, IPageSizeContainable psc, HtmlPipelineContext context) { if (t.Attributes.ContainsKey("id")) div.Tag = t.Attributes["id"]; IDictionary<String, String> css = t.CSS; float fontSize = FontSizeTranslator.GetInstance().TranslateFontSize(t); if (fontSize == Font.UNDEFINED) { fontSize = FontSizeTranslator.DEFAULT_FONT_SIZE; } String align = null; if (t.Attributes.ContainsKey(HTML.Attribute.ALIGN)) { align = t.Attributes[HTML.Attribute.ALIGN]; } else if (css.ContainsKey(CSS.Property.TEXT_ALIGN)) { align = css[CSS.Property.TEXT_ALIGN]; } if (align != null) { div.TextAlignment = CSS.GetElementAlignment(align); } String widthValue; if (!css.TryGetValue(HTML.Attribute.WIDTH, out widthValue)) { t.Attributes.TryGetValue(HTML.Attribute.WIDTH, out widthValue); } if (widthValue != null) { float pageWidth = psc.PageSize.Width; if (utils.IsNumericValue(widthValue) || utils.IsMetricValue(widthValue)) { div.Width = Math.Min(pageWidth, utils.ParsePxInCmMmPcToPt(widthValue)); } else if (utils.IsRelativeValue(widthValue)) { if (widthValue.Contains(CSS.Value.PERCENTAGE)) { div.PercentageWidth = utils.ParseRelativeValue(widthValue, 1f); } else { div.Width = Math.Min(pageWidth, utils.ParseRelativeValue(widthValue, fontSize)); } } } String heightValue; if (!css.TryGetValue(HTML.Attribute.HEIGHT, out heightValue)) { t.Attributes.TryGetValue(HTML.Attribute.HEIGHT, out heightValue); } if (heightValue != null) { if (utils.IsNumericValue(heightValue) || utils.IsMetricValue(heightValue)) { div.Height = utils.ParsePxInCmMmPcToPt(heightValue); } else if (utils.IsRelativeValue(heightValue)) { if (heightValue.Contains(CSS.Value.PERCENTAGE)) { div.PercentageHeight = utils.ParseRelativeValue(heightValue, 1f); } else { div.Height = utils.ParseRelativeValue(heightValue, fontSize); } } } float? marginTop = null; float? marginBottom = null; foreach (KeyValuePair<String, String> entry in css) { String key = entry.Key; String value = entry.Value; if (Util.EqualsIgnoreCase(key, CSS.Property.LEFT)) { div.Left = utils.ParseValueToPt(value, fontSize); } else if (Util.EqualsIgnoreCase(key, CSS.Property.RIGHT)) { if (div.Width == null || div.Left == null) { div.Right = utils.ParseValueToPt(value, fontSize); } } else if (Util.EqualsIgnoreCase(key, CSS.Property.TOP)) { div.Top = utils.ParseValueToPt(value, fontSize); } else if (Util.EqualsIgnoreCase(key, CSS.Property.BOTTOM)) { if (div.Height == null || div.Top == null) { div.Bottom = utils.ParseValueToPt(value, fontSize); } } else if (Util.EqualsIgnoreCase(key, CSS.Property.BACKGROUND_COLOR)) { div.BackgroundColor = HtmlUtilities.DecodeColor(value); } else if (Util.EqualsIgnoreCase(key, CSS.Property.BACKGROUND_IMAGE)) { string url = utils.ExtractUrl(value); try { Image img = new ImageRetrieve(context.ResourcePath, context.GetImageProvider()).RetrieveImage(url); div.BackgroundImage = img; } catch (NoImageException e) { if (LOG.IsLogging(Level.ERROR)) { LOG.Error(string.Format(LocaleMessages.GetInstance().GetMessage("html.tag.img.failed"), url), e); } } } else if (Util.EqualsIgnoreCase(key, CSS.Property.PADDING_LEFT)) { div.PaddingLeft = utils.ParseValueToPt(value, fontSize); } else if (Util.EqualsIgnoreCase(key, CSS.Property.PADDING_RIGHT)) { div.PaddingRight = utils.ParseValueToPt(value, fontSize); } else if (Util.EqualsIgnoreCase(key, CSS.Property.PADDING_TOP)) { div.PaddingTop = utils.ParseValueToPt(value, fontSize); } else if (Util.EqualsIgnoreCase(key, CSS.Property.PADDING_BOTTOM)) { div.PaddingBottom = utils.ParseValueToPt(value, fontSize); } else if (Util.EqualsIgnoreCase(key, CSS.Property.MARGIN_TOP)) { div.SpacingBefore = div.SpacingBefore + utils.CalculateMarginTop(value, fontSize, memory); marginTop = utils.CalculateMarginTop(value, fontSize, memory); } else if (Util.EqualsIgnoreCase(key, CSS.Property.MARGIN_BOTTOM)) { div.SpacingAfter = div.SpacingAfter + utils.CalculateMarginTop(value, fontSize, memory); marginBottom = utils.ParseValueToPt(value, fontSize); } else if (Util.EqualsIgnoreCase(key, CSS.Property.FLOAT)) { if (Util.EqualsIgnoreCase(value, CSS.Value.LEFT)) { div.Float = PdfDiv.FloatType.LEFT; } else if (Util.EqualsIgnoreCase(value, CSS.Value.RIGHT)) { div.Float = PdfDiv.FloatType.RIGHT; } } else if (Util.EqualsIgnoreCase(key, CSS.Property.POSITION)) { if (Util.EqualsIgnoreCase(value, CSS.Value.ABSOLUTE)) { div.Position = PdfDiv.PositionType.ABSOLUTE; } else if (Util.EqualsIgnoreCase(value, CSS.Value.FIXED)) { div.Position = PdfDiv.PositionType.FIXED; } else if (Util.EqualsIgnoreCase(value, CSS.Value.RELATIVE)) { div.Position = PdfDiv.PositionType.RELATIVE; } } else if (Util.EqualsIgnoreCase(key, CSS.Property.DISPLAY)) { if (Util.EqualsIgnoreCase(value, CSS.Value.BLOCK)) { div.Display = PdfDiv.DisplayType.BLOCK; } else if (Util.EqualsIgnoreCase(value, CSS.Value.INLINE)) { div.Display = PdfDiv.DisplayType.INLINE; } else if (Util.EqualsIgnoreCase(value, CSS.Value.INLINE_BLOCK)) { div.Display = PdfDiv.DisplayType.INLINE_BLOCK; } else if (Util.EqualsIgnoreCase(value, CSS.Value.INLINE_TABLE)) { div.Display = PdfDiv.DisplayType.INLINE_TABLE; } else if (Util.EqualsIgnoreCase(value, CSS.Value.LIST_ITEM)) { div.Display = PdfDiv.DisplayType.LIST_ITEM; } else if (Util.EqualsIgnoreCase(value, CSS.Value.NONE)) { div.Display = PdfDiv.DisplayType.NONE; } else if (Util.EqualsIgnoreCase(value, CSS.Value.RUN_IN)) { div.Display = PdfDiv.DisplayType.RUN_IN; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE)) { div.Display = PdfDiv.DisplayType.TABLE; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_CAPTION)) { div.Display = PdfDiv.DisplayType.TABLE_CAPTION; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_CELL)) { div.Display = PdfDiv.DisplayType.TABLE_CELL; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_COLUMN_GROUP)) { div.Display = PdfDiv.DisplayType.TABLE_COLUMN_GROUP; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_COLUMN)) { div.Display = PdfDiv.DisplayType.TABLE_COLUMN; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_FOOTER_GROUP)) { div.Display = PdfDiv.DisplayType.TABLE_FOOTER_GROUP; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_HEADER_GROUP)) { div.Display = PdfDiv.DisplayType.TABLE_HEADER_GROUP; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_ROW)) { div.Display = PdfDiv.DisplayType.TABLE_ROW; } else if (Util.EqualsIgnoreCase(value, CSS.Value.TABLE_ROW_GROUP)) { div.Display = PdfDiv.DisplayType.TABLE_ROW_GROUP; } } else if (Util.EqualsIgnoreCase(CSS.Property.BORDER_TOP_STYLE, key) || Util.EqualsIgnoreCase(CSS.Property.BORDER_TOP, key)) { if (value.Contains(CSS.Value.DOTTED)) { div.BorderStyleTop = PdfDiv.BorderStyle.DOTTED; } else if (value.Contains(CSS.Value.DASHED)) { div.BorderStyleTop = PdfDiv.BorderStyle.DASHED; } else if (value.Contains(CSS.Value.SOLID)) { div.BorderStyleTop = PdfDiv.BorderStyle.SOLID; } else if (value.Contains(CSS.Value.DOUBLE)) { div.BorderStyleTop = PdfDiv.BorderStyle.DOUBLE; } else if (value.Contains(CSS.Value.GROOVE)) { div.BorderStyleTop = PdfDiv.BorderStyle.GROOVE; } else if (value.Contains(CSS.Value.RIDGE)) { div.BorderStyleTop = PdfDiv.BorderStyle.RIDGE; } else if (value.Contains(CSS.Value.INSET)) { div.BorderStyleTop = PdfDiv.BorderStyle.INSET; } else if (value.Contains(CSS.Value.OUTSET)) { div.BorderStyleTop = PdfDiv.BorderStyle.OUTSET; } } else if (Util.EqualsIgnoreCase(CSS.Property.BORDER_BOTTOM_STYLE, key) || Util.EqualsIgnoreCase(CSS.Property.BORDER_BOTTOM, key)) { if (value.Contains(CSS.Value.DOTTED)) { div.BorderStyleBottom = PdfDiv.BorderStyle.DOTTED; } else if (value.Contains(CSS.Value.DASHED)) { div.BorderStyleBottom = PdfDiv.BorderStyle.DASHED; } else if (value.Contains(CSS.Value.SOLID)) { div.BorderStyleBottom = PdfDiv.BorderStyle.SOLID; } else if (value.Contains(CSS.Value.DOUBLE)) { div.BorderStyleBottom = PdfDiv.BorderStyle.DOUBLE; } else if (value.Contains(CSS.Value.GROOVE)) { div.BorderStyleBottom = PdfDiv.BorderStyle.GROOVE; } else if (value.Contains(CSS.Value.RIDGE)) { div.BorderStyleBottom = PdfDiv.BorderStyle.RIDGE; } else if (value.Contains(CSS.Value.INSET)) { div.BorderStyleBottom = PdfDiv.BorderStyle.INSET; } else if (value.Contains(CSS.Value.OUTSET)) { div.BorderStyleBottom = PdfDiv.BorderStyle.OUTSET; } } else if (Util.EqualsIgnoreCase(key, CSS.Property.PAGE_BREAK_INSIDE)) { if (Util.EqualsIgnoreCase(value, CSS.Value.AVOID)) { div.KeepTogether = true; } } //TODO: border, background properties. } return div; }
virtual public void SetUp() { ctx = new HtmlPipelineContext(null); }
/** * @param hpc the initial {@link HtmlPipelineContext} * @param next the next pipe in row */ public HtmlPipeline(HtmlPipelineContext hpc, IPipeline next) : base(next) { this.hpc = hpc; }
/// <summary> /// ExecuteResult /// </summary> /// <param name="context"></param> public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.Clear(); context.HttpContext.Response.ContentType = "application/pdf"; if (Download) context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName); Html = RenderRazorViewToString(context); Format(context.HttpContext); using (var document = new Document(Settings.PageSize, Settings.Margin.Left, Settings.Margin.Right, Settings.Margin.Top, Settings.Margin.Bottom)) { var memoryStream = new MemoryStream(); TextReader textReader = new StringReader(Html); var pdfWriter = PdfWriter.GetInstance(document, memoryStream); var htmlPipelineContext = new HtmlPipelineContext(null); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); document.Open(); FontFactory.RegisterDirectories(); htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); foreach (var styleSheet in StyleSheets) { cssResolver.AddCssFile(context.HttpContext.Server.MapPath(styleSheet), true); } var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, pdfWriter))); var worker = new XMLWorker(pipeline, true); var xmlParse = new XMLParser(true, worker); xmlParse.Parse(textReader); xmlParse.Flush(); document.Close(); document.Dispose(); context.HttpContext.Response.BinaryWrite(memoryStream.ToArray()); } context.HttpContext.Response.End(); context.HttpContext.Response.Flush(); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Invalid number of arguments."); Console.WriteLine("Usage: html2Pdf.exe [input html_file/directory] [default css file]"); return; } List<FileStream> fileList = new List<FileStream>(); if (File.Exists(args[0])) { fileList.Add(new FileStream(args[0], FileMode.Open)); } else if (Directory.Exists(args[0])) { CollectHtmlFiles(fileList, args[0]); } if (fileList.Count == 0) { Console.WriteLine("Invalid html_file/directory"); Console.WriteLine("Usage: html2Pdf.exe [input html_file/directory] [default css file]"); return; } foreach (FileStream fileStream in fileList) { Document doc = new Document(PageSize.LETTER); doc.SetMargins(doc.LeftMargin, doc.RightMargin, 35, 0); String path = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(fileStream.Name) + ".pdf"; PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create)); doc.Open(); Dictionary<String, String> substFonts = new Dictionary<String, String>(); substFonts["Arial Unicode MS"] = "Helvetica"; CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetCSS(new FileStream(args[1], FileMode.Open))); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(new UnembedFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS, substFonts))); hpc.SetImageProvider(new ImageProvider(args[0])); 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, null); xmlParse.Parse(fileStream); doc.Close(); String cmpPath = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "cmp_" + Path.GetFileNameWithoutExtension(fileStream.Name) + ".pdf"; if (File.Exists(cmpPath)) { CompareTool ct = new CompareTool(path, cmpPath); String outImage = "<testName>-%03d.png".Replace("<testName>", Path.GetFileNameWithoutExtension(fileStream.Name) ); String cmpImage = "cmp_<testName>-%03d.png".Replace("<testName>", Path.GetFileNameWithoutExtension(fileStream.Name) ); String diffPath = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "diff_" + Path.GetFileNameWithoutExtension(fileStream.Name); String errorMessage = ct.Compare(Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "compare" + Path.DirectorySeparatorChar, diffPath); if (errorMessage != null) { Console.WriteLine(errorMessage); } } } }
protected void btnGeneratePdf_Click1(object sender, EventArgs e) { var sb = new StringBuilder(); sb.Append("<table>"); sb.Append("<tr>"); sb.Append("<th class=\"th\">Title</th>"); sb.Append("<th>Author</th>"); sb.Append("</tr>"); MongoDbProvider.db.LoadData<Word>().ToList().ForEach(b => { sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", b.WordName); sb.AppendFormat("<td>{0}</td>", b.Translation); sb.Append("</tr>"); }); sb.Append("</table>"); using (var document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("loremipsum5.pdf"), FileMode.Append)); document.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); //change this to your CCS file location cssResolver.AddCssFile(Server.MapPath("style.css"), 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(new StringReader(sb.ToString())); } }
virtual public void SetUp() { ctx = new HtmlPipelineContext(null); ctx.SetImageProvider(new CustomAbstractImageProvider()); clone = (HtmlPipelineContext) ctx.Clone(); }
/** * 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; }
/** * The ListCssApplier has the capabilities to change the type of the given {@link List} dependable on the css. * This means: <strong>Always replace your list with the returned one and add content to the list after applying!</strong> */ // not implemented: list-style-type:armenian, georgian, decimal-leading-zero. virtual public List Apply(List list, Tag t, HtmlPipelineContext context) { float fontSize = FontSizeTranslator.GetInstance().GetFontSize(t); List lst = list; IDictionary<String, String> css = t.CSS; String styleType; css.TryGetValue(CSS.Property.LIST_STYLE_TYPE, out styleType); BaseColor color = HtmlUtilities.DecodeColor(css.ContainsKey(CSS.Property.COLOR) ? css[CSS.Property.COLOR] : null); if (null == color) color = BaseColor.BLACK; if (null != styleType) { if (Util.EqualsIgnoreCase(styleType, CSS.Value.NONE)) { lst.Lettered = false; lst.Numbered = false; lst.SetListSymbol(""); } else if (Util.EqualsIgnoreCase(CSS.Value.DECIMAL, styleType)) { lst = new List(List.ORDERED); } else if (Util.EqualsIgnoreCase(CSS.Value.DISC, styleType)) { lst = new ZapfDingbatsList(108); lst.Autoindent = false; lst.SymbolIndent = 7.75f; Chunk symbol = lst.Symbol; symbol.SetTextRise(1.5f); Font font = symbol.Font; font.Size = 4.5f; font.Color = color; } else if (Util.EqualsIgnoreCase(CSS.Value.SQUARE, styleType)) { lst = new ZapfDingbatsList(110); ShrinkSymbol(lst, fontSize, color); } else if (Util.EqualsIgnoreCase(CSS.Value.CIRCLE, styleType)) { lst = new ZapfDingbatsList(109); lst.Autoindent = false; lst.SymbolIndent = 7.75f; Chunk symbol = lst.Symbol; symbol.SetTextRise(1.5f); Font font = symbol.Font; font.Size = 4.5f; font.Color = color; } else if (CSS.Value.LOWER_ROMAN.Equals(styleType)) { lst = new RomanList(true, 0); lst.Autoindent = true; SynchronizeSymbol(fontSize, lst, color); } else if (CSS.Value.UPPER_ROMAN.Equals(styleType)) { lst = new RomanList(false, 0); SynchronizeSymbol(fontSize, lst, color); lst.Autoindent = true; } else if (CSS.Value.LOWER_GREEK.Equals(styleType)) { lst = new GreekList(true, 0); SynchronizeSymbol(fontSize, lst, color); lst.Autoindent = true; } else if (CSS.Value.UPPER_GREEK.Equals(styleType)) { lst = new GreekList(false, 0); SynchronizeSymbol(fontSize, lst, color); lst.Autoindent = true; } else if (CSS.Value.LOWER_ALPHA.Equals(styleType) || CSS.Value.LOWER_LATIN.Equals(styleType)) { lst = new List(List.ORDERED, List.ALPHABETICAL); SynchronizeSymbol(fontSize, lst, color); lst.Lowercase = true; lst.Autoindent = true; } else if (CSS.Value.UPPER_ALPHA.Equals(styleType) || CSS.Value.UPPER_LATIN.Equals(styleType)) { lst = new List(List.ORDERED, List.ALPHABETICAL); SynchronizeSymbol(fontSize, lst, color); lst.Lowercase = false; lst.Autoindent = true; } } else if (Util.EqualsIgnoreCase(t.Name, HTML.Tag.OL)) { lst = new List(List.ORDERED); String type = null; t.Attributes.TryGetValue("type", out type); if (type != null) { if (type.Equals("A")) { lst.Lettered = true; } else if (type.Equals("a")) { lst.Lettered = true; lst.Lowercase = true; } } SynchronizeSymbol(fontSize, lst, color); lst.Autoindent = true; } else if (Util.EqualsIgnoreCase(t.Name, HTML.Tag.UL)) { lst = new List(List.UNORDERED); ShrinkSymbol(lst, fontSize, color); } if (css.ContainsKey(CSS.Property.LIST_STYLE_IMAGE) && !Util.EqualsIgnoreCase(css[CSS.Property.LIST_STYLE_IMAGE], CSS.Value.NONE)) { lst = new List(); String url = utils.ExtractUrl(css[CSS.Property.LIST_STYLE_IMAGE]); try { Image img = new ImageRetrieve(context.ResourcePath, context.GetImageProvider()).RetrieveImage(url); lst.ListSymbol = new Chunk(img, 0, 0, false); lst.SymbolIndent = img.Width; if (LOG.IsLogging(Level.TRACE)) { LOG.Trace(String.Format(LocaleMessages.GetInstance().GetMessage("html.tag.list"), url)); } } catch (NoImageException e) { if (LOG.IsLogging(Level.ERROR)) { LOG.Error(String.Format(LocaleMessages.GetInstance().GetMessage("html.tag.img.failed"), url), e); } lst = new List(List.UNORDERED); } lst.Autoindent = false; } lst.Alignindent = false; float leftIndent = 0; if (css.ContainsKey(CSS.Property.LIST_STYLE_POSITION) && Util.EqualsIgnoreCase(css[CSS.Property.LIST_STYLE_POSITION], CSS.Value.INSIDE)) { leftIndent += 30; } else { leftIndent += 15; } leftIndent += css.ContainsKey(CSS.Property.MARGIN_LEFT)?utils.ParseValueToPt(css[CSS.Property.MARGIN_LEFT],fontSize):0; leftIndent += css.ContainsKey(CSS.Property.PADDING_LEFT)?utils.ParseValueToPt(css[CSS.Property.PADDING_LEFT],fontSize):0; lst.IndentationLeft = leftIndent; String startAtr = null; t.Attributes.TryGetValue(HTML.Attribute.START, out startAtr); if (startAtr != null) { try { int start = int.Parse(startAtr); lst.First = start; } catch (FormatException exc) { } } return lst; }
public WriteH(HtmlPipelineContext context, Tag tag, Header header, Paragraph title) { this.context = context; this.tag = tag; this.header = header; this.title = title; base.directElementType = DIRECT_ELEMENT_TYPE_HEADER; }
virtual public void SetUp() { hpc = new HtmlPipelineContext(null); p = new HtmlPipeline(hpc, null); wc = new WorkerContextImpl(); p.Init(wc); }
/** * Create a clone of this HtmlPipelineContext, the clone only contains the * initial values, not the internal values. Beware, the state of the current * Context is not copied to the clone. Only the configurational important * stuff like the LinkProvider (same object), ImageProvider (new * {@link AbstractImageProvider} with same ImageRootPath) , * TagProcessorFactory (same object), acceptUnknown (primitive), charset * (Charset.forName to get a new charset), autobookmark (primitive) are * copied. */ virtual public object Clone() { CssAppliers cloneCssApliers = this.cssAppliers.Clone(); HtmlPipelineContext newCtx = new HtmlPipelineContext(cloneCssApliers); if (this.imageProvider != null) { newCtx.SetImageProvider(imageProvider); } if (null != this.charset) { newCtx.CharSet(Encoding.GetEncoding(this.charset.CodePage)); } newCtx.SetPageSize(new Rectangle(this.pageSize)).SetLinkProvider(this.linkprovider) .SetRootTags(new List<String>(this.roottags)).AutoBookmark(this.autoBookmark) .SetTagFactory(this.tagFactory).SetAcceptUnknown(this.acceptUnknown); return newCtx; }