/// <summary>Applies an image list style to an element.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="element">the element</param>
        public static void ApplyListStyleImageProperty(IDictionary <String, String> cssProps, ProcessorContext context
                                                       , IPropertyContainer element)
        {
            String listStyleImage = cssProps.Get(CssConstants.LIST_STYLE_IMAGE);

            if (listStyleImage != null && !CssConstants.NONE.Equals(listStyleImage))
            {
                String     url          = CssUtils.ExtractUrl(listStyleImage);
                PdfXObject imageXObject = context.GetResourceResolver().RetrieveImageExtended(url);
                if (imageXObject != null)
                {
                    Image image = null;
                    if (imageXObject is PdfImageXObject)
                    {
                        image = new Image((PdfImageXObject)imageXObject);
                    }
                    else
                    {
                        if (imageXObject is PdfFormXObject)
                        {
                            image = new Image((PdfFormXObject)imageXObject);
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    element.SetProperty(Property.LIST_SYMBOL, image);
                    element.SetProperty(Property.LIST_SYMBOL_INDENT, 5);
                }
            }
        }
Exemple #2
0
        /// <summary>Resolves content.</summary>
        /// <param name="styles">the styles map</param>
        /// <param name="contentContainer">the content container</param>
        /// <param name="context">the CSS context</param>
        /// <returns>
        /// a list of
        /// <see cref="iText.StyledXmlParser.Node.INode"/>
        /// instances
        /// </returns>
        internal static IList <INode> ResolveContent(IDictionary <String, String> styles, INode contentContainer, CssContext
                                                     context)
        {
            String        contentStr = styles.Get(CssConstants.CONTENT);
            IList <INode> result     = new List <INode>();

            if (contentStr == null || CssConstants.NONE.Equals(contentStr) || CssConstants.NORMAL.Equals(contentStr))
            {
                return(null);
            }
            CssDeclarationValueTokenizer tokenizer = new CssDeclarationValueTokenizer(contentStr);

            CssDeclarationValueTokenizer.Token token;
            CssQuotes quotes = null;

            while ((token = tokenizer.GetNextValidToken()) != null)
            {
                if (token.IsString())
                {
                    result.Add(new CssContentPropertyResolver.ContentTextNode(contentContainer, token.GetValue()));
                }
                else
                {
                    if (token.GetValue().StartsWith(CssConstants.COUNTERS + "("))
                    {
                        String paramsStr = token.GetValue().JSubstring(CssConstants.COUNTERS.Length + 1, token.GetValue().Length -
                                                                       1);
                        String[] @params = iText.IO.Util.StringUtil.Split(paramsStr, ",");
                        if (@params.Length == 0)
                        {
                            return(ErrorFallback(contentStr));
                        }
                        // Counters are denoted by case-sensitive identifiers
                        String counterName          = @params[0].Trim();
                        String counterSeparationStr = @params[1].Trim();
                        counterSeparationStr = counterSeparationStr.JSubstring(1, counterSeparationStr.Length - 1);
                        String            listStyleType  = @params.Length > 2 ? @params[2].Trim() : null;
                        CssCounterManager counterManager = context.GetCounterManager();
                        INode             scope          = contentContainer;
                        if (CssConstants.PAGE.Equals(counterName))
                        {
                            result.Add(new PageCountElementNode(false, contentContainer));
                        }
                        else
                        {
                            if (CssConstants.PAGES.Equals(counterName))
                            {
                                result.Add(new PageCountElementNode(true, contentContainer));
                            }
                            else
                            {
                                String resolvedCounter = counterManager.ResolveCounters(counterName, counterSeparationStr, listStyleType,
                                                                                        scope);
                                if (resolvedCounter == null)
                                {
                                    logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.UNABLE_TO_RESOLVE_COUNTER, counterName
                                                                          ));
                                }
                                else
                                {
                                    result.Add(new CssContentPropertyResolver.ContentTextNode(scope, resolvedCounter));
                                }
                            }
                        }
                    }
                    else
                    {
                        if (token.GetValue().StartsWith(CssConstants.COUNTER + "("))
                        {
                            String paramsStr = token.GetValue().JSubstring(CssConstants.COUNTER.Length + 1, token.GetValue().Length -
                                                                           1);
                            String[] @params = iText.IO.Util.StringUtil.Split(paramsStr, ",");
                            if (@params.Length == 0)
                            {
                                return(ErrorFallback(contentStr));
                            }
                            // Counters are denoted by case-sensitive identifiers
                            String            counterName    = @params[0].Trim();
                            String            listStyleType  = @params.Length > 1 ? @params[1].Trim() : null;
                            CssCounterManager counterManager = context.GetCounterManager();
                            INode             scope          = contentContainer;
                            if (CssConstants.PAGE.Equals(counterName))
                            {
                                result.Add(new PageCountElementNode(false, contentContainer));
                            }
                            else
                            {
                                if (CssConstants.PAGES.Equals(counterName))
                                {
                                    result.Add(new PageCountElementNode(true, contentContainer));
                                }
                                else
                                {
                                    String resolvedCounter = counterManager.ResolveCounter(counterName, listStyleType, scope);
                                    if (resolvedCounter == null)
                                    {
                                        logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.UNABLE_TO_RESOLVE_COUNTER, counterName
                                                                              ));
                                    }
                                    else
                                    {
                                        result.Add(new CssContentPropertyResolver.ContentTextNode(scope, resolvedCounter));
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (token.GetValue().StartsWith("url("))
                            {
                                IDictionary <String, String> attributes = new Dictionary <String, String>();
                                attributes.Put(AttributeConstants.SRC, CssUtils.ExtractUrl(token.GetValue()));
                                //TODO: probably should add user agent styles on CssContentElementNode creation, not here.
                                attributes.Put(AttributeConstants.STYLE, CssConstants.DISPLAY + ":" + CssConstants.INLINE_BLOCK);
                                result.Add(new CssContentElementNode(contentContainer, TagConstants.IMG, attributes));
                            }
                            else
                            {
                                if (CssGradientUtil.IsCssLinearGradientValue(token.GetValue()))
                                {
                                    IDictionary <String, String> attributes = new Dictionary <String, String>();
                                    attributes.Put(AttributeConstants.STYLE, CssConstants.BACKGROUND_IMAGE + ":" + token.GetValue() + ";" + CssConstants
                                                   .HEIGHT + ":" + CssConstants.INHERIT + ";" + CssConstants.WIDTH + ":" + CssConstants.INHERIT + ";");
                                    result.Add(new CssContentElementNode(contentContainer, TagConstants.DIV, attributes));
                                }
                                else
                                {
                                    if (token.GetValue().StartsWith("attr(") && contentContainer is CssPseudoElementNode)
                                    {
                                        int endBracket = token.GetValue().IndexOf(')');
                                        if (endBracket > 5)
                                        {
                                            String attrName = token.GetValue().JSubstring(5, endBracket);
                                            if (attrName.Contains("(") || attrName.Contains(" ") || attrName.Contains("'") || attrName.Contains("\""))
                                            {
                                                return(ErrorFallback(contentStr));
                                            }
                                            IElementNode element = (IElementNode)contentContainer.ParentNode();
                                            String       value   = element.GetAttribute(attrName);
                                            result.Add(new CssContentPropertyResolver.ContentTextNode(contentContainer, value == null ? "" : value));
                                        }
                                    }
                                    else
                                    {
                                        if (token.GetValue().EndsWith("quote") && contentContainer is IStylesContainer)
                                        {
                                            if (quotes == null)
                                            {
                                                quotes = CssQuotes.CreateQuotes(styles.Get(CssConstants.QUOTES), true);
                                            }
                                            String value = quotes.ResolveQuote(token.GetValue(), context);
                                            if (value == null)
                                            {
                                                return(ErrorFallback(contentStr));
                                            }
                                            result.Add(new CssContentPropertyResolver.ContentTextNode(contentContainer, value));
                                        }
                                        else
                                        {
                                            if (token.GetValue().StartsWith(CssConstants.ELEMENT + "(") && contentContainer is PageMarginBoxContextNode
                                                )
                                            {
                                                String paramsStr = token.GetValue().JSubstring(CssConstants.ELEMENT.Length + 1, token.GetValue().Length -
                                                                                               1);
                                                String[] @params = iText.IO.Util.StringUtil.Split(paramsStr, ",");
                                                if (@params.Length == 0)
                                                {
                                                    return(ErrorFallback(contentStr));
                                                }
                                                String name = @params[0].Trim();
                                                String runningElementOccurrence = null;
                                                if (@params.Length > 1)
                                                {
                                                    runningElementOccurrence = @params[1].Trim();
                                                }
                                                result.Add(new PageMarginRunningElementNode(name, runningElementOccurrence));
                                            }
                                            else
                                            {
                                                return(ErrorFallback(contentStr));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(result);
        }
Exemple #3
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);
        }
Exemple #4
0
 virtual public void ParseUrlSingleQuoted()
 {
     Assert.AreEqual("file.jpg", css.ExtractUrl("url( 'file.jpg')"));
 }
        private static IList <BackgroundImage> GetBackgroundImagesList(IList <String> backgroundImagesArray, ProcessorContext
                                                                       context, float em, float rem, IList <String> backgroundPositionXArray, IList <String> backgroundPositionYArray
                                                                       , IList <IList <String> > backgroundSizeArray, IList <String> backgroundBlendModeArray, IList <String> backgroundRepeatArray
                                                                       , IList <String> backgroundClipArray, IList <String> backgroundOriginArray)
        {
            IList <BackgroundImage> backgroundImagesList = new List <BackgroundImage>();

            for (int i = 0; i < backgroundImagesArray.Count; ++i)
            {
                String backgroundImage = backgroundImagesArray[i];
                if (backgroundImage == null || CssConstants.NONE.Equals(backgroundImage))
                {
                    continue;
                }
                BackgroundPosition position = ApplyBackgroundPosition(backgroundPositionXArray, backgroundPositionYArray,
                                                                      i, em, rem);
                BlendMode        blendMode    = ApplyBackgroundBlendMode(backgroundBlendModeArray, i);
                bool             imageApplied = false;
                BackgroundRepeat repeat       = ApplyBackgroundRepeat(backgroundRepeatArray, i);
                BackgroundBox    clip         = GetBackgroundBoxProperty(backgroundClipArray, i, BackgroundBox.BORDER_BOX);
                BackgroundBox    origin       = GetBackgroundBoxProperty(backgroundOriginArray, i, BackgroundBox.PADDING_BOX);
                if (CssGradientUtil.IsCssLinearGradientValue(backgroundImage))
                {
                    imageApplied = ApplyLinearGradient(backgroundImage, backgroundImagesList, blendMode, position, em, rem, repeat
                                                       , clip, origin);
                }
                else
                {
                    PdfXObject image = context.GetResourceResolver().RetrieveImageExtended(CssUtils.ExtractUrl(backgroundImage
                                                                                                               ));
                    imageApplied = ApplyBackgroundImage(image, backgroundImagesList, repeat, blendMode, position, clip, origin
                                                        );
                }
                if (imageApplied)
                {
                    ApplyBackgroundSize(backgroundSizeArray, em, rem, i, backgroundImagesList[backgroundImagesList.Count - 1]);
                }
            }
            return(backgroundImagesList);
        }
        /// <summary>Applies background to an element.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="element">the element</param>
        public static void ApplyBackground(IDictionary <String, String> cssProps, ProcessorContext context, IPropertyContainer
                                           element)
        {
            String backgroundColorStr = cssProps.Get(CssConstants.BACKGROUND_COLOR);

            if (backgroundColorStr != null && !CssConstants.TRANSPARENT.Equals(backgroundColorStr))
            {
                float[]    rgbaColor       = CssUtils.ParseRgbaColor(backgroundColorStr);
                Color      color           = new DeviceRgb(rgbaColor[0], rgbaColor[1], rgbaColor[2]);
                float      opacity         = rgbaColor[3];
                Background backgroundColor = new Background(color, opacity);
                element.SetProperty(Property.BACKGROUND, backgroundColor);
            }
            String backgroundImageStr = cssProps.Get(CssConstants.BACKGROUND_IMAGE);

            if (backgroundImageStr != null && !backgroundImageStr.Equals(CssConstants.NONE))
            {
                String     backgroundRepeatStr = cssProps.Get(CssConstants.BACKGROUND_REPEAT);
                PdfXObject image = context.GetResourceResolver().RetrieveImageExtended(CssUtils.ExtractUrl(backgroundImageStr
                                                                                                           ));
                bool repeatX = true;
                bool repeatY = true;
                if (backgroundRepeatStr != null)
                {
                    repeatX = backgroundRepeatStr.Equals(CssConstants.REPEAT) || backgroundRepeatStr.Equals(CssConstants.REPEAT_X
                                                                                                            );
                    repeatY = backgroundRepeatStr.Equals(CssConstants.REPEAT) || backgroundRepeatStr.Equals(CssConstants.REPEAT_Y
                                                                                                            );
                }
                if (image != null)
                {
                    BackgroundImage backgroundImage = null;
                    if (image is PdfImageXObject)
                    {
                        backgroundImage = new BackgroundImage((PdfImageXObject)image, repeatX, repeatY);
                    }
                    else
                    {
                        if (image is PdfFormXObject)
                        {
                            backgroundImage = new BackgroundImage((PdfFormXObject)image, repeatX, repeatY);
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    element.SetProperty(Property.BACKGROUND_IMAGE, backgroundImage);
                }
            }
        }
        public override PdfDiv Apply(PdfDiv div, Tag t, IMarginMemory memory, IPageSizeContainable psc, HtmlPipelineContext context) {
            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)) {
                    marginTop = utils.CalculateMarginTop(value, fontSize, memory);
                } else if (Util.EqualsIgnoreCase(key, CSS.Property.MARGIN_BOTTOM)) {
                    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))
                {
                    if (Util.EqualsIgnoreCase(CSS.Value.DOTTED, value))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.DOTTED;
                    }
                    else if (Util.EqualsIgnoreCase(CSS.Value.DASHED, value))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.DASHED;
                    }
                    else if (Util.EqualsIgnoreCase(CSS.Value.SOLID, value))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.SOLID;
                    }
                    else if (Util.EqualsIgnoreCase(CSS.Value.DOUBLE, value))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.DOUBLE;
                    }
                    else if (Util.EqualsIgnoreCase(CSS.Value.GROOVE, value))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.GROOVE;
                    }
                    else if (Util.EqualsIgnoreCase(CSS.Value.RIDGE, value))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.RIDGE;
                    }
                    else if (Util.EqualsIgnoreCase(value, CSS.Value.INSET))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.INSET;
                    }
                    else if (Util.EqualsIgnoreCase(value, CSS.Value.OUTSET))
                    {
                        div.BorderStyle = PdfDiv.BorderTopStyle.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;
        }
Exemple #8
0
        /// <summary>Applies an image list style to an element.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="element">the element</param>
        public static void ApplyListStyleImageProperty(IDictionary <String, String> cssProps, ProcessorContext context
                                                       , IPropertyContainer element)
        {
            String     listStyleImageStr = cssProps.Get(CssConstants.LIST_STYLE_IMAGE);
            PdfXObject imageXObject      = null;

            if (listStyleImageStr != null && !CssConstants.NONE.Equals(listStyleImageStr))
            {
                if (CssGradientUtil.IsCssLinearGradientValue(listStyleImageStr))
                {
                    float em  = CssUtils.ParseAbsoluteLength(cssProps.Get(CssConstants.FONT_SIZE));
                    float rem = context.GetCssContext().GetRootFontSize();
                    try {
                        StrategyBasedLinearGradientBuilder gradientBuilder = CssGradientUtil.ParseCssLinearGradient(listStyleImageStr
                                                                                                                    , em, rem);
                        if (gradientBuilder != null)
                        {
                            Rectangle formBBox = new Rectangle(0, 0, em * LIST_ITEM_MARKER_SIZE_COEFFICIENT, em * LIST_ITEM_MARKER_SIZE_COEFFICIENT
                                                               );
                            PdfDocument pdfDocument   = context.GetPdfDocument();
                            Color       gradientColor = gradientBuilder.BuildColor(formBBox, null, pdfDocument);
                            if (gradientColor != null)
                            {
                                imageXObject = new PdfFormXObject(formBBox);
                                new PdfCanvas((PdfFormXObject)imageXObject, context.GetPdfDocument()).SetColor(gradientColor, true).Rectangle
                                    (formBBox).Fill();
                            }
                        }
                    }
                    catch (StyledXMLParserException) {
                        LOGGER.Warn(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.INVALID_GRADIENT_DECLARATION, listStyleImageStr
                                                             ));
                    }
                }
                else
                {
                    imageXObject = context.GetResourceResolver().RetrieveImageExtended(CssUtils.ExtractUrl(listStyleImageStr));
                }
                if (imageXObject != null)
                {
                    Image image = null;
                    if (imageXObject is PdfImageXObject)
                    {
                        image = new Image((PdfImageXObject)imageXObject);
                    }
                    else
                    {
                        if (imageXObject is PdfFormXObject)
                        {
                            image = new Image((PdfFormXObject)imageXObject);
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    element.SetProperty(Property.LIST_SYMBOL, image);
                    element.SetProperty(Property.LIST_SYMBOL_INDENT, 5);
                }
            }
        }