Esempio n. 1
0
        /**
         * ProcessFromHref first tries to create an {@link URL} from the given <code>href</code>,
         * if that throws a {@link MalformedURLException}, it will prepend the given
         * root URLs to <code>href</code> until a valid URL is found.<br />If by then there is
         * no valid url found, this method will see if the given <code>href</code> is a valid file
         * and can read it.<br />If it's not a valid file or a file that can't be read,
         * the given root directories will be set as root path with the given <code>href</code> as
         * file path until a valid file has been found.
         */
        public void ProcessFromHref(String href, IReadingProcessor processor)
        {
            if (LOGGER.IsLogging(Level.DEBUG))
            {
                LOGGER.Debug(String.Format(LocaleMessages.GetInstance().GetMessage("retrieve.file.from"), href));
            }
            Uri    url    = null;
            bool   isfile = false;
            string f      = href;

            try {
                url = new Uri(href);
            } catch (UriFormatException) {
                try {
                    url = DetectWithRootUrls(href);
                } catch (UriFormatException) {
                    // its probably a file, try to detect it.
                    isfile = true;
                    if (!(File.Exists(href)))
                    {
                        isfile = false;
                        foreach (string root in rootdirs)
                        {
                            f = Path.Combine(root, href);
                            if (File.Exists(f))
                            {
                                isfile = true;
                                break;
                            }
                        }
                    }
                }
            }
            Stream inp = null;

            if (null != url)
            {
                WebRequest w = WebRequest.Create(url);
                try {
                    inp = w.GetResponse().GetResponseStream();
                } catch (WebException) {
                    throw new IOException(LocaleMessages.GetInstance().GetMessage("retrieve.file.from.nothing"));
                }
            }
            else if (isfile)
            {
                inp = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            else
            {
                throw new IOException(LocaleMessages.GetInstance().GetMessage("retrieve.file.from.nothing"));
            }
            Read(processor, inp);
        }
Esempio n. 2
0
 /* (non-Javadoc)
  * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
  */
 public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
 {
     try {
         IList <IElement>    list = new List <IElement>();
         HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx);
         LineSeparator       lineSeparator       = (LineSeparator)GetCssAppliers().Apply(new LineSeparator(), tag, htmlPipelineContext);
         list.Add(lineSeparator);
         return(list);
     } catch (NoCustomContextException e) {
         throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
     }
 }
Esempio n. 3
0
 public override IPipeline Init(IWorkerContext context)
 {
     try {
         SvgPipelineContext clone = (SvgPipelineContext)hpc.Clone();
         context.Put(GetContextKey(), clone);
     } catch (Exception e) {
         String message = String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.UNSUPPORTED_CLONING),
                                        hpc.GetType().FullName);
         throw new PipelineException(message, e);
     }
     return(GetNext());
 }
Esempio n. 4
0
        /**
         * Method used for retrieving a sibling of the given tag t.
         *
         * @param t tag to find the previous sibling of
         * @param i int index relative to the one of the given tag. (-i for previous siblings)
         * @return the previous sibling
         * @throws NoSiblingException when no previous sibling can be found, because the tag is the first child.
         */
        virtual public Tag GetSibling(Tag t, int i)
        {
            Tag sibling = null;

            try {
                IList <Tag> siblings = t.Parent.Children;
                sibling = siblings[siblings.IndexOf(t) + i];
            } catch (ArgumentOutOfRangeException e) {
                throw new NoSiblingException(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_SIBLING), t.Name, i), e);
            }
            return(sibling);
        }
Esempio n. 5
0
        /* (non-Javadoc)
         * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
         */
        public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
        {
            IList <IElement> l = new List <IElement>(1);

            try {
                HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx);
                Chunk newLine = (Chunk)GetCssAppliers().Apply(new Chunk(Chunk.NEWLINE), tag, htmlPipelineContext);
                l.Add(newLine);
            } catch (NoCustomContextException exc) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), exc);
            }
            return(l);
        }
 public virtual ICustomContext GetLocalContext(IWorkerContext context)
 {
     try {
         ICustomContext cc = context.Get(GetContextKey());
         if (null != cc)
         {
             return(cc);
         }
         throw new PipelineException(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.OWN_CONTEXT_404), this.GetType().FullName));
     } catch (NoCustomContextException e) {
         throw new PipelineException(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.OWN_CONTEXT_404), this.GetType().FullName), e);
     }
 }
Esempio n. 7
0
        /*
         * (non-Javadoc)
         *
         * @see
         * com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag,
         * java.util.List, com.itextpdf.text.Document)
         */
        public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
        {
            IDictionary <String, String> attributes = tag.Attributes;
            String src;

            attributes.TryGetValue(HTML.Attribute.SRC, out src);
            iTextSharp.text.Image img = null;
            IList <IElement>      l   = new List <IElement>(1);

            if (!string.IsNullOrEmpty(src))
            {
                src = XMLUtil.UnescapeXML(src);
                src = src.Trim();
                // check if the image was already added once
                try {
                    if (logger.IsLogging(Level.TRACE))
                    {
                        logger.Trace(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.HTML_IMG_USE), src));
                    }
                    try {
                        img = new ImageRetrieve(GetHtmlPipelineContext(ctx).GetImageProvider()).RetrieveImage(src);
                    } catch (NoImageProviderException) {
                        img = new ImageRetrieve().RetrieveImage(src);
                    }
                } catch (IOException e) {
                    if (logger.IsLogging(Level.ERROR))
                    {
                        logger.Error(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.HTML_IMG_RETRIEVE_FAIL), src), e);
                    }
                } catch (NoImageException e) {
                    if (logger.IsLogging(Level.ERROR))
                    {
                        logger.Error("", e);
                    }
                } catch (NoCustomContextException e) {
                    throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
                }
                if (null != img)
                {
                    try {
                        HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx);
                        l.Add(GetCssAppliers().Apply(new Chunk((iTextSharp.text.Image)GetCssAppliers().Apply(img, tag, htmlPipelineContext), 0, 0, true), tag, htmlPipelineContext));
                    } catch (NoCustomContextException e) {
                        throw new RuntimeWorkerException(e);
                    }
                }
            }
            return(l);
        }
Esempio n. 8
0
        /*
         * (non-Javadoc)
         *
         * @see com.itextpdf.tool.xml.ITagProcessor#content(com.itextpdf.tool.xml.Tag, java.util.List,
         * com.itextpdf.text.Document, java.lang.String)
         */
        public override IList <IElement> Content(IWorkerContext ctx, Tag tag, String content)
        {
            String           sanitized = HTMLUtils.Sanitize(content);
            IList <IElement> l         = new List <IElement>(1);

            if (sanitized.Length > 0)
            {
                try {
                    l.Add(GetCssAppliers().Apply(new NoNewLineParagraph(sanitized), tag, GetHtmlPipelineContext(ctx)));
                } catch (NoCustomContextException e) {
                    throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
                }
            }
            return(l);
        }
Esempio n. 9
0
        /*
         * (non-Javadoc)
         *
         * @see
         * com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag,
         * java.util.List, com.itextpdf.text.Document)
         */
        public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
        {
            HtmlCell         cell = new HtmlCell();
            IList <IElement> l    = new List <IElement>(1);

            foreach (IElement e in currentContent)
            {
                cell.AddElement(e);
            }
            try {
                l.Add(new HtmlCellCssApplier(GetHtmlPipelineContext(ctx)).Apply(cell, tag));
            } catch (NoCustomContextException e1) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e1);
            }
            return(l);
        }
Esempio n. 10
0
 /*
  * (non-Javadoc)
  *
  * @see
  * com.itextpdf.tool.xml.ITagProcessor#content(com.itextpdf.tool.xml.Tag,
  * java.lang.String)
  */
 public override IList <IElement> Content(IWorkerContext ctx, Tag tag, String content)
 {
     try {
         ICSSResolver cssResolver = GetCSSResolver(ctx);
         cssResolver.AddCss(content, false);
     } catch (CssResolverException e) {
         LOG.Error(LocaleMessages.GetInstance().GetMessage(LocaleMessages.STYLE_NOTPARSED), e);
         if (LOG.IsLogging(Level.TRACE))
         {
             LOG.Trace(content);
         }
     } catch (NoCustomContextException) {
         LOG.Warn(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.CUSTOMCONTEXT_404_CONTINUE), typeof(CssResolverPipeline).FullName));
     }
     return(new List <IElement>(0));
 }
Esempio n. 11
0
        /*
         * (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());
        }
        /**
         * Adds currentContent list to a paragraph element. If addNewLines is true a
         * Paragraph object is returned, else a NoNewLineParagraph object is
         * returned.
         *
         * @param currentContent IList<IElement> of the current elements to be added.
         * @param addNewLines bool to declare which paragraph element should be
         *            returned, true if new line should be added or not.
         * @param applyCSS true if CSS should be applied on the paragraph
         * @param tag the relevant tag
         * @return a List with paragraphs
         */

        public virtual IList <IElement> CurrentContentToParagraph(IList <IElement> currentContent,
                                                                  bool addNewLines, bool applyCSS, Tag tag,
                                                                  IWorkerContext ctx)
        {
            try
            {
                IList <IElement> list = new List <IElement>();
                if (currentContent.Count > 0)
                {
                    if (addNewLines)
                    {
                        Paragraph p = new Paragraph(float.NaN);
                        p.MultipliedLeading = 1.2f;
                        foreach (IElement e in currentContent)
                        {
                            if (e is LineSeparator)
                            {
                                p.Add(Chunk.NEWLINE);
                            }
                            p.Add(e);
                        }
                        if (applyCSS)
                        {
                            p = (Paragraph)GetCssAppliers().Apply(p, tag, GetHtmlPipelineContext(ctx));
                        }
                        list.Add(p);
                    }
                    else
                    {
                        NoNewLineParagraph p = new NoNewLineParagraph(float.NaN);
                        p.MultipliedLeading = 1.2f;
                        foreach (IElement e in currentContent)
                        {
                            p.Add(e);
                        }
                        p = (NoNewLineParagraph)GetCssAppliers().Apply(p, tag, GetHtmlPipelineContext(ctx));
                        list.Add(p);
                    }
                }
                return(list);
            }
            catch (NoCustomContextException e)
            {
                throw new RuntimeWorkerException(
                          LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
            }
        }
Esempio n. 13
0
        /* (non-Javadoc)
         * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
         */
        public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
        {
            List <IElement> l = new List <IElement>(1);

            if (currentContent.Count > 0)
            {
                IList <IElement> currentContentToParagraph = CurrentContentToParagraph(currentContent, true, true, tag, ctx);
                foreach (IElement p in currentContentToParagraph)
                {
                    ((Paragraph)p).Role = (getHeaderRole(GetLevel(tag)));
                }
                ParentTreeUtil pt = new ParentTreeUtil();
                try {
                    HtmlPipelineContext context = GetHtmlPipelineContext(ctx);

                    bool oldBookmark = context.AutoBookmark();
                    if (pt.GetParentTree(tag).Contains(HTML.Tag.TD))
                    {
                        context.AutoBookmark(false);
                    }

                    if (context.AutoBookmark())
                    {
                        Paragraph title = new Paragraph();
                        foreach (IElement w in currentContentToParagraph)
                        {
                            title.Add(w);
                        }

                        l.Add(new WriteH(context, tag, this, title));
                    }

                    context.AutoBookmark(oldBookmark);
                } catch (NoCustomContextException e) {
                    if (LOGGER.IsLogging(Level.ERROR))
                    {
                        LOGGER.Error(LocaleMessages.GetInstance().GetMessage(LocaleMessages.HEADER_BM_DISABLED), e);
                    }
                }
                l.AddRange(currentContentToParagraph);
            }
            return(l);
        }
Esempio n. 14
0
 /* (non-Javadoc)
  * @see com.itextpdf.tool.xml.ITagProcessor#startElement(com.itextpdf.tool.xml.Tag)
  */
 public override IList <IElement> Start(IWorkerContext ctx, Tag tag)
 {
     if (tag.Attributes.ContainsKey(HTML.Attribute.TYPE) && Util.EqualsIgnoreCase(tag.Attributes[HTML.Attribute.TYPE], HTML.Attribute.Value.TEXTCSS))
     {
         String href;
         tag.Attributes.TryGetValue(HTML.Attribute.HREF, out href);
         if (null != href)
         {
             try {
                 GetCSSResolver(ctx).AddCssFile(href, false);
             } catch (CssResolverException e) {
                 LOG.Error(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.LINK_404), href), e);
             } catch (NoCustomContextException) {
                 LOG.Warn(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.CUSTOMCONTEXT_404_CONTINUE), typeof(CssResolverPipeline).FullName));
             }
         }
     }
     return(new List <IElement>(0));
 }
Esempio n. 15
0
            public override void Write(PdfWriter writer, Document doc)
            {
                PdfDestination destination = new PdfDestination(PdfDestination.XYZ, 20,
                                                                writer.GetVerticalPosition(false), 0);
                IDictionary <String, Object> memory = context.GetMemory();
                HeaderNode tree = null;

                if (memory.ContainsKey(HtmlPipelineContext.BOOKMARK_TREE))
                {
                    tree = (HeaderNode)memory[HtmlPipelineContext.BOOKMARK_TREE];
                }
                int level = header.GetLevel(tag);

                if (null == tree)
                {
                    // first h tag encounter
                    tree = new HeaderNode(0, writer.RootOutline, null);
                }
                else
                {
                    // calculate parent
                    int lastLevel = tree.Level;
                    if (lastLevel == level)
                    {
                        tree = tree.Parent;
                    }
                    else if (lastLevel > level)
                    {
                        while (lastLevel >= level)
                        {
                            lastLevel = tree.Parent.Level;
                            tree      = tree.Parent;
                        }
                    }
                }
                if (LOGGER.IsLogging(Level.TRACE))
                {
                    LOGGER.Trace(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.ADD_HEADER), title.ToString()));
                }
                HeaderNode node = new HeaderNode(level, new PdfOutline(tree.Outline, destination, title), tree);

                memory[HtmlPipelineContext.BOOKMARK_TREE] = node;
            }
Esempio n. 16
0
        /*
         * (non-Javadoc)
         *
         * @see
         * com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag,
         * java.util.List, com.itextpdf.text.Document)
         */
        public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
        {
            try {
                Paragraph p   = null;
                PdfDiv    div = (PdfDiv)GetCssAppliers().Apply(new PdfDiv(), tag, GetHtmlPipelineContext(ctx));
                foreach (IElement e in currentContent)
                {
                    if (e is Paragraph || e is PdfPTable || e is PdfDiv)
                    {
                        if (p != null)
                        {
                            if (p.Trim())
                            {
                                div.AddElement(p);
                            }
                            p = null;
                        }
                        div.AddElement(e);
                    }
                    else
                    {
                        if (p == null)
                        {
                            p = new Paragraph();
                            p.MultipliedLeading = 1.2f;
                        }
                        p.Add(e);
                    }
                }
                if (p != null && p.Trim())
                {
                    div.AddElement(p);
                }

                List <IElement> l = new List <IElement>(1);
                l.Add(div);
                return(l);
            } catch (NoCustomContextException e) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
            }
        }
Esempio n. 17
0
        /*
         * (non-Javadoc)
         *
         * @see com.itextpdf.tool.xml.ITagProcessor#content(com.itextpdf.tool.xml.Tag, java.util.List,
         * com.itextpdf.text.Document, java.lang.String)
         */
        public override IList <IElement> Content(IWorkerContext ctx, Tag tag, String content)
        {
            List <Chunk>       sanitizedChunks = HTMLUtils.Sanitize(content, false);
            List <IElement>    l = new List <IElement>(1);
            NoNewLineParagraph sanitizedNoNewLineParagraph = new NoNewLineParagraph();

            foreach (Chunk sanitized in sanitizedChunks)
            {
                Chunk c = GetCssAppliers().ChunkCssAplier.Apply(sanitized, tag);
                sanitizedNoNewLineParagraph.Add(c);
            }
            if (sanitizedNoNewLineParagraph.Count > 0)
            {
                try {
                    l.Add(GetCssAppliers().Apply(sanitizedNoNewLineParagraph, tag, GetHtmlPipelineContext(ctx)));
                } catch (NoCustomContextException e) {
                    throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
                }
            }
            return(l);
        }
Esempio n. 18
0
        private void ProcessListItems(IWorkerContext ctx, Tag tag, IList <ListItem> listItems, HtmlCell cell)
        {
            try {
                List list = new List();
                list.Autoindent      = false;
                list                 = (List)GetCssAppliers().Apply(list, tag, GetHtmlPipelineContext(ctx));
                list.IndentationLeft = 0;
                foreach (ListItem li in listItems)
                {
                    ListItem listItem = (ListItem)GetCssAppliers().Apply(li, tag, GetHtmlPipelineContext(ctx));
                    listItem.SpacingAfter  = 0;
                    listItem.SpacingBefore = 0;

                    listItem.MultipliedLeading = 1.2f;
                    list.Add(listItem);
                }
                cell.AddElement(list);
                listItems.Clear();
            } catch (NoCustomContextException e) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
            }
        }
Esempio n. 19
0
        /*
         * (non-Javadoc)
         *
         * @see com.itextpdf.tool.xml.ITagProcessor#startElement(com.itextpdf.tool.xml.Tag)
         */
        public override IList <IElement> Start(IWorkerContext ctx, Tag tag)
        {
            String enc;

            tag.Attributes.TryGetValue("encoding", out enc);
            if (null != enc)
            {
                try {
                    Encoding encd = null;
                    try {
                        encd = Encoding.GetEncoding(enc);
                    }
                    catch (ArgumentException) {
                    }
                    if (encd != null)
                    {
                        GetHtmlPipelineContext(ctx).CharSet(encd);
                        if (LOGGER.IsLogging(Level.DEBUG))
                        {
                            LOGGER.Debug(
                                String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.META_CC), enc));
                        }
                    }
                    else
                    {
                        if (LOGGER.IsLogging(Level.DEBUG))
                        {
                            LOGGER.Debug(
                                String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.META_404), GetHtmlPipelineContext(ctx)
                                              .CharSet() == null ? "" : GetHtmlPipelineContext(ctx).CharSet().WebName));
                        }
                    }
                }
                catch (NoCustomContextException) {
                    throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT));
                }
            }
            return(new List <IElement>(0));
        }
Esempio n. 20
0
        /**
         * @param po
         * @throws PipelineException
         */
        private void Write(IWorkerContext context, ProcessObject po)
        {
            MapContext mp = (MapContext)GetLocalContext(context);

            if (po.ContainsWritable())
            {
                Document  doc             = (Document)mp[DOCUMENT];
                bool      continuousWrite = (bool)mp[CONTINUOUS];
                IWritable writable        = null;
                while (null != (writable = po.Poll()))
                {
                    if (writable is WritableElement)
                    {
                        foreach (IElement e in ((WritableElement)writable).Elements())
                        {
                            try {
                                if (!doc.Add(e))
                                {
                                    LOG.Trace(String.Format(
                                                  LocaleMessages.GetInstance().GetMessage(LocaleMessages.ELEMENT_NOT_ADDED),
                                                  e.ToString()));
                                }
                            } catch (DocumentException e1) {
                                if (!continuousWrite)
                                {
                                    throw new PipelineException(e1);
                                }
                                else
                                {
                                    LOG.Error(
                                        LocaleMessages.GetInstance().GetMessage(LocaleMessages.ELEMENT_NOT_ADDED_EXC),
                                        e1);
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 21
0
 /**
  * Adds currentContent list to a paragraph element. If addNewLines is true a
  * Paragraph object is returned, else a NoNewLineParagraph object is
  * returned.
  *
  * @param currentContent IList<IElement> of the current elements to be added.
  * @param addNewLines bool to declare which paragraph element should be
  *            returned, true if new line should be added or not.
  * @param applyCSS true if CSS should be applied on the paragraph
  * @param tag the relevant tag
  * @return a List with paragraphs
  */
 public virtual IList <IElement> CurrentContentToParagraph(IList <IElement> currentContent,
                                                           bool addNewLines, bool applyCSS, Tag tag, IWorkerContext ctx)
 {
     try {
         IList <IElement> list = new List <IElement>();
         if (currentContent.Count > 0)
         {
             if (addNewLines)
             {
                 Paragraph p = new Paragraph();
                 foreach (IElement e in currentContent)
                 {
                     p.Add(e);
                 }
                 if (applyCSS)
                 {
                     p = new ParagraphCssApplier(GetHtmlPipelineContext(ctx)).Apply(p, tag);
                 }
                 list.Add(p);
             }
             else
             {
                 NoNewLineParagraph p = new NoNewLineParagraph();
                 foreach (IElement e in currentContent)
                 {
                     p.Add(e);
                 }
                 p = new NoNewLineParagraphCssApplier(GetHtmlPipelineContext(ctx)).Apply(p, tag);
                 list.Add(p);
             }
             // TODO enhance
         }
         return(list);
     } catch (NoCustomContextException e) {
         throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
     }
 }
Esempio n. 22
0
        /**
         * Called when an ending tag is encountered by the {@link SimpleXMLParser}.
         * This method searches for the tags {@link ITagProcessor} in the given
         * {@link TagProcessorFactory}. If none found and acceptUknown is false a
         * {@link NoTagProcessorException} is thrown. If found the TagProcessors
         * endElement is called.<br />
         * The returned IElement by the ITagProcessor is added to the currentContent
         * stack.<br />
         * If any of the parent tags or the given tags
         * {@link ITagProcessor#isStackOwner()} is true. The returned IElement is put
         * on the respective stack.Else it element is added to the document or the
         * elementList.
         *
         */
        public virtual void EndElement(String tag, String ns)
        {
            String thetag = null;

            if (parseHtml)
            {
                thetag = tag.ToLowerInvariant();
            }
            else
            {
                thetag = tag;
            }
            IWorkerContext ctx = GetLocalWC();

            if (null != ctx.GetCurrentTag() && !thetag.Equals(ctx.GetCurrentTag().Name))
            {
                throw new RuntimeWorkerException(String.Format(
                                                     LocaleMessages.GetInstance().GetMessage(LocaleMessages.INVALID_NESTED_TAG), thetag,
                                                     ctx.GetCurrentTag().Name));
            }
            IPipeline     wp = rootpPipe;
            ProcessObject po = new ProcessObject();

            try {
                while (null != (wp = wp.Close(ctx, ctx.GetCurrentTag(), po)))
                {
                    ;
                }
            } catch (PipelineException e) {
                throw new RuntimeWorkerException(e);
            } finally {
                if (null != ctx.GetCurrentTag())
                {
                    ctx.SetCurrentTag(ctx.GetCurrentTag().Parent);
                }
            }
        }
Esempio n. 23
0
        /* (non-Javadoc)
         * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
         */
        public override IList <IElement> Start(IWorkerContext ctx, Tag tag)
        {
            try {
                IList <IElement>             list = new List <IElement>();
                HtmlPipelineContext          htmlPipelineContext = GetHtmlPipelineContext(ctx);
                LineSeparator                lineSeparator       = (LineSeparator)GetCssAppliers().Apply(new LineSeparator(), tag, htmlPipelineContext);
                Paragraph                    p   = new Paragraph();
                IDictionary <String, String> css = tag.CSS;
                float fontSize = 12;


                if (css.ContainsKey(CSS.Property.FONT_SIZE))
                {
                    fontSize = CssUtils.GetInstance().ParsePxInCmMmPcToPt(css[CSS.Property.FONT_SIZE]);
                }
                String marginTop;
                css.TryGetValue(CSS.Property.MARGIN_TOP, out marginTop);
                if (marginTop == null)
                {
                    marginTop = "0.5em";
                }
                String marginBottom;
                css.TryGetValue(CSS.Property.MARGIN_BOTTOM, out marginBottom);
                if (marginBottom == null)
                {
                    marginBottom = "0.5em";
                }
                p.SpacingBefore = p.SpacingBefore + CssUtils.GetInstance().ParseValueToPt(marginTop, fontSize);
                p.SpacingAfter  = p.SpacingAfter + CssUtils.GetInstance().ParseValueToPt(marginBottom, fontSize);
                p.Leading       = 0;
                p.Add(lineSeparator);
                list.Add(p);
                return(list);
            } catch (NoCustomContextException e) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
            }
        }
Esempio n. 24
0
 /*
  * (non-Javadoc)
  *
  * @see
  * com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag,
  * java.util.List, com.itextpdf.text.Document)
  */
 public override IList <IElement> End(IWorkerContext context, Tag tag, IList <IElement> currentContent)
 {
     try {
         Paragraph        p = null;
         IList <IElement> l = new List <IElement>(1);
         foreach (IElement e in currentContent)
         {
             if (e is Paragraph)
             {
                 if (p != null)
                 {
                     p = new ParagraphCssApplier(GetHtmlPipelineContext(context)).Apply(p, tag);
                     l.Add(p);
                     p = null;
                 }
                 l.Add(e);
             }
             else
             {
                 if (p == null)
                 {
                     p = new Paragraph();
                 }
                 p.Add(e);
             }
         }
         if (p != null)
         {
             p = new ParagraphCssApplier(GetHtmlPipelineContext(context)).Apply(p, tag);
             l.Add(p);
         }
         return(l);
     } catch (NoCustomContextException e) {
         throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
     }
 }
Esempio n. 25
0
 virtual protected void ProcessListItems(IWorkerContext ctx, Tag tag, IList <ListItem> listItems, IList <IElement> l)
 {
     try {
         List list = new List();
         list.Autoindent      = false;
         list                 = (List)GetCssAppliers().Apply(list, tag, GetHtmlPipelineContext(ctx));
         list.IndentationLeft = 0;
         int i = 0;
         foreach (ListItem li in listItems)
         {
             ListItem listItem = (ListItem)GetCssAppliers().Apply(li, tag, GetHtmlPipelineContext(ctx));
             if (i != listItems.Count - 1)
             {
                 listItem.SpacingAfter = 0;
             }
             if (i != 0)
             {
                 listItem.SpacingBefore = 0;
             }
             i++;
             listItem.MultipliedLeading = 1.2f;
             list.Add(listItem);
         }
         if (l.Count > 0)
         {
             IElement latestElement = l[l.Count - 1];
             if (latestElement is Paragraph)
             {
                 ((Paragraph)latestElement).SpacingAfter = 0;
             }
         }
         l.Add(list);
     } catch (NoCustomContextException e) {
         throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
     }
 }
Esempio n. 26
0
        /*
         * (non-Javadoc)
         *
         * @see
         * com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag,
         * java.util.List, com.itextpdf.text.Document)
         */
        public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
        {
            try {
                bool   percentage = false;
                String widthValue = null;
                tag.CSS.TryGetValue(HTML.Attribute.WIDTH, out widthValue);
                if (!tag.CSS.TryGetValue(HTML.Attribute.WIDTH, out widthValue) &&
                    !tag.Attributes.TryGetValue(HTML.Attribute.WIDTH, out widthValue))
                {
                    widthValue = null;
                }
                if (widthValue != null && widthValue.Trim().EndsWith("%"))
                {
                    percentage = true;
                }
                int numberOfColumns = 0;
                List <TableRowElement> tableRows          = new List <TableRowElement>(currentContent.Count);
                IList <IElement>       invalidRowElements = new List <IElement>(1);
                String repeatHeader;
                tag.CSS.TryGetValue(CSS.Property.REPEAT_HEADER, out repeatHeader);
                String repeatFooter;
                tag.CSS.TryGetValue(CSS.Property.REPEAT_FOOTER, out repeatFooter);
                int headerRows = 0;
                int footerRows = 0;
                foreach (IElement e in currentContent)
                {
                    int localNumCols = 0;
                    if (e is TableRowElement)
                    {
                        TableRowElement tableRowElement = (TableRowElement)e;
                        foreach (HtmlCell cell in tableRowElement.Content)
                        {
                            localNumCols += cell.Colspan;
                        }
                        if (localNumCols > numberOfColumns)
                        {
                            numberOfColumns = localNumCols;
                        }
                        tableRows.Add(tableRowElement);
                        if (repeatHeader != null && Util.EqualsIgnoreCase(repeatHeader, "yes") && tableRowElement.RowPlace.Equals(TableRowElement.Place.HEADER))
                        {
                            headerRows++;
                        }
                        if (repeatFooter != null && Util.EqualsIgnoreCase(repeatFooter, "yes") && tableRowElement.RowPlace.Equals(TableRowElement.Place.FOOTER))
                        {
                            footerRows++;
                        }
                    }
                    else
                    {
                        invalidRowElements.Add(e);
                    }
                }
                if (repeatFooter == null || !Util.EqualsIgnoreCase(repeatFooter, "yes"))
                {
                    InsertionSort <TableRowElement>(tableRows, delegate(TableRowElement o1, TableRowElement o2) {
                        return(o1.RowPlace.Normal.CompareTo(o2.RowPlace.Normal));
                    });
                }
                else
                {
                    InsertionSort <TableRowElement>(tableRows, delegate(TableRowElement o1, TableRowElement o2) {
                        return(o1.RowPlace.Repeated.CompareTo(o2.RowPlace.Repeated));
                    });
                }
                PdfPTable table = new PdfPTable(numberOfColumns);
                table.HeaderRows          = headerRows + footerRows;
                table.FooterRows          = footerRows;
                table.HorizontalAlignment = Element.ALIGN_LEFT;
                TableStyleValues styleValues = SetStyleValues(tag);
                table.TableEvent = new TableBorderEvent(styleValues);
                SetVerticalMargin(table, tag, styleValues, ctx);
                WidenLastCell(tableRows, styleValues.HorBorderSpacing);
                float[] columnWidths                = new float[numberOfColumns];
                float[] widestWords                 = new float[numberOfColumns];
                float[] fixedWidths                 = new float[numberOfColumns];
                float[] colspanWidestWords          = new float[numberOfColumns];
                int[]   rowspanValue                = new int[numberOfColumns];
                float   largestColumn               = 0;
                float   largestColspanColumn        = 0;
                int     indexOfLargestColumn        = -1;
                int     indexOfLargestColspanColumn = -1;

                // Initial fill of the widths arrays
                foreach (TableRowElement row in tableRows)
                {
                    int column = 0;
                    foreach (HtmlCell cell in row.Content)
                    {
                        // check whether the current column should be skipped due to a
                        // rowspan value of higher cell in this column.
                        while (rowspanValue[column] > 1)
                        {
                            rowspanValue[column] = rowspanValue[column] - 1;
                            ++column;
                        }
                        // sets a rowspan counter for current column (counter not
                        // needed for last column).
                        if (cell.Rowspan > 1 && column != numberOfColumns - 1)
                        {
                            rowspanValue[column] = cell.Rowspan - 1;
                        }
                        int colspan = cell.Colspan;
                        if (cell.FixedWidth != 0)
                        {
                            float fixedWidth = cell.FixedWidth + GetCellStartWidth(cell);
                            fixedWidth /= colspan;
                            for (int i = 0; i < colspan; i++)
                            {
                                int c = column + i;
                                if (fixedWidth > fixedWidths[c])
                                {
                                    fixedWidths[c]  = fixedWidth;
                                    columnWidths[c] = fixedWidth;
                                }
                            }
                        }
                        if (cell.CompositeElements != null)
                        {
                            float[] widthValues      = SetCellWidthAndWidestWord(cell);
                            float   cellWidth        = widthValues[0] / colspan;
                            float   widestWordOfCell = widthValues[1] / colspan;
                            for (int i = 0; i < colspan; i++)
                            {
                                int c = column + i;
                                if (fixedWidths[c] == 0 && cellWidth > columnWidths[c])
                                {
                                    columnWidths[c] = cellWidth;
                                    if (colspan == 1)
                                    {
                                        if (cellWidth > largestColumn)
                                        {
                                            largestColumn        = cellWidth;
                                            indexOfLargestColumn = c;
                                        }
                                    }
                                    else
                                    {
                                        if (cellWidth > largestColspanColumn)
                                        {
                                            largestColspanColumn        = cellWidth;
                                            indexOfLargestColspanColumn = c;
                                        }
                                    }
                                }
                                if (colspan == 1)
                                {
                                    if (widestWordOfCell > widestWords[c])
                                    {
                                        widestWords[c] = widestWordOfCell;
                                    }
                                }
                                else
                                {
                                    if (widestWordOfCell > colspanWidestWords[c])
                                    {
                                        colspanWidestWords[c] = widestWordOfCell;
                                    }
                                }
                            }
                        }
                        if (colspan > 1)
                        {
                            if (LOG.IsLogging(Level.TRACE))
                            {
                                LOG.Trace(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.COLSPAN), colspan));
                            }
                            column += colspan - 1;
                        }
                        column++;
                    }
                }

                if (indexOfLargestColumn == -1)
                {
                    indexOfLargestColumn = indexOfLargestColspanColumn;
                    if (indexOfLargestColumn == -1)
                    {
                        indexOfLargestColumn = 0;
                    }

                    for (int column = 0; column < numberOfColumns; column++)
                    {
                        widestWords[column] = colspanWidestWords[column];
                    }
                }
                float outerWidth        = GetTableOuterWidth(tag, styleValues.HorBorderSpacing, ctx);
                float initialTotalWidth = GetTableWidth(columnWidths, 0);
                //          float targetWidth = calculateTargetWidth(tag, columnWidths, outerWidth, ctx);
                float targetWidth = 0;
                HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx);
                float max             = htmlPipelineContext.PageSize.Width - outerWidth;
                bool  tableWidthFixed = false;
                if (tag.Attributes.ContainsKey(CSS.Property.WIDTH) || tag.CSS.ContainsKey(CSS.Property.WIDTH))
                {
                    targetWidth = new WidthCalculator().GetWidth(tag, htmlPipelineContext.GetRootTags(), htmlPipelineContext.PageSize.Width);
                    if (targetWidth > max)
                    {
                        targetWidth = max;
                    }
                    tableWidthFixed = true;
                }
                else if (initialTotalWidth <= max)
                {
                    targetWidth = initialTotalWidth;
                }
                else if (null == tag.Parent || (null != tag.Parent && htmlPipelineContext.GetRootTags().Contains(tag.Parent.Name)))
                {
                    targetWidth = max;
                }
                else   /* this table is an inner table and width adjustment is done in outer table */
                {
                    targetWidth = GetTableWidth(columnWidths, outerWidth);
                }
                float totalFixedColumnWidth = GetTableWidth(fixedWidths, 0);
                float targetPercentage      = 0;
                if (totalFixedColumnWidth == initialTotalWidth)   // all column widths are fixed
                {
                    targetPercentage = targetWidth / initialTotalWidth;
                    if (initialTotalWidth > targetWidth)
                    {
                        for (int column = 0; column < columnWidths.Length; column++)
                        {
                            columnWidths[column] *= targetPercentage;
                        }
                    }
                    else if (tableWidthFixed && targetPercentage != 1)
                    {
                        for (int column = 0; column < columnWidths.Length; column++)
                        {
                            columnWidths[column] *= targetPercentage;
                        }
                    }
                }
                else
                {
                    targetPercentage = (targetWidth - totalFixedColumnWidth) / (initialTotalWidth - totalFixedColumnWidth);
                    // Reduce width of columns if the columnWidth array + borders +
                    // paddings
                    // is too large for the given targetWidth.
                    if (initialTotalWidth > targetWidth)
                    {
                        float leftToReduce = 0;
                        for (int column = 0; column < columnWidths.Length; column++)
                        {
                            if (fixedWidths[column] == 0)
                            {
                                // Reduce width of the column to its targetWidth, if
                                // widestWord of column still fits in the targetWidth of
                                // the
                                // column.
                                if (widestWords[column] <= columnWidths[column] * targetPercentage)
                                {
                                    columnWidths[column] *= targetPercentage;
                                    // else take the widest word and calculate space
                                    // left to
                                    // reduce.
                                }
                                else
                                {
                                    columnWidths[column] = widestWords[column];
                                    leftToReduce        += widestWords[column] - columnWidths[column] * targetPercentage;
                                }
                                // if widestWord of a column does not fit in the
                                // fixedWidth,
                                // set the column width to the widestWord.
                            }
                            else if (fixedWidths[column] < widestWords[column])
                            {
                                columnWidths[column] = widestWords[column];
                                leftToReduce        += widestWords[column] - fixedWidths[column];
                            }
                        }
                        if (leftToReduce != 0)
                        {
                            // Reduce width of the column with the most text, if its
                            // widestWord still fits in the reduced column.
                            if (widestWords[indexOfLargestColumn] <= columnWidths[indexOfLargestColumn] - leftToReduce)
                            {
                                columnWidths[indexOfLargestColumn] -= leftToReduce;
                            }
                            else     // set all columns to their minimum, with the
                                     // widestWord array.
                            {
                                for (int column = 0; leftToReduce != 0 && column < columnWidths.Length; column++)
                                {
                                    if (fixedWidths[column] == 0 && columnWidths[column] > widestWords[column])
                                    {
                                        float difference = columnWidths[column] - widestWords[column];
                                        if (difference <= leftToReduce)
                                        {
                                            leftToReduce        -= difference;
                                            columnWidths[column] = widestWords[column];
                                        }
                                        else
                                        {
                                            columnWidths[column] -= leftToReduce;
                                            leftToReduce          = 0;
                                        }
                                    }
                                }
                                if (leftToReduce != 0)
                                {
                                    // If the table has an insufficient fixed width
                                    // by
                                    // an
                                    // attribute or style, try to enlarge the table
                                    // to
                                    // its
                                    // minimum width (= widestWords array).
                                    float pageWidth = GetHtmlPipelineContext(ctx).PageSize.Width;
                                    if (GetTableWidth(widestWords, outerWidth) < pageWidth)
                                    {
                                        targetWidth  = GetTableWidth(widestWords, outerWidth);
                                        leftToReduce = 0;
                                    }
                                    else
                                    {
                                        // If all columnWidths are set to the
                                        // widestWordWidths and the table is still
                                        // to
                                        // wide
                                        // content will fall off the edge of a page,
                                        // which
                                        // is similar to HTML.
                                        targetWidth  = pageWidth - outerWidth;
                                        leftToReduce = 0;
                                    }
                                }
                            }
                        }
                        // Enlarge width of columns to fit the targetWidth.
                    }
                    else if (initialTotalWidth < targetWidth)
                    {
                        for (int column = 0; column < columnWidths.Length; column++)
                        {
                            if (fixedWidths[column] == 0)
                            {
                                columnWidths[column] *= targetPercentage;
                            }
                        }
                    }
                }
                try {
                    table.SetTotalWidth(columnWidths);
                    table.LockedWidth        = true;
                    table.DefaultCell.Border = Rectangle.NO_BORDER;
                } catch (DocumentException e) {
                    throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
                }
                float?tableHeight    = new HeightCalculator().GetHeight(tag, GetHtmlPipelineContext(ctx).PageSize.Height);
                float?tableRowHeight = null;
                if (tableHeight != null && tableHeight > 0)
                {
                    tableRowHeight = tableHeight / tableRows.Count;
                }
                int rowNumber = 0;
                foreach (TableRowElement row in tableRows)
                {
                    int   columnNumber      = -1;
                    float?computedRowHeight = null;

                    /*if ( tableHeight != null &&  tableRows.IndexOf(row) == tableRows.Count - 1) {
                     *  float computedTableHeigt = table.CalculateHeights();
                     *  computedRowHeight = tableHeight - computedTableHeigt;
                     * }*/
                    foreach (HtmlCell cell in row.Content)
                    {
                        IList <IElement> compositeElements = cell.CompositeElements;
                        if (compositeElements != null)
                        {
                            foreach (IElement baseLevel in compositeElements)
                            {
                                if (baseLevel is PdfPTable)
                                {
                                    TableStyleValues cellValues        = cell.CellValues;
                                    float            totalBordersWidth = cellValues.IsLastInRow ? styleValues.HorBorderSpacing * 2
                                            : styleValues.HorBorderSpacing;
                                    totalBordersWidth += cellValues.BorderWidthLeft + cellValues.BorderWidthRight;
                                    float columnWidth = 0;
                                    for (int currentColumnNumber = columnNumber + 1; currentColumnNumber <= columnNumber + cell.Colspan; currentColumnNumber++)
                                    {
                                        columnWidth += columnWidths[currentColumnNumber];
                                    }
                                    IPdfPTableEvent  tableEvent       = ((PdfPTable)baseLevel).TableEvent;
                                    TableStyleValues innerStyleValues = ((TableBorderEvent)tableEvent).TableStyleValues;
                                    totalBordersWidth += innerStyleValues.BorderWidthLeft;
                                    totalBordersWidth += innerStyleValues.BorderWidthRight;
                                    ((PdfPTable)baseLevel).TotalWidth = columnWidth - totalBordersWidth;
                                }
                            }
                        }
                        columnNumber += cell.Colspan;

                        table.AddCell(cell);
                    }
                    table.CompleteRow();
                    if ((computedRowHeight == null || computedRowHeight <= 0) && tableRowHeight != null)
                    {
                        computedRowHeight = tableRowHeight;
                    }
                    if (computedRowHeight != null && computedRowHeight > 0)
                    {
                        float rowHeight = table.GetRow(rowNumber).MaxHeights;
                        if (rowHeight < computedRowHeight)
                        {
                            table.GetRow(rowNumber).MaxHeights = computedRowHeight.Value;
                        }
                        else if (tableRowHeight != null && tableRowHeight < rowHeight)
                        {
                            tableRowHeight = (tableHeight - rowHeight - rowNumber * tableRowHeight)
                                             / (tableRows.Count - rowNumber - 1);
                        }
                    }
                    rowNumber++;
                }
                if (percentage)
                {
                    table.WidthPercentage = utils.ParsePxInCmMmPcToPt(widthValue);
                    table.LockedWidth     = false;
                }
                List <IElement> elems = new List <IElement>();
                if (invalidRowElements.Count > 0)
                {
                    // all invalid row elements taken as caption
                    int i          = 0;
                    Tag captionTag = tag.Children[i++];
                    while (!Util.EqualsIgnoreCase(captionTag.Name, HTML.Tag.CAPTION) && i < tag.Children.Count)
                    {
                        captionTag = tag.Children[i];
                        i++;
                    }
                    String captionSideValue;
                    captionTag.CSS.TryGetValue(CSS.Property.CAPTION_SIDE, out captionSideValue);
                    if (captionSideValue != null && Util.EqualsIgnoreCase(captionSideValue, CSS.Value.BOTTOM))
                    {
                        elems.Add(table);
                        elems.AddRange(invalidRowElements);
                    }
                    else
                    {
                        elems.AddRange(invalidRowElements);
                        elems.Add(table);
                    }
                }
                else
                {
                    elems.Add(table);
                }
                return(elems);
            } catch (NoCustomContextException e) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
            }
        }
Esempio n. 27
0
        /**
         * Calculates top or bottom spacing of the list. In HTML following possibilities exist:
         * <ul>
         * <li><b>padding-top of the ul/ol tag == 0.</b><br />
         * The margin-top values of the ul/ol tag and its <b>first</b> li tag are <b>compared</b>. The total spacing before is the largest margin value and the first li's padding-top.</li>
         * <li><b>padding-top of the ul/ol tag != 0.</b><br />
         * The margin-top or bottom values of the ul/ol tag and its first li tag are <b>accumulated</b>, along with padding-top values of both tags.</li>
         * <li><b>padding-bottom of the ul/ol tag == 0.</b><br />
         * The margin-bottom values of the ul/ol tag and its <b>last</b> li tag are <b>compared</b>. The total spacing after is the largest margin value and the first li's padding-bottom.</li>
         * <li><b>padding-bottom of the ul/ol tag != 0.</b><br />
         * The margin-bottom or bottom values of the ul/ol tag and its last li tag are <b>accumulated</b>, along with padding-bottom values of both tags.</li>
         * </ul>
         * @param isTop bool, if true the top spacing is calculated, if false the bottom spacing is calculated.
         * @param storeMarginBottom if true the calculated margin bottom value is stored for later comparison with the top margin value of the next tag.
         * @param tag the ul/ol tag.
         * @param child first or last li tag of this list.
         * @return float containing the spacing before or after.
         */
        private float CalculateTopOrBottomSpacing(bool isTop, bool storeMarginBottom, Tag tag, Tag child, IWorkerContext ctx)
        {
            float totalSpacing = 0;

            try {
                HtmlPipelineContext context = GetHtmlPipelineContext(ctx);
                String end         = isTop?"-top":"-bottom";
                float  ownFontSize = fst.GetFontSize(tag);
                float  ownMargin   = 0;
                String marginValue;
                tag.CSS.TryGetValue(CSS.Property.MARGIN + end, out marginValue);
                if (marginValue == null)
                {
                    if (null != tag.Parent && GetHtmlPipelineContext(ctx).GetRootTags().Contains(tag.Parent.Name))
                    {
                        ownMargin = ownFontSize;
                    }
                }
                else
                {
                    ownMargin = utils.ParseValueToPt(marginValue, ownFontSize);
                }
                float ownPadding = 0;
                if (tag.CSS.ContainsKey(CSS.Property.PADDING + end))
                {
                    ownPadding = utils.ParseValueToPt(tag.CSS[CSS.Property.PADDING + end], ownFontSize);
                }
                float childFontSize = fst.GetFontSize(child);
                float childMargin   = 0;
                if (child.CSS.ContainsKey(CSS.Property.MARGIN + end))
                {
                    childMargin = utils.ParseValueToPt(child.CSS[CSS.Property.MARGIN + end], childFontSize);
                }
                //Margin values of this tag and its first child need to be compared if paddingTop or bottom = 0.
                if (ownPadding == 0)
                {
                    float margin = 0;
                    if (ownMargin != 0 && childMargin != 0)
                    {
                        margin = ownMargin >= childMargin?ownMargin:childMargin;
                    }
                    else if (ownMargin != 0)
                    {
                        margin = ownMargin;
                    }
                    else if (childMargin != 0)
                    {
                        margin = childMargin;
                    }
                    if (!isTop && storeMarginBottom)
                    {
                        context.GetMemory()[HtmlPipelineContext.LAST_MARGIN_BOTTOM] = margin;
                    }
                    totalSpacing = margin;
                }
                else     // ownpadding != 0 and all margins and paddings need to be accumulated.
                {
                    totalSpacing = ownMargin + ownPadding + childMargin;
                    if (!isTop && storeMarginBottom)
                    {
                        context.GetMemory()[HtmlPipelineContext.LAST_MARGIN_BOTTOM] = ownMargin;
                    }
                }
            } catch (NoCustomContextException e) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
            }
            return(totalSpacing);
        }
Esempio n. 28
0
 /**
  * @param src the src attribute, used by localization message
  * @param e the actual error
  */
 public NoImageException(String src, Exception e) : base(String.Format(LocaleMessages.GetInstance().GetMessage(LocaleMessages.IMG_SRC_NOTCONVERTED), src), e)
 {
 }
Esempio n. 29
0
        /**
         * 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, IImageProvider htmlPipelineContext)
        {
            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);
                    SynchronizeSymbol(fontSize, lst, color);
                }
                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);
                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]);
                iTextSharp.text.Image img = null;
                try {
                    if (htmlPipelineContext == null)
                    {
                        img = new ImageRetrieve().RetrieveImage(url);
                    }
                    else
                    {
                        try {
                            img = new ImageRetrieve(htmlPipelineContext).RetrieveImage(url);
                        } catch (NoImageException) {
                            if (LOG.IsLogging(Level.TRACE))
                            {
                                LOG.Trace(String.Format(LocaleMessages.GetInstance().GetMessage("css.applier.list.noimage")));
                            }
                            img = new ImageRetrieve().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 (IOException e) {
                    if (LOG.IsLogging(Level.ERROR))
                    {
                        LOG.Error(String.Format(LocaleMessages.GetInstance().GetMessage("html.tag.list.failed"), url), e);
                    }
                    lst = new List(List.UNORDERED);
                } catch (NoImageException e) {
                    if (LOG.IsLogging(Level.ERROR))
                    {
                        LOG.Error(e.Message, 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);
        }
Esempio n. 30
0
        public override IList <IElement> Start(IWorkerContext ctx, Tag tag)
        {
            IList <IElement> result;
            LineSeparator    lineSeparator;
            var cssUtil = CssUtils.GetInstance();

            try
            {
                IList <IElement>    list = new List <IElement>();
                HtmlPipelineContext htmlPipelineContext = this.GetHtmlPipelineContext(ctx);

                Paragraph paragraph = new Paragraph();
                IDictionary <string, string> css = tag.CSS;
                float baseValue = 12f;
                if (css.ContainsKey("font-size"))
                {
                    baseValue = cssUtil.ParsePxInCmMmPcToPt(css["font-size"]);
                }
                string text;
                css.TryGetValue("margin-top", out text);
                if (text == null)
                {
                    text = "0.5em";
                }

                string text2;
                css.TryGetValue("margin-bottom", out text2);
                if (text2 == null)
                {
                    text2 = "0.5em";
                }

                string border;
                css.TryGetValue(CSS.Property.BORDER_BOTTOM_STYLE, out border);
                lineSeparator = border != null && border == "dotted"
                    ? new DottedLineSeparator()
                    : new LineSeparator();

                var element = (LineSeparator)this.GetCssAppliers().Apply(
                    lineSeparator, tag, htmlPipelineContext
                    );

                string color;
                css.TryGetValue(CSS.Property.BORDER_BOTTOM_COLOR, out color);
                if (color != null)
                {
                    // WebColors deprecated, but docs don't state replacement
                    element.LineColor = WebColors.GetRGBColor(color);
                }

                paragraph.SpacingBefore += cssUtil.ParseValueToPt(text, baseValue);
                paragraph.SpacingAfter  += cssUtil.ParseValueToPt(text2, baseValue);
                paragraph.Leading        = 0f;
                paragraph.Add(element);
                list.Add(paragraph);
                result = list;
            }
            catch (NoCustomContextException cause)
            {
                throw new RuntimeWorkerException(
                          LocaleMessages.GetInstance().GetMessage("customcontext.404"),
                          cause
                          );
            }
            return(result);
        }