Пример #1
0
        /// <summary>Sets properties to top-level layout elements converted from HTML.</summary>
        /// <remarks>
        /// Sets properties to top-level layout elements converted from HTML.
        /// This enables features set by user via HTML converter API and also changes properties defaults
        /// to the ones specific to HTML-like behavior.
        /// </remarks>
        /// <param name="cssProperties">HTML document-level css properties.</param>
        /// <param name="context">processor context specific to the current HTML conversion.</param>
        /// <param name="propertyContainer">top-level layout element converted from HTML.</param>
        public static void SetConvertedRootElementProperties(IDictionary <String, String> cssProperties, ProcessorContext
                                                             context, IPropertyContainer propertyContainer)
        {
            propertyContainer.SetProperty(Property.COLLAPSING_MARGINS, true);
            propertyContainer.SetProperty(Property.RENDERING_MODE, RenderingMode.HTML_MODE);
            propertyContainer.SetProperty(Property.FONT_PROVIDER, context.GetFontProvider());
            if (context.GetTempFonts() != null)
            {
                propertyContainer.SetProperty(Property.FONT_SET, context.GetTempFonts());
            }
            // TODO DEVSIX-2534
            IList <String> fontFamilies = FontFamilySplitter.SplitFontFamily(cssProperties.Get(CssConstants.FONT_FAMILY
                                                                                               ));

            if (fontFamilies != null && !propertyContainer.HasOwnProperty(Property.FONT))
            {
                propertyContainer.SetProperty(Property.FONT, fontFamilies.ToArray(new String[0]));
            }
        }
Пример #2
0
        /// <summary>Applies a float value (left, right, or both) 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 ApplyFloating(IDictionary <String, String> cssProps, ProcessorContext context, IPropertyContainer
                                         element)
        {
            String floatValue = cssProps.Get(CssConstants.FLOAT);

            if (floatValue != null)
            {
                if (CssConstants.LEFT.Equals(floatValue))
                {
                    element.SetProperty(Property.FLOAT, FloatPropertyValue.LEFT);
                }
                else
                {
                    if (CssConstants.RIGHT.Equals(floatValue))
                    {
                        element.SetProperty(Property.FLOAT, FloatPropertyValue.RIGHT);
                    }
                }
            }
            String clearValue = cssProps.Get(CssConstants.CLEAR);

            if (clearValue != null)
            {
                if (CssConstants.LEFT.Equals(clearValue))
                {
                    element.SetProperty(Property.CLEAR, ClearPropertyValue.LEFT);
                }
                else
                {
                    if (CssConstants.RIGHT.Equals(clearValue))
                    {
                        element.SetProperty(Property.CLEAR, ClearPropertyValue.RIGHT);
                    }
                    else
                    {
                        if (CssConstants.BOTH.Equals(clearValue))
                        {
                            element.SetProperty(Property.CLEAR, ClearPropertyValue.BOTH);
                        }
                    }
                }
            }
        }
    public override void ProcessEnd(IElementNode element, ProcessorContext context)
    {
        base.ProcessEnd(element, context);
        IPropertyContainer elementResult = GetElementResult();

        if (elementResult != null && !String.IsNullOrEmpty(element.GetAttribute(AttributeConstants.CLASS)))
        {
            elementResult.SetProperty(CUSTOM_PROPERTY_ID, element.GetAttribute(AttributeConstants.CLASS));
        }
    }
Пример #4
0
        /// <summary>Applies opacity to an element.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="container">the container element</param>
        public static void ApplyOpacity(IDictionary <String, String> cssProps, ProcessorContext context, IPropertyContainer
                                        container)
        {
            float?opacity = CssUtils.ParseFloat(cssProps.Get(CssConstants.OPACITY));

            if (opacity != null)
            {
                container.SetProperty(Property.OPACITY, opacity);
            }
        }
Пример #5
0
        /// <summary>
        /// Creates a new
        /// <see cref="PageCountWorker"/>
        /// instance.
        /// </summary>
        /// <param name="element">the element</param>
        /// <param name="context">the context</param>
        public PageCountWorker(IElementNode element, ProcessorContext context)
            : base(element, context)
        {
            bool totalPageCount = element is PageCountElementNode && ((PageCountElementNode)element).IsTotalPageCount(
                );

            pageCountElement = new PageCountElement();
            pageCountElement.SetProperty(Html2PdfProperty.PAGE_COUNT_TYPE, totalPageCount ? PageCountType.TOTAL_PAGE_COUNT
                 : PageCountType.CURRENT_PAGE_NUMBER);
        }
Пример #6
0
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.css.apply.impl.BlockCssApplier#apply(com.itextpdf.html2pdf.attach.ProcessorContext, com.itextpdf.html2pdf.html.node.IStylesContainer, com.itextpdf.html2pdf.attach.ITagWorker)
         */
        public override void Apply(ProcessorContext context, IStylesContainer stylesContainer, ITagWorker tagWorker
                                   )
        {
            IDictionary <String, String> cssProps = stylesContainer.GetStyles();

            base.Apply(context, stylesContainer, tagWorker);
            if (CssConstants.BOTTOM.Equals(cssProps.Get(CssConstants.CAPTION_SIDE)))
            {
                IPropertyContainer container = tagWorker.GetElementResult();
                container.SetProperty(Property.CAPTION_SIDE, CaptionSide.BOTTOM);
            }
        }
 private static void ApplyBackgroundColor(String backgroundColorStr, IPropertyContainer element, BackgroundBox
                                          clip)
 {
     if (backgroundColorStr != null && !CssConstants.TRANSPARENT.Equals(backgroundColorStr))
     {
         float[]    rgbaColor       = CssDimensionParsingUtils.ParseRgbaColor(backgroundColorStr);
         Color      color           = new DeviceRgb(rgbaColor[0], rgbaColor[1], rgbaColor[2]);
         float      opacity         = rgbaColor[3];
         Background backgroundColor = new Background(color, opacity, clip);
         element.SetProperty(Property.BACKGROUND, backgroundColor);
     }
 }
Пример #8
0
        /// <summary>Applies a page break inside property.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="element">the element</param>
        private static void ApplyPageBreakInside(IDictionary <String, String> cssProps, ProcessorContext context, IPropertyContainer
                                                 element)
        {
            // TODO A potential page break location is typically under the influence of the parent element's 'page-break-inside' property,
            // the 'page-break-after' property of the preceding element, and the 'page-break-before' property of the following element.
            // When these properties have values other than 'auto', the values 'always', 'left', and 'right' take precedence over 'avoid'.
            String pageBreakInsideVal = cssProps.Get(CssConstants.PAGE_BREAK_INSIDE);

            if (CssConstants.AVOID.Equals(pageBreakInsideVal))
            {
                element.SetProperty(Property.KEEP_TOGETHER, true);
            }
        }
Пример #9
0
 private static void SetLineHeightByLeading(IPropertyContainer element, String lineHeight, float em, float
                                            rem)
 {
     // specification does not give auto as a possible lineHeight value
     // nevertheless some browsers compute it as normal so we apply the same behaviour.
     // What's more, it's basically the same thing as if lineHeight is not set in the first place
     if (lineHeight != null && !CssConstants.NORMAL.Equals(lineHeight) && !CssConstants.AUTO.Equals(lineHeight)
         )
     {
         if (CssTypesValidationUtils.IsNumericValue(lineHeight))
         {
             float?mult = CssDimensionParsingUtils.ParseFloat(lineHeight);
             if (mult != null)
             {
                 element.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, (float)mult));
             }
         }
         else
         {
             UnitValue lineHeightValue = CssDimensionParsingUtils.ParseLengthValueToPt(lineHeight, em, rem);
             if (lineHeightValue != null && lineHeightValue.IsPointValue())
             {
                 element.SetProperty(Property.LEADING, new Leading(Leading.FIXED, lineHeightValue.GetValue()));
             }
             else
             {
                 if (lineHeightValue != null)
                 {
                     element.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, lineHeightValue.GetValue() / 100));
                 }
             }
         }
     }
     else
     {
         element.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, DEFAULT_LINE_HEIGHT));
     }
 }
 /// <summary>Applies orphans and widows properties to an element.</summary>
 /// <param name="cssProps">the CSS properties</param>
 /// <param name="element">to which the property will be applied.</param>
 public static void ApplyOrphansAndWidows(IDictionary <String, String> cssProps, IPropertyContainer element)
 {
     if (cssProps != null)
     {
         if (cssProps.ContainsKey(CssConstants.WIDOWS))
         {
             int?minWidows = CssUtils.ParseInteger(cssProps.Get(CssConstants.WIDOWS));
             if (minWidows != null && minWidows > 0)
             {
                 element.SetProperty(Property.WIDOWS_CONTROL, new ParagraphWidowsControl(minWidows.Value, MAX_LINES_TO_MOVE
                                                                                         , OVERFLOW_PARAGRAPH_ON_VIOLATION));
             }
         }
         if (cssProps.ContainsKey(CssConstants.ORPHANS))
         {
             int?minOrphans = CssUtils.ParseInteger(cssProps.Get(CssConstants.ORPHANS));
             if (minOrphans != null && minOrphans > 0)
             {
                 element.SetProperty(Property.ORPHANS_CONTROL, new ParagraphOrphansControl(minOrphans.Value));
             }
         }
     }
 }
Пример #11
0
        /// <summary>Applies vertical alignment to cells.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="element">the element</param>
        public static void ApplyVerticalAlignmentForCells(IDictionary <String, String> cssProps, ProcessorContext context
                                                          , IPropertyContainer element)
        {
            String vAlignVal = cssProps.Get(CssConstants.VERTICAL_ALIGN);

            if (vAlignVal != null)
            {
                // In layout, 'top' is the default behaviour for cells;
                // 'baseline' is not supported at the moment on layout level, so it defaults to value 'top';
                // all other possible values except 'middle' and 'bottom' do not apply to cells; 'baseline' is applied instead.
                if (CssConstants.MIDDLE.Equals(vAlignVal))
                {
                    element.SetProperty(Property.VERTICAL_ALIGNMENT, VerticalAlignment.MIDDLE);
                }
                else
                {
                    if (CssConstants.BOTTOM.Equals(vAlignVal))
                    {
                        element.SetProperty(Property.VERTICAL_ALIGNMENT, VerticalAlignment.BOTTOM);
                    }
                }
            }
        }
Пример #12
0
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.css.apply.impl.BlockCssApplier#apply(com.itextpdf.html2pdf.attach.ProcessorContext, com.itextpdf.html2pdf.html.node.IStylesContainer, com.itextpdf.html2pdf.attach.ITagWorker)
         */
        public override void Apply(ProcessorContext context, IStylesContainer stylesContainer, ITagWorker tagWorker
                                   )
        {
            base.Apply(context, stylesContainer, tagWorker);
            IPropertyContainer propertyContainer = tagWorker.GetElementResult();

            if (propertyContainer != null && stylesContainer is INode)
            {
                INode parent     = ((INode)stylesContainer).ParentNode();
                bool  parentIsDl = parent is IElementNode && TagConstants.DL.Equals(((IElementNode)parent).Name());
                if (CssConstants.INSIDE.Equals(stylesContainer.GetStyles().Get(CssConstants.LIST_STYLE_POSITION)) || parentIsDl
                    )
                {
                    propertyContainer.SetProperty(Property.LIST_SYMBOL_POSITION, ListSymbolPosition.INSIDE);
                }
                else
                {
                    propertyContainer.SetProperty(Property.LIST_SYMBOL_POSITION, ListSymbolPosition.OUTSIDE);
                }
                ListStyleApplierUtil.ApplyListStyleTypeProperty(stylesContainer, stylesContainer.GetStyles(), context, propertyContainer
                                                                );
                ListStyleApplierUtil.ApplyListStyleImageProperty(stylesContainer.GetStyles(), context, propertyContainer);
            }
        }
        /// <summary>Tries set margin if the value isn't "auto".</summary>
        /// <param name="marginProperty">the margin property</param>
        /// <param name="marginValue">the margin value</param>
        /// <param name="element">the element</param>
        /// <param name="em">the em value</param>
        /// <param name="rem">the root em value</param>
        /// <param name="baseValue">value used by default</param>
        /// <returns>false if the margin value was "auto"</returns>
        private static bool TrySetMarginIfNotAuto(int marginProperty, String marginValue, IPropertyContainer element
                                                  , float em, float rem, float baseValue)
        {
            bool isAuto = CssConstants.AUTO.Equals(marginValue);

            if (isAuto)
            {
                return(false);
            }
            float?marginVal = ParseMarginValue(marginValue, em, rem, baseValue);

            if (marginVal != null)
            {
                element.SetProperty(marginProperty, UnitValue.CreatePointValue((float)marginVal));
            }
            return(true);
        }
Пример #14
0
        public virtual void Apply(ProcessorContext context, IStylesContainer stylesContainer, ITagWorker tagWorker
                                  )
        {
            IDictionary <String, String> boxStyles = stylesContainer.GetStyles();
            IPropertyContainer           marginBox = tagWorker.GetElementResult();

            BackgroundApplierUtil.ApplyBackground(boxStyles, context, marginBox);
            FontStyleApplierUtil.ApplyFontStyles(boxStyles, context, stylesContainer, marginBox);
            BorderStyleApplierUtil.ApplyBorders(boxStyles, context, marginBox);
            VerticalAlignmentApplierUtil.ApplyVerticalAlignmentForCells(boxStyles, context, marginBox);
            // Set overflow to HIDDEN if it's not explicitly set in css in order to avoid overlapping with page content.
            String overflow = CssConstants.OVERFLOW_VALUES.Contains(boxStyles.Get(CssConstants.OVERFLOW)) ? boxStyles.
                              Get(CssConstants.OVERFLOW) : null;
            String overflowX = CssConstants.OVERFLOW_VALUES.Contains(boxStyles.Get(CssConstants.OVERFLOW_X)) ? boxStyles
                               .Get(CssConstants.OVERFLOW_X) : overflow;

            if (overflowX == null || CssConstants.HIDDEN.Equals(overflowX))
            {
                marginBox.SetProperty(Property.OVERFLOW_X, OverflowPropertyValue.HIDDEN);
            }
            else
            {
                marginBox.SetProperty(Property.OVERFLOW_X, OverflowPropertyValue.VISIBLE);
            }
            String overflowY = CssConstants.OVERFLOW_VALUES.Contains(boxStyles.Get(CssConstants.OVERFLOW_Y)) ? boxStyles
                               .Get(CssConstants.OVERFLOW_Y) : overflow;

            if (overflowY == null || CssConstants.HIDDEN.Equals(overflowY))
            {
                marginBox.SetProperty(Property.OVERFLOW_Y, OverflowPropertyValue.HIDDEN);
            }
            else
            {
                marginBox.SetProperty(Property.OVERFLOW_Y, OverflowPropertyValue.VISIBLE);
            }
            // TODO outlines are currently not supported for page margin boxes, because of the outlines handling specificity (they are handled on renderer's parent level)
            OutlineApplierUtil.ApplyOutlines(boxStyles, context, marginBox);
            marginBox.SetProperty(Property.FONT_PROVIDER, context.GetFontProvider());
            marginBox.SetProperty(Property.FONT_SET, context.GetTempFonts());
            if (!(stylesContainer is PageMarginBoxContextNode))
            {
                ILog logger = LogManager.GetLogger(typeof(PageMarginBoxCssApplier));
                logger.Warn(iText.Html2pdf.LogMessageConstant.PAGE_MARGIN_BOX_SOME_PROPERTIES_NOT_PROCESSED);
                return;
            }
            float availableWidth = ((PageMarginBoxContextNode)stylesContainer).GetContainingBlockForMarginBox().GetWidth
                                       ();
            float availableHeight = ((PageMarginBoxContextNode)stylesContainer).GetContainingBlockForMarginBox().GetHeight
                                        ();

            MarginApplierUtil.ApplyMargins(boxStyles, context, marginBox, availableHeight, availableWidth);
            PaddingApplierUtil.ApplyPaddings(boxStyles, context, marginBox, availableHeight, availableWidth);
        }
        /// <summary>Applies borders 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 ApplyBorders(IDictionary <String, String> cssProps, ProcessorContext context, IPropertyContainer
                                        element)
        {
            float em  = CssUtils.ParseAbsoluteLength(cssProps.Get(CssConstants.FONT_SIZE));
            float rem = context.GetCssContext().GetRootFontSize();

            Border[] bordersArray = GetBordersArray(cssProps, em, rem);
            if (bordersArray[0] != null)
            {
                element.SetProperty(Property.BORDER_TOP, bordersArray[0]);
            }
            if (bordersArray[1] != null)
            {
                element.SetProperty(Property.BORDER_RIGHT, bordersArray[1]);
            }
            if (bordersArray[2] != null)
            {
                element.SetProperty(Property.BORDER_BOTTOM, bordersArray[2]);
            }
            if (bordersArray[3] != null)
            {
                element.SetProperty(Property.BORDER_LEFT, bordersArray[3]);
            }
            BorderRadius[] borderRadii = GetBorderRadiiArray(cssProps, em, rem);
            if (borderRadii[0] != null)
            {
                element.SetProperty(Property.BORDER_TOP_LEFT_RADIUS, borderRadii[0]);
            }
            if (borderRadii[1] != null)
            {
                element.SetProperty(Property.BORDER_TOP_RIGHT_RADIUS, borderRadii[1]);
            }
            if (borderRadii[2] != null)
            {
                element.SetProperty(Property.BORDER_BOTTOM_RIGHT_RADIUS, borderRadii[2]);
            }
            if (borderRadii[3] != null)
            {
                element.SetProperty(Property.BORDER_BOTTOM_LEFT_RADIUS, borderRadii[3]);
            }
        }
        /// <summary>Applies the "right" property.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="element">the element</param>
        /// <param name="em">the em value</param>
        /// <param name="rem">the root em value</param>
        /// <param name="layoutPropertyMapping">the layout property mapping</param>
        private static void ApplyRightProperty(IDictionary <String, String> cssProps, IPropertyContainer element, float
                                               em, float rem, int layoutPropertyMapping)
        {
            String    right    = cssProps.Get(CssConstants.RIGHT);
            UnitValue rightVal = CssDimensionParsingUtils.ParseLengthValueToPt(right, em, rem);

            if (rightVal != null)
            {
                if (rightVal.IsPointValue())
                {
                    element.SetProperty(layoutPropertyMapping, rightVal.GetValue());
                }
                else
                {
                    logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.CSS_PROPERTY_IN_PERCENTS_NOT_SUPPORTED
                                                          , CssConstants.RIGHT));
                }
            }
        }
Пример #17
0
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.css.apply.ICssApplier#apply(com.itextpdf.html2pdf.attach.ProcessorContext, com.itextpdf.html2pdf.html.node.IStylesContainer, com.itextpdf.html2pdf.attach.ITagWorker)
         */
        public virtual void Apply(ProcessorContext context, IStylesContainer stylesContainer, ITagWorker tagWorker
                                  )
        {
            IDictionary <String, String> cssProps      = stylesContainer.GetStyles();
            BodyHtmlStylesContainer      styleProperty = new BodyHtmlStylesContainer();
            IPropertyContainer           container     = tagWorker.GetElementResult();

            if (container != null)
            {
                BackgroundApplierUtil.ApplyBackground(cssProps, context, styleProperty);
                MarginApplierUtil.ApplyMargins(cssProps, context, styleProperty);
                PaddingApplierUtil.ApplyPaddings(cssProps, context, styleProperty);
                BorderStyleApplierUtil.ApplyBorders(cssProps, context, styleProperty);
                if (styleProperty.HasStylesToApply())
                {
                    container.SetProperty(Html2PdfProperty.HTML_STYLING, styleProperty);
                }
            }
        }
Пример #18
0
        /// <summary>Applies the "bottom" property.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="element">the element</param>
        /// <param name="em">the em value</param>
        /// <param name="rem">the root em value</param>
        /// <param name="layoutPropertyMapping">the layout property mapping</param>
        private static void ApplyBottomProperty(IDictionary <String, String> cssProps, IPropertyContainer element,
                                                float em, float rem, int layoutPropertyMapping)
        {
            String    bottom    = cssProps.Get(CssConstants.BOTTOM);
            UnitValue bottomVal = CssUtils.ParseLengthValueToPt(bottom, em, rem);

            if (bottomVal != null)
            {
                if (bottomVal.IsPointValue())
                {
                    element.SetProperty(layoutPropertyMapping, bottomVal.GetValue());
                }
                else
                {
                    logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.CSS_PROPERTY_IN_PERCENTS_NOT_SUPPORTED
                                                          , CssConstants.BOTTOM));
                }
            }
        }
Пример #19
0
 /// <summary>
 /// Creates a new
 /// <see cref="PageCountWorker"/>
 /// instance.
 /// </summary>
 /// <param name="element">the element</param>
 /// <param name="context">the context</param>
 public PageCountWorker(IElementNode element, ProcessorContext context)
     : base(element, context)
 {
     if (element is PageCountElementNode)
     {
         CounterDigitsGlyphStyle digitsStyle = ((PageCountElementNode)element).GetDigitsGlyphStyle();
         if (element is PageTargetCountElementNode)
         {
             pageCountElement = new PageTargetCountElement(((PageTargetCountElementNode)element).GetTarget(), digitsStyle
                                                           );
         }
         else
         {
             bool totalPageCount = ((PageCountElementNode)element).IsTotalPageCount();
             pageCountElement = new PageCountElement(digitsStyle);
             pageCountElement.SetProperty(Html2PdfProperty.PAGE_COUNT_TYPE, totalPageCount ? PageCountType.TOTAL_PAGE_COUNT
                  : PageCountType.CURRENT_PAGE_NUMBER);
         }
     }
 }
Пример #20
0
        /// <summary>Creates a destination</summary>
        /// <param name="tagWorker">the tagworker that is building the (iText) element</param>
        /// <param name="element">the (HTML) element being converted</param>
        /// <param name="context">the Processor context</param>
        public static void CreateDestination(ITagWorker tagWorker, IElementNode element, ProcessorContext context)
        {
            String id = element.GetAttribute(AttributeConstants.ID);

            if (id == null)
            {
                return;
            }
            if (!context.GetLinkContext().IsUsedLinkDestination(id))
            {
                return;
            }
            IPropertyContainer propertyContainer = null;

            if (tagWorker != null)
            {
                if (tagWorker is SpanTagWorker)
                {
                    IList <IPropertyContainer> spanElements = ((SpanTagWorker)tagWorker).GetAllElements();
                    if (!spanElements.IsEmpty())
                    {
                        propertyContainer = spanElements[0];
                    }
                }
                else
                {
                    propertyContainer = tagWorker.GetElementResult();
                }
            }
            if (propertyContainer == null)
            {
                ILog   logger             = LogManager.GetLogger(typeof(iText.Html2pdf.Attach.Util.LinkHelper));
                String tagWorkerClassName = tagWorker != null?tagWorker.GetType().FullName : "null";

                logger.Warn(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.ANCHOR_LINK_NOT_HANDLED, element.Name
                                                         (), id, tagWorkerClassName));
                return;
            }
            propertyContainer.SetProperty(Property.DESTINATION, id);
        }
        /// <summary>Applies a transformation to an element.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the properties context</param>
        /// <param name="element">the element</param>
        public static void ApplyTransformation(IDictionary <String, String> cssProps, ProcessorContext context, IPropertyContainer
                                               element)
        {
            String transformationFunction;

            if (cssProps.Get(CssConstants.TRANSFORM) != null)
            {
                transformationFunction = cssProps.Get(CssConstants.TRANSFORM).ToLowerInvariant();
            }
            else
            {
                return;
            }
            String[]  components       = iText.IO.Util.StringUtil.Split(transformationFunction, "\\)");
            Transform multipleFunction = new Transform(components.Length);

            foreach (String component in components)
            {
                multipleFunction.AddSingleTransform(ParseSingleFunction(component));
            }
            element.SetProperty(Property.TRANSFORM, multipleFunction);
        }
Пример #22
0
        private static TaggingHintKey GetOrCreateHintKey(IPropertyContainer hintOwner, bool setProperty)
        {
            TaggingHintKey hintKey = hintOwner.GetProperty <TaggingHintKey>(Property.TAGGING_HINT_KEY);

            if (hintKey == null)
            {
                IAccessibleElement elem = null;
                if (hintOwner is IAccessibleElement)
                {
                    elem = (IAccessibleElement)hintOwner;
                }
                else
                {
                    if (hintOwner is IRenderer && ((IRenderer)hintOwner).GetModelElement() is IAccessibleElement)
                    {
                        elem = (IAccessibleElement)((IRenderer)hintOwner).GetModelElement();
                    }
                }
                hintKey = new TaggingHintKey(elem, hintOwner is IElement);
                if (elem != null && StandardRoles.ARTIFACT.Equals(elem.GetAccessibilityProperties().GetRole()))
                {
                    hintKey.SetArtifact();
                    hintKey.SetFinished();
                }
                if (setProperty)
                {
                    if (elem is ILargeElement && !((ILargeElement)elem).IsComplete())
                    {
                        ((ILargeElement)elem).SetProperty(Property.TAGGING_HINT_KEY, hintKey);
                    }
                    else
                    {
                        hintOwner.SetProperty(Property.TAGGING_HINT_KEY, hintKey);
                    }
                }
            }
            return(hintKey);
        }
        /// <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);
            String                  backgroundImagesStr    = cssProps.Get(CssConstants.BACKGROUND_IMAGE);
            String                  backgroundRepeatStr    = cssProps.Get(CssConstants.BACKGROUND_REPEAT);
            String                  backgroundSizeStr      = cssProps.Get(CssConstants.BACKGROUND_SIZE);
            String                  backgroundPositionXStr = cssProps.Get(CssConstants.BACKGROUND_POSITION_X);
            String                  backgroundPositionYStr = cssProps.Get(CssConstants.BACKGROUND_POSITION_Y);
            String                  backgroundBlendModeStr = cssProps.Get(CssConstants.BACKGROUND_BLEND_MODE);
            String                  backgroundClipStr      = cssProps.Get(CssConstants.BACKGROUND_CLIP);
            String                  backgroundOriginStr    = cssProps.Get(CssConstants.BACKGROUND_ORIGIN);
            IList <String>          backgroundImagesArray  = CssUtils.SplitStringWithComma(backgroundImagesStr);
            IList <String>          backgroundRepeatArray  = CssUtils.SplitStringWithComma(backgroundRepeatStr);
            IList <IList <String> > backgroundSizeArray    = backgroundSizeStr == null ? null : CssUtils.ExtractShorthandProperties
                                                                 (backgroundSizeStr);
            IList <String> backgroundPositionXArray = CssUtils.SplitStringWithComma(backgroundPositionXStr);
            IList <String> backgroundPositionYArray = CssUtils.SplitStringWithComma(backgroundPositionYStr);
            IList <String> backgroundBlendModeArray = CssUtils.SplitStringWithComma(backgroundBlendModeStr);
            String         fontSize              = cssProps.Get(CssConstants.FONT_SIZE);
            float          em                    = fontSize == null ? 0 : CssDimensionParsingUtils.ParseAbsoluteLength(fontSize);
            float          rem                   = context.GetCssContext().GetRootFontSize();
            IList <String> backgroundClipArray   = CssUtils.SplitStringWithComma(backgroundClipStr);
            IList <String> backgroundOriginArray = CssUtils.SplitStringWithComma(backgroundOriginStr);
            BackgroundBox  clipForColor          = GetBackgroundBoxProperty(backgroundClipArray, backgroundImagesArray.IsEmpty()
                 ? 0 : (backgroundImagesArray.Count - 1), BackgroundBox.BORDER_BOX);

            ApplyBackgroundColor(backgroundColorStr, element, clipForColor);
            IList <BackgroundImage> backgroundImagesList = GetBackgroundImagesList(backgroundImagesArray, context, em,
                                                                                   rem, backgroundPositionXArray, backgroundPositionYArray, backgroundSizeArray, backgroundBlendModeArray
                                                                                   , backgroundRepeatArray, backgroundClipArray, backgroundOriginArray);

            if (!backgroundImagesList.IsEmpty())
            {
                element.SetProperty(Property.BACKGROUND_IMAGE, backgroundImagesList);
            }
        }
Пример #24
0
 /// <summary>Applies a link annotation.</summary>
 /// <param name="container">the containing object</param>
 /// <param name="url">the destination</param>
 public static void ApplyLinkAnnotation(IPropertyContainer container, String url)
 {
     if (container != null)
     {
         PdfLinkAnnotation linkAnnotation;
         if (url.StartsWith("#"))
         {
             String name = url.Substring(1);
             linkAnnotation = (PdfLinkAnnotation) new PdfLinkAnnotation(new Rectangle(0, 0, 0, 0)).SetAction(PdfAction.CreateGoTo
                                                                                                                 (name)).SetFlags(PdfAnnotation.PRINT);
         }
         else
         {
             linkAnnotation = (PdfLinkAnnotation) new PdfLinkAnnotation(new Rectangle(0, 0, 0, 0)).SetAction(PdfAction.CreateURI
                                                                                                                 (url)).SetFlags(PdfAnnotation.PRINT);
         }
         linkAnnotation.SetBorder(new PdfArray(new float[] { 0, 0, 0 }));
         container.SetProperty(Property.LINK_ANNOTATION, linkAnnotation);
         if (container is ILeafElement && container is IAccessibleElement)
         {
             ((IAccessibleElement)container).GetAccessibilityProperties().SetRole(StandardRoles.LINK);
         }
     }
 }
Пример #25
0
 private static void SetLineHeight(IPropertyContainer elementToSet, String lineHeight, float em, float rem)
 {
     if (lineHeight != null && !CssConstants.NORMAL.Equals(lineHeight) && !CssConstants.AUTO.Equals(lineHeight)
         )
     {
         if (CssTypesValidationUtils.IsNumericValue(lineHeight))
         {
             float?number = CssDimensionParsingUtils.ParseFloat(lineHeight);
             if (number != null)
             {
                 elementToSet.SetProperty(Property.LINE_HEIGHT, LineHeight.CreateMultipliedValue((float)number));
             }
             else
             {
                 elementToSet.SetProperty(Property.LINE_HEIGHT, LineHeight.CreateNormalValue());
             }
         }
         else
         {
             UnitValue lineHeightValue = CssDimensionParsingUtils.ParseLengthValueToPt(lineHeight, em, rem);
             if (lineHeightValue != null && lineHeightValue.IsPointValue())
             {
                 elementToSet.SetProperty(Property.LINE_HEIGHT, LineHeight.CreateFixedValue(lineHeightValue.GetValue()));
             }
             else
             {
                 if (lineHeightValue != null)
                 {
                     elementToSet.SetProperty(Property.LINE_HEIGHT, LineHeight.CreateMultipliedValue(lineHeightValue.GetValue()
                                                                                                     / 100f));
                 }
                 else
                 {
                     elementToSet.SetProperty(Property.LINE_HEIGHT, LineHeight.CreateNormalValue());
                 }
             }
         }
     }
     else
     {
         elementToSet.SetProperty(Property.LINE_HEIGHT, LineHeight.CreateNormalValue());
     }
 }
Пример #26
0
        /// <summary>Applies font styles to an element.</summary>
        /// <param name="cssProps">the CSS props</param>
        /// <param name="context">the processor context</param>
        /// <param name="stylesContainer">the styles container</param>
        /// <param name="element">the element</param>
        public static void ApplyFontStyles(IDictionary <String, String> cssProps, ProcessorContext context, IStylesContainer
                                           stylesContainer, IPropertyContainer element)
        {
            float em  = CssDimensionParsingUtils.ParseAbsoluteLength(cssProps.Get(CssConstants.FONT_SIZE));
            float rem = context.GetCssContext().GetRootFontSize();

            if (em != 0)
            {
                element.SetProperty(Property.FONT_SIZE, UnitValue.CreatePointValue(em));
            }
            if (cssProps.Get(CssConstants.FONT_FAMILY) != null)
            {
                // TODO DEVSIX-2534
                IList <String> fontFamilies = FontFamilySplitter.SplitFontFamily(cssProps.Get(CssConstants.FONT_FAMILY));
                element.SetProperty(Property.FONT, fontFamilies.ToArray(new String[fontFamilies.Count]));
            }
            if (cssProps.Get(CssConstants.FONT_WEIGHT) != null)
            {
                element.SetProperty(Property.FONT_WEIGHT, cssProps.Get(CssConstants.FONT_WEIGHT));
            }
            if (cssProps.Get(CssConstants.FONT_STYLE) != null)
            {
                element.SetProperty(Property.FONT_STYLE, cssProps.Get(CssConstants.FONT_STYLE));
            }
            String cssColorPropValue = cssProps.Get(CssConstants.COLOR);

            if (cssColorPropValue != null)
            {
                TransparentColor transparentColor;
                if (!CssConstants.TRANSPARENT.Equals(cssColorPropValue))
                {
                    float[] rgbaColor = CssDimensionParsingUtils.ParseRgbaColor(cssColorPropValue);
                    Color   color     = new DeviceRgb(rgbaColor[0], rgbaColor[1], rgbaColor[2]);
                    float   opacity   = rgbaColor[3];
                    transparentColor = new TransparentColor(color, opacity);
                }
                else
                {
                    transparentColor = new TransparentColor(ColorConstants.BLACK, 0f);
                }
                element.SetProperty(Property.FONT_COLOR, transparentColor);
            }
            // Make sure to place that before text-align applier
            String direction = cssProps.Get(CssConstants.DIRECTION);

            if (CssConstants.RTL.Equals(direction))
            {
                element.SetProperty(Property.BASE_DIRECTION, BaseDirection.RIGHT_TO_LEFT);
                element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.RIGHT);
            }
            else
            {
                if (CssConstants.LTR.Equals(direction))
                {
                    element.SetProperty(Property.BASE_DIRECTION, BaseDirection.LEFT_TO_RIGHT);
                    element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.LEFT);
                }
            }
            if (stylesContainer is IElementNode && ((IElementNode)stylesContainer).ParentNode() is IElementNode && CssConstants
                .RTL.Equals(((IElementNode)((IElementNode)stylesContainer).ParentNode()).GetStyles().Get(CssConstants.
                                                                                                         DIRECTION)) && !element.HasProperty(Property.HORIZONTAL_ALIGNMENT))
            {
                // We should only apply horizontal alignment if parent has dir attribute or direction property
                element.SetProperty(Property.HORIZONTAL_ALIGNMENT, HorizontalAlignment.RIGHT);
            }
            // Make sure to place that after direction applier
            String align = cssProps.Get(CssConstants.TEXT_ALIGN);

            if (CssConstants.LEFT.Equals(align))
            {
                element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.LEFT);
            }
            else
            {
                if (CssConstants.RIGHT.Equals(align))
                {
                    element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.RIGHT);
                }
                else
                {
                    if (CssConstants.CENTER.Equals(align))
                    {
                        element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.CENTER);
                    }
                    else
                    {
                        if (CssConstants.JUSTIFY.Equals(align))
                        {
                            element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.JUSTIFIED);
                            element.SetProperty(Property.SPACING_RATIO, 1f);
                        }
                    }
                }
            }
            String whiteSpace           = cssProps.Get(CssConstants.WHITE_SPACE);
            bool   textWrappingDisabled = CssConstants.NOWRAP.Equals(whiteSpace) || CssConstants.PRE.Equals(whiteSpace);

            element.SetProperty(Property.NO_SOFT_WRAP_INLINE, textWrappingDisabled);
            if (!textWrappingDisabled)
            {
                String overflowWrap = cssProps.Get(CssConstants.OVERFLOW_WRAP);
                if (CssConstants.ANYWHERE.Equals(overflowWrap))
                {
                    element.SetProperty(Property.OVERFLOW_WRAP, OverflowWrapPropertyValue.ANYWHERE);
                }
                else
                {
                    if (CssConstants.BREAK_WORD.Equals(overflowWrap))
                    {
                        element.SetProperty(Property.OVERFLOW_WRAP, OverflowWrapPropertyValue.BREAK_WORD);
                    }
                    else
                    {
                        element.SetProperty(Property.OVERFLOW_WRAP, OverflowWrapPropertyValue.NORMAL);
                    }
                }
                String wordBreak = cssProps.Get(CssConstants.WORD_BREAK);
                if (CssConstants.BREAK_ALL.Equals(wordBreak))
                {
                    element.SetProperty(Property.SPLIT_CHARACTERS, new BreakAllSplitCharacters());
                }
                else
                {
                    if (CssConstants.KEEP_ALL.Equals(wordBreak))
                    {
                        element.SetProperty(Property.SPLIT_CHARACTERS, new KeepAllSplitCharacters());
                    }
                    else
                    {
                        if (CssConstants.BREAK_WORD.Equals(wordBreak))
                        {
                            // CSS specification cite that describes the reason for overflow-wrap overriding:
                            // "For compatibility with legacy content, the word-break property also supports
                            //  a deprecated break-word keyword. When specified, this has the same effect
                            //  as word-break: normal and overflow-wrap: anywhere, regardless of the actual value
                            //  of the overflow-wrap property."
                            element.SetProperty(Property.OVERFLOW_WRAP, OverflowWrapPropertyValue.BREAK_WORD);
                            element.SetProperty(Property.SPLIT_CHARACTERS, new DefaultSplitCharacters());
                        }
                        else
                        {
                            element.SetProperty(Property.SPLIT_CHARACTERS, new DefaultSplitCharacters());
                        }
                    }
                }
            }
            float[] colors = new float[4];
            Color   textDecorationColor;
            float   opacity_1 = 1f;
            String  textDecorationColorProp = cssProps.Get(CssConstants.TEXT_DECORATION_COLOR);

            if (textDecorationColorProp == null || CssConstants.CURRENTCOLOR.Equals(textDecorationColorProp))
            {
                if (element.GetProperty <TransparentColor>(Property.FONT_COLOR) != null)
                {
                    TransparentColor transparentColor = element.GetProperty <TransparentColor>(Property.FONT_COLOR);
                    textDecorationColor = transparentColor.GetColor();
                    opacity_1           = transparentColor.GetOpacity();
                }
                else
                {
                    textDecorationColor = ColorConstants.BLACK;
                }
            }
            else
            {
                if (textDecorationColorProp.StartsWith("hsl"))
                {
                    logger.Error(iText.Html2pdf.LogMessageConstant.HSL_COLOR_NOT_SUPPORTED);
                    textDecorationColor = ColorConstants.BLACK;
                }
                else
                {
                    colors = CssDimensionParsingUtils.ParseRgbaColor(textDecorationColorProp);
                    textDecorationColor = new DeviceRgb(colors[0], colors[1], colors[2]);
                    opacity_1           = colors[3];
                }
            }
            String textDecorationLineProp = cssProps.Get(CssConstants.TEXT_DECORATION_LINE);

            if (textDecorationLineProp != null)
            {
                String[]          textDecorationLines = iText.IO.Util.StringUtil.Split(textDecorationLineProp, "\\s+");
                IList <Underline> underlineList       = new List <Underline>();
                foreach (String textDecorationLine in textDecorationLines)
                {
                    if (CssConstants.BLINK.Equals(textDecorationLine))
                    {
                        logger.Error(iText.Html2pdf.LogMessageConstant.TEXT_DECORATION_BLINK_NOT_SUPPORTED);
                    }
                    else
                    {
                        if (CssConstants.LINE_THROUGH.Equals(textDecorationLine))
                        {
                            underlineList.Add(new Underline(textDecorationColor, opacity_1, .75f, 0, 0, 1 / 4f, PdfCanvasConstants.LineCapStyle
                                                            .BUTT));
                        }
                        else
                        {
                            if (CssConstants.OVERLINE.Equals(textDecorationLine))
                            {
                                underlineList.Add(new Underline(textDecorationColor, opacity_1, .75f, 0, 0, 9 / 10f, PdfCanvasConstants.LineCapStyle
                                                                .BUTT));
                            }
                            else
                            {
                                if (CssConstants.UNDERLINE.Equals(textDecorationLine))
                                {
                                    underlineList.Add(new Underline(textDecorationColor, opacity_1, .75f, 0, 0, -1 / 10f, PdfCanvasConstants.LineCapStyle
                                                                    .BUTT));
                                }
                                else
                                {
                                    if (CssConstants.NONE.Equals(textDecorationLine))
                                    {
                                        underlineList = null;
                                        // if none and any other decoration are used together, none is displayed
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                element.SetProperty(Property.UNDERLINE, underlineList);
            }
            String textIndent = cssProps.Get(CssConstants.TEXT_INDENT);

            if (textIndent != null)
            {
                UnitValue textIndentValue = CssDimensionParsingUtils.ParseLengthValueToPt(textIndent, em, rem);
                if (textIndentValue != null)
                {
                    if (textIndentValue.IsPointValue())
                    {
                        element.SetProperty(Property.FIRST_LINE_INDENT, textIndentValue.GetValue());
                    }
                    else
                    {
                        logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.CSS_PROPERTY_IN_PERCENTS_NOT_SUPPORTED
                                                              , CssConstants.TEXT_INDENT));
                    }
                }
            }
            String letterSpacing = cssProps.Get(CssConstants.LETTER_SPACING);

            if (letterSpacing != null && !CssConstants.NORMAL.Equals(letterSpacing))
            {
                UnitValue letterSpacingValue = CssDimensionParsingUtils.ParseLengthValueToPt(letterSpacing, em, rem);
                if (letterSpacingValue.IsPointValue())
                {
                    element.SetProperty(Property.CHARACTER_SPACING, letterSpacingValue.GetValue());
                }
            }
            // browsers ignore values in percents
            String wordSpacing = cssProps.Get(CssConstants.WORD_SPACING);

            if (wordSpacing != null)
            {
                UnitValue wordSpacingValue = CssDimensionParsingUtils.ParseLengthValueToPt(wordSpacing, em, rem);
                if (wordSpacingValue != null)
                {
                    if (wordSpacingValue.IsPointValue())
                    {
                        element.SetProperty(Property.WORD_SPACING, wordSpacingValue.GetValue());
                    }
                }
            }
            // browsers ignore values in percents
            String lineHeight = cssProps.Get(CssConstants.LINE_HEIGHT);

            SetLineHeight(element, lineHeight, em, rem);
            SetLineHeightByLeading(element, lineHeight, em, rem);
        }
Пример #27
0
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.attach.impl.tags.SpanTagWorker#processEnd(com.itextpdf.html2pdf.html.node.IElementNode, com.itextpdf.html2pdf.attach.ProcessorContext)
         */
        public override void ProcessEnd(IElementNode element, ProcessorContext context)
        {
            base.ProcessEnd(element, context);
            String url = element.GetAttribute(AttributeConstants.HREF);

            if (url != null)
            {
                String @base = context.GetBaseUri();
                if (@base != null)
                {
                    UriResolver uriResolver = new UriResolver(@base);
                    if (!(url.StartsWith("#") && uriResolver.IsLocalBaseUri()))
                    {
                        try {
                            String resolvedUri = uriResolver.ResolveAgainstBaseUri(url).ToExternalForm();
                            if (!url.EndsWith("/") && resolvedUri.EndsWith("/"))
                            {
                                resolvedUri = resolvedUri.JSubstring(0, resolvedUri.Length - 1);
                            }
                            if (!resolvedUri.StartsWith("file:"))
                            {
                                url = resolvedUri;
                            }
                        }
                        catch (UriFormatException) {
                        }
                    }
                }
                for (int i = 0; i < GetAllElements().Count; i++)
                {
                    if (GetAllElements()[i] is RunningElement)
                    {
                        continue;
                    }
                    if (GetAllElements()[i] is IBlockElement)
                    {
                        Div simulatedDiv = new Div();
                        simulatedDiv.GetAccessibilityProperties().SetRole(StandardRoles.LINK);
                        Transform cssTransform = GetAllElements()[i].GetProperty <Transform>(Property.TRANSFORM);
                        if (cssTransform != null)
                        {
                            GetAllElements()[i].DeleteOwnProperty(Property.TRANSFORM);
                            simulatedDiv.SetProperty(Property.TRANSFORM, cssTransform);
                        }
                        FloatPropertyValue?floatPropVal = GetAllElements()[i].GetProperty <FloatPropertyValue?>(Property.FLOAT);
                        if (floatPropVal != null)
                        {
                            GetAllElements()[i].DeleteOwnProperty(Property.FLOAT);
                            simulatedDiv.SetProperty(Property.FLOAT, floatPropVal);
                        }
                        simulatedDiv.Add((IBlockElement)GetAllElements()[i]);
                        String display = childrenDisplayMap.JRemove(GetAllElements()[i]);
                        if (display != null)
                        {
                            childrenDisplayMap.Put(simulatedDiv, display);
                        }
                        GetAllElements()[i] = simulatedDiv;
                    }
                    LinkHelper.ApplyLinkAnnotation(GetAllElements()[i], url);
                }
            }
            if (!GetAllElements().IsEmpty())
            {
                String             name         = element.GetAttribute(AttributeConstants.NAME);
                IPropertyContainer firstElement = GetAllElements()[0];
                firstElement.SetProperty(Property.DESTINATION, name);
            }
        }
Пример #28
0
        /// <summary>Applies font styles to an element.</summary>
        /// <param name="cssProps">the CSS props</param>
        /// <param name="context">the processor context</param>
        /// <param name="stylesContainer">the styles container</param>
        /// <param name="element">the element</param>
        public static void ApplyFontStyles(IDictionary <String, String> cssProps, ProcessorContext context, IStylesContainer
                                           stylesContainer, IPropertyContainer element)
        {
            float em  = CssUtils.ParseAbsoluteLength(cssProps.Get(CssConstants.FONT_SIZE));
            float rem = context.GetCssContext().GetRootFontSize();

            if (em != 0)
            {
                element.SetProperty(Property.FONT_SIZE, UnitValue.CreatePointValue(em));
            }
            if (cssProps.Get(CssConstants.FONT_FAMILY) != null)
            {
                // TODO DEVSIX-2534
                IList <String> fontFamilies = FontFamilySplitter.SplitFontFamily(cssProps.Get(CssConstants.FONT_FAMILY));
                element.SetProperty(Property.FONT, fontFamilies.ToArray(new String[fontFamilies.Count]));
            }
            if (cssProps.Get(CssConstants.FONT_WEIGHT) != null)
            {
                element.SetProperty(Property.FONT_WEIGHT, cssProps.Get(CssConstants.FONT_WEIGHT));
            }
            if (cssProps.Get(CssConstants.FONT_STYLE) != null)
            {
                element.SetProperty(Property.FONT_STYLE, cssProps.Get(CssConstants.FONT_STYLE));
            }
            String cssColorPropValue = cssProps.Get(CssConstants.COLOR);

            if (cssColorPropValue != null)
            {
                TransparentColor transparentColor;
                if (!CssConstants.TRANSPARENT.Equals(cssColorPropValue))
                {
                    float[] rgbaColor = CssUtils.ParseRgbaColor(cssColorPropValue);
                    Color   color     = new DeviceRgb(rgbaColor[0], rgbaColor[1], rgbaColor[2]);
                    float   opacity   = rgbaColor[3];
                    transparentColor = new TransparentColor(color, opacity);
                }
                else
                {
                    transparentColor = new TransparentColor(ColorConstants.BLACK, 0f);
                }
                element.SetProperty(Property.FONT_COLOR, transparentColor);
            }
            // Make sure to place that before text-align applier
            String direction = cssProps.Get(CssConstants.DIRECTION);

            if (CssConstants.RTL.Equals(direction))
            {
                element.SetProperty(Property.BASE_DIRECTION, BaseDirection.RIGHT_TO_LEFT);
                element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.RIGHT);
            }
            else
            {
                if (CssConstants.LTR.Equals(direction))
                {
                    element.SetProperty(Property.BASE_DIRECTION, BaseDirection.LEFT_TO_RIGHT);
                    element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.LEFT);
                }
            }
            if (stylesContainer is IElementNode && ((IElementNode)stylesContainer).ParentNode() is IElementNode && CssConstants
                .RTL.Equals(((IElementNode)((IElementNode)stylesContainer).ParentNode()).GetStyles().Get(CssConstants.
                                                                                                         DIRECTION)) && !element.HasProperty(Property.HORIZONTAL_ALIGNMENT))
            {
                // We should only apply horizontal alignment if parent has dir attribute or direction property
                element.SetProperty(Property.HORIZONTAL_ALIGNMENT, HorizontalAlignment.RIGHT);
            }
            // Make sure to place that after direction applier
            String align = cssProps.Get(CssConstants.TEXT_ALIGN);

            if (CssConstants.LEFT.Equals(align))
            {
                element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.LEFT);
            }
            else
            {
                if (CssConstants.RIGHT.Equals(align))
                {
                    element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.RIGHT);
                }
                else
                {
                    if (CssConstants.CENTER.Equals(align))
                    {
                        element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.CENTER);
                    }
                    else
                    {
                        if (CssConstants.JUSTIFY.Equals(align))
                        {
                            element.SetProperty(Property.TEXT_ALIGNMENT, TextAlignment.JUSTIFIED);
                            element.SetProperty(Property.SPACING_RATIO, 1f);
                        }
                    }
                }
            }
            String whiteSpace = cssProps.Get(CssConstants.WHITE_SPACE);

            element.SetProperty(Property.NO_SOFT_WRAP_INLINE, CssConstants.NOWRAP.Equals(whiteSpace) || CssConstants.PRE
                                .Equals(whiteSpace));
            String textDecorationProp = cssProps.Get(CssConstants.TEXT_DECORATION);

            if (textDecorationProp != null)
            {
                String[]          textDecorations = iText.IO.Util.StringUtil.Split(textDecorationProp, "\\s+");
                IList <Underline> underlineList   = new List <Underline>();
                foreach (String textDecoration in textDecorations)
                {
                    if (CssConstants.BLINK.Equals(textDecoration))
                    {
                        logger.Error(iText.Html2pdf.LogMessageConstant.TEXT_DECORATION_BLINK_NOT_SUPPORTED);
                    }
                    else
                    {
                        if (CssConstants.LINE_THROUGH.Equals(textDecoration))
                        {
                            underlineList.Add(new Underline(null, .75f, 0, 0, 1 / 4f, PdfCanvasConstants.LineCapStyle.BUTT));
                        }
                        else
                        {
                            if (CssConstants.OVERLINE.Equals(textDecoration))
                            {
                                underlineList.Add(new Underline(null, .75f, 0, 0, 9 / 10f, PdfCanvasConstants.LineCapStyle.BUTT));
                            }
                            else
                            {
                                if (CssConstants.UNDERLINE.Equals(textDecoration))
                                {
                                    underlineList.Add(new Underline(null, .75f, 0, 0, -1 / 10f, PdfCanvasConstants.LineCapStyle.BUTT));
                                }
                                else
                                {
                                    if (CssConstants.NONE.Equals(textDecoration))
                                    {
                                        underlineList = null;
                                        // if none and any other decoration are used together, none is displayed
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                element.SetProperty(Property.UNDERLINE, underlineList);
            }
            String textIndent = cssProps.Get(CssConstants.TEXT_INDENT);

            if (textIndent != null)
            {
                UnitValue textIndentValue = CssUtils.ParseLengthValueToPt(textIndent, em, rem);
                if (textIndentValue != null)
                {
                    if (textIndentValue.IsPointValue())
                    {
                        element.SetProperty(Property.FIRST_LINE_INDENT, textIndentValue.GetValue());
                    }
                    else
                    {
                        logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.CSS_PROPERTY_IN_PERCENTS_NOT_SUPPORTED
                                                              , CssConstants.TEXT_INDENT));
                    }
                }
            }
            String letterSpacing = cssProps.Get(CssConstants.LETTER_SPACING);

            if (letterSpacing != null && !letterSpacing.Equals(CssConstants.NORMAL))
            {
                UnitValue letterSpacingValue = CssUtils.ParseLengthValueToPt(letterSpacing, em, rem);
                if (letterSpacingValue.IsPointValue())
                {
                    element.SetProperty(Property.CHARACTER_SPACING, letterSpacingValue.GetValue());
                }
            }
            // browsers ignore values in percents
            String wordSpacing = cssProps.Get(CssConstants.WORD_SPACING);

            if (wordSpacing != null)
            {
                UnitValue wordSpacingValue = CssUtils.ParseLengthValueToPt(wordSpacing, em, rem);
                if (wordSpacingValue != null)
                {
                    if (wordSpacingValue.IsPointValue())
                    {
                        element.SetProperty(Property.WORD_SPACING, wordSpacingValue.GetValue());
                    }
                }
            }
            // browsers ignore values in percents
            String lineHeight = cssProps.Get(CssConstants.LINE_HEIGHT);

            // specification does not give auto as a possible lineHeight value
            // nevertheless some browsers compute it as normal so we apply the same behaviour.
            // What's more, it's basically the same thing as if lineHeight is not set in the first place
            if (lineHeight != null && !CssConstants.NORMAL.Equals(lineHeight) && !CssConstants.AUTO.Equals(lineHeight)
                )
            {
                if (CssUtils.IsNumericValue(lineHeight))
                {
                    float?mult = CssUtils.ParseFloat(lineHeight);
                    if (mult != null)
                    {
                        element.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, (float)mult));
                    }
                }
                else
                {
                    UnitValue lineHeightValue = CssUtils.ParseLengthValueToPt(lineHeight, em, rem);
                    if (lineHeightValue != null && lineHeightValue.IsPointValue())
                    {
                        element.SetProperty(Property.LEADING, new Leading(Leading.FIXED, lineHeightValue.GetValue()));
                    }
                    else
                    {
                        if (lineHeightValue != null)
                        {
                            element.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, lineHeightValue.GetValue() / 100));
                        }
                    }
                }
            }
            else
            {
                element.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.2f));
            }
        }
Пример #29
0
        /// <summary>Applies paddings to an element.</summary>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="element">the element</param>
        /// <param name="baseValueHorizontal">value used by default for horizontal dimension</param>
        /// <param name="baseValueVertical">value used by default for vertical dimension</param>
        public static void ApplyPaddings(IDictionary <String, String> cssProps, ProcessorContext context, IPropertyContainer
                                         element, float baseValueVertical, float baseValueHorizontal)
        {
            String    paddingTop       = cssProps.Get(CssConstants.PADDING_TOP);
            String    paddingBottom    = cssProps.Get(CssConstants.PADDING_BOTTOM);
            String    paddingLeft      = cssProps.Get(CssConstants.PADDING_LEFT);
            String    paddingRight     = cssProps.Get(CssConstants.PADDING_RIGHT);
            float     em               = CssUtils.ParseAbsoluteLength(cssProps.Get(CssConstants.FONT_SIZE));
            float     rem              = context.GetCssContext().GetRootFontSize();
            UnitValue paddingTopVal    = CssUtils.ParseLengthValueToPt(paddingTop, em, rem);
            UnitValue paddingBottomVal = CssUtils.ParseLengthValueToPt(paddingBottom, em, rem);
            UnitValue paddingLeftVal   = CssUtils.ParseLengthValueToPt(paddingLeft, em, rem);
            UnitValue paddingRightVal  = CssUtils.ParseLengthValueToPt(paddingRight, em, rem);

            if (paddingTopVal != null)
            {
                if (paddingTopVal.IsPointValue())
                {
                    element.SetProperty(Property.PADDING_TOP, paddingTopVal);
                }
                else
                {
                    if (baseValueVertical != 0.0f)
                    {
                        element.SetProperty(Property.PADDING_TOP, new UnitValue(UnitValue.POINT, baseValueVertical * paddingTopVal
                                                                                .GetValue() * 0.01f));
                    }
                    else
                    {
                        logger.Error(iText.Html2pdf.LogMessageConstant.PADDING_VALUE_IN_PERCENT_NOT_SUPPORTED);
                    }
                }
            }
            if (paddingBottomVal != null)
            {
                if (paddingBottomVal.IsPointValue())
                {
                    element.SetProperty(Property.PADDING_BOTTOM, paddingBottomVal);
                }
                else
                {
                    if (baseValueVertical != 0.0f)
                    {
                        element.SetProperty(Property.PADDING_BOTTOM, new UnitValue(UnitValue.POINT, baseValueVertical * paddingBottomVal
                                                                                   .GetValue() * 0.01f));
                    }
                    else
                    {
                        logger.Error(iText.Html2pdf.LogMessageConstant.PADDING_VALUE_IN_PERCENT_NOT_SUPPORTED);
                    }
                }
            }
            if (paddingLeftVal != null)
            {
                if (paddingLeftVal.IsPointValue())
                {
                    element.SetProperty(Property.PADDING_LEFT, paddingLeftVal);
                }
                else
                {
                    if (baseValueHorizontal != 0.0f)
                    {
                        element.SetProperty(Property.PADDING_LEFT, new UnitValue(UnitValue.POINT, baseValueHorizontal * paddingLeftVal
                                                                                 .GetValue() * 0.01f));
                    }
                    else
                    {
                        logger.Error(iText.Html2pdf.LogMessageConstant.PADDING_VALUE_IN_PERCENT_NOT_SUPPORTED);
                    }
                }
            }
            if (paddingRightVal != null)
            {
                if (paddingRightVal.IsPointValue())
                {
                    element.SetProperty(Property.PADDING_RIGHT, paddingRightVal);
                }
                else
                {
                    if (baseValueHorizontal != 0.0f)
                    {
                        element.SetProperty(Property.PADDING_RIGHT, new UnitValue(UnitValue.POINT, baseValueHorizontal * paddingRightVal
                                                                                  .GetValue() * 0.01f));
                    }
                    else
                    {
                        logger.Error(iText.Html2pdf.LogMessageConstant.PADDING_VALUE_IN_PERCENT_NOT_SUPPORTED);
                    }
                }
            }
        }
        /// <summary>Applies a list style to an element.</summary>
        /// <param name="stylesContainer">the styles container</param>
        /// <param name="cssProps">the CSS properties</param>
        /// <param name="context">the processor context</param>
        /// <param name="element">the element</param>
        public static void ApplyListStyleTypeProperty(IStylesContainer stylesContainer, IDictionary <String, String
                                                                                                     > cssProps, ProcessorContext context, IPropertyContainer element)
        {
            float  em    = CssUtils.ParseAbsoluteLength(cssProps.Get(CssConstants.FONT_SIZE));
            String style = cssProps.Get(CssConstants.LIST_STYLE_TYPE);

            if (CssConstants.DISC.Equals(style))
            {
                SetDiscStyle(element, em);
            }
            else
            {
                if (CssConstants.CIRCLE.Equals(style))
                {
                    SetCircleStyle(element, em);
                }
                else
                {
                    if (CssConstants.SQUARE.Equals(style))
                    {
                        SetSquareStyle(element, em);
                    }
                    else
                    {
                        if (CssConstants.DECIMAL.Equals(style))
                        {
                            SetListSymbol(element, ListNumberingType.DECIMAL);
                        }
                        else
                        {
                            if (CssConstants.DECIMAL_LEADING_ZERO.Equals(style))
                            {
                                SetListSymbol(element, ListNumberingType.DECIMAL_LEADING_ZERO);
                            }
                            else
                            {
                                if (CssConstants.UPPER_ALPHA.Equals(style) || CssConstants.UPPER_LATIN.Equals(style))
                                {
                                    SetListSymbol(element, ListNumberingType.ENGLISH_UPPER);
                                }
                                else
                                {
                                    if (CssConstants.LOWER_ALPHA.Equals(style) || CssConstants.LOWER_LATIN.Equals(style))
                                    {
                                        SetListSymbol(element, ListNumberingType.ENGLISH_LOWER);
                                    }
                                    else
                                    {
                                        if (CssConstants.UPPER_ROMAN.Equals(style))
                                        {
                                            SetListSymbol(element, ListNumberingType.ROMAN_UPPER);
                                        }
                                        else
                                        {
                                            if (CssConstants.LOWER_ROMAN.Equals(style))
                                            {
                                                SetListSymbol(element, ListNumberingType.ROMAN_LOWER);
                                            }
                                            else
                                            {
                                                if (CssConstants.LOWER_GREEK.Equals(style))
                                                {
                                                    element.SetProperty(Property.LIST_SYMBOL, new ListStyleApplierUtil.HtmlAlphabetSymbolFactory(GREEK_LOWERCASE
                                                                                                                                                 ));
                                                }
                                                else
                                                {
                                                    if (CssConstants.NONE.Equals(style))
                                                    {
                                                        SetListSymbol(element, new Text(""));
                                                    }
                                                    else
                                                    {
                                                        if (style != null)
                                                        {
                                                            ILog logger = LogManager.GetLogger(typeof(iText.Html2pdf.Css.Apply.Util.ListStyleApplierUtil));
                                                            logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.NOT_SUPPORTED_LIST_STYLE_TYPE, style
                                                                                                  ));
                                                        }
                                                        // Fallback style
                                                        if (stylesContainer is IElementNode)
                                                        {
                                                            String elementName = ((IElementNode)stylesContainer).Name();
                                                            if (TagConstants.UL.Equals(elementName))
                                                            {
                                                                SetDiscStyle(element, em);
                                                            }
                                                            else
                                                            {
                                                                if (TagConstants.OL.Equals(elementName))
                                                                {
                                                                    SetListSymbol(element, ListNumberingType.DECIMAL);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }