Exemple #1
0
        private void Test(String fileName, String elementPath, params String[] expectedStyles)
        {
            String        filePath    = sourceFolder + fileName;
            IXmlParser    parser      = new JsoupHtmlParser();
            IDocumentNode document    = parser.Parse(new FileStream(filePath, FileMode.Open, FileAccess.Read), "UTF-8");
            ICssResolver  cssResolver = new DefaultCssResolver(document, MediaDeviceDescription.CreateDefault(), new ResourceResolver
                                                                   (""));
            CssContext context = new CssContext();

            ResolveStylesForTree(document, cssResolver, context);
            IElementNode element = FindElement(document, elementPath);

            if (element == null)
            {
                NUnit.Framework.Assert.Fail(MessageFormatUtil.Format("Element at path \"{0}\" was not found.", elementPath
                                                                     ));
            }
            IDictionary <String, String> elementStyles     = element.GetStyles();
            ICollection <String>         expectedStylesSet = new HashSet <String>(JavaUtil.ArraysAsList(expectedStyles));
            ICollection <String>         actualStylesSet   = StylesMapToHashSet(elementStyles);

            NUnit.Framework.Assert.IsTrue(SetsAreEqual(expectedStylesSet, actualStylesSet), GetDifferencesMessage(expectedStylesSet
                                                                                                                  , actualStylesSet));
        }
Exemple #2
0
 public override String ToString()
 {
     return(MessageFormatUtil.Format("PDF-{0}.{1}", major, minor));
 }
Exemple #3
0
 public virtual void ColorCheckTest1()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer             = new PdfWriter(new MemoryStream());
         Stream @is                   = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                            , @is);
         PdfADocument doc            = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
         float[] whitePoint          = new float[] { 0.9505f, 1f, 1.089f };
         float[] gamma               = new float[] { 2.2f, 2.2f, 2.2f };
         float[] matrix              = new float[] { 0.4124f, 0.2126f, 0.0193f, 0.3576f, 0.7152f, 0.1192f, 0.1805f, 0.0722f, 0.9505f };
         PdfCieBasedCs.CalRgb calRgb = new PdfCieBasedCs.CalRgb(whitePoint, null, gamma, matrix);
         PdfCanvas canvas            = new PdfCanvas(doc.AddNewPage());
         canvas.GetResources().SetDefaultCmyk(calRgb);
         canvas.SetFillColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f));
         canvas.MoveTo(doc.GetDefaultPageSize().GetLeft(), doc.GetDefaultPageSize().GetBottom());
         canvas.LineTo(doc.GetDefaultPageSize().GetRight(), doc.GetDefaultPageSize().GetBottom());
         canvas.LineTo(doc.GetDefaultPageSize().GetRight(), doc.GetDefaultPageSize().GetTop());
         canvas.Fill();
         doc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfAConformanceException.COLOR_SPACE_0_SHALL_HAVE_1_COMPONENTS, PdfName.DefaultCMYK.GetValue(), 4)))
     ;
 }
Exemple #4
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);
        }
        public virtual void ImageWithInvalidMaskTest()
        {
            ImageData mask = ImageDataFactory.Create(sourceFolder + "mask.png");

            NUnit.Framework.Assert.That(() => {
                mask.MakeMask();
            }
                                        , NUnit.Framework.Throws.InstanceOf <iText.IO.IOException>().With.Message.EqualTo(MessageFormatUtil.Format(iText.IO.IOException.ThisImageCanNotBeAnImageMask)))
            ;
        }
Exemple #6
0
        /// <exception cref="System.IO.IOException"/>
        private void InitializeFontProperties()
        {
            // initialize sfnt tables
            OpenTypeParser.HeaderTable      head = fontParser.GetHeadTable();
            OpenTypeParser.HorizontalHeader hhea = fontParser.GetHheaTable();
            OpenTypeParser.WindowsMetrics   os_2 = fontParser.GetOs_2Table();
            OpenTypeParser.PostTable        post = fontParser.GetPostTable();
            isFontSpecific = fontParser.GetCmapTable().fontSpecific;
            kerning        = fontParser.ReadKerning(head.unitsPerEm);
            bBoxes         = fontParser.ReadBbox(head.unitsPerEm);
            // font names group
            fontNames = fontParser.GetFontNames();
            // font metrics group
            fontMetrics.SetUnitsPerEm(head.unitsPerEm);
            fontMetrics.UpdateBbox(head.xMin, head.yMin, head.xMax, head.yMax);
            fontMetrics.SetNumberOfGlyphs(fontParser.ReadNumGlyphs());
            fontMetrics.SetGlyphWidths(fontParser.GetGlyphWidthsByIndex());
            fontMetrics.SetTypoAscender(os_2.sTypoAscender);
            fontMetrics.SetTypoDescender(os_2.sTypoDescender);
            fontMetrics.SetCapHeight(os_2.sCapHeight);
            fontMetrics.SetXHeight(os_2.sxHeight);
            fontMetrics.SetItalicAngle(post.italicAngle);
            fontMetrics.SetAscender(hhea.Ascender);
            fontMetrics.SetDescender(hhea.Descender);
            fontMetrics.SetLineGap(hhea.LineGap);
            fontMetrics.SetWinAscender(os_2.usWinAscent);
            fontMetrics.SetWinDescender(os_2.usWinDescent);
            fontMetrics.SetAdvanceWidthMax(hhea.advanceWidthMax);
            fontMetrics.SetUnderlinePosition((post.underlinePosition - post.underlineThickness) / 2);
            fontMetrics.SetUnderlineThickness(post.underlineThickness);
            fontMetrics.SetStrikeoutPosition(os_2.yStrikeoutPosition);
            fontMetrics.SetStrikeoutSize(os_2.yStrikeoutSize);
            fontMetrics.SetSubscriptOffset(-os_2.ySubscriptYOffset);
            fontMetrics.SetSubscriptSize(os_2.ySubscriptYSize);
            fontMetrics.SetSuperscriptOffset(os_2.ySuperscriptYOffset);
            fontMetrics.SetSuperscriptSize(os_2.ySuperscriptYSize);
            fontMetrics.SetIsFixedPitch(post.isFixedPitch);
            // font identification group
            String[][] ttfVersion = fontNames.GetNames(5);
            if (ttfVersion != null)
            {
                fontIdentification.SetTtfVersion(ttfVersion[0][3]);
            }
            String[][] ttfUniqueId = fontNames.GetNames(3);
            if (ttfUniqueId != null)
            {
                fontIdentification.SetTtfVersion(ttfUniqueId[0][3]);
            }
            byte[] pdfPanose = new byte[12];
            pdfPanose[1] = (byte)(os_2.sFamilyClass);
            pdfPanose[0] = (byte)(os_2.sFamilyClass >> 8);
            Array.Copy(os_2.panose, 0, pdfPanose, 2, 10);
            fontIdentification.SetPanose(pdfPanose);
            IDictionary <int, int[]> cmap = GetActiveCmap();

            int[] glyphWidths = fontParser.GetGlyphWidthsByIndex();
            int   numOfGlyphs = fontMetrics.GetNumberOfGlyphs();

            unicodeToGlyph = new LinkedDictionary <int, Glyph>(cmap.Count);
            codeToGlyph    = new LinkedDictionary <int, Glyph>(numOfGlyphs);
            avgWidth       = 0;
            foreach (int charCode in cmap.Keys)
            {
                int index = cmap.Get(charCode)[0];
                if (index >= numOfGlyphs)
                {
                    ILog LOGGER = LogManager.GetLogger(typeof(iText.IO.Font.TrueTypeFont));
                    LOGGER.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.FONT_HAS_INVALID_GLYPH, GetFontNames().GetFontName
                                                             (), index));
                    continue;
                }
                Glyph glyph = new Glyph(index, glyphWidths[index], charCode, bBoxes != null ? bBoxes[index] : null);
                unicodeToGlyph.Put(charCode, glyph);
                // This is done on purpose to keep the mapping to glyphs with smaller unicode values, in contrast with
                // larger values which often represent different forms of other characters.
                if (!codeToGlyph.ContainsKey(index))
                {
                    codeToGlyph.Put(index, glyph);
                }
                avgWidth += glyph.GetWidth();
            }
            FixSpaceIssue();
            for (int index = 0; index < glyphWidths.Length; index++)
            {
                if (codeToGlyph.ContainsKey(index))
                {
                    continue;
                }
                Glyph glyph = new Glyph(index, glyphWidths[index], -1);
                codeToGlyph.Put(index, glyph);
                avgWidth += glyph.GetWidth();
            }
            if (codeToGlyph.Count != 0)
            {
                avgWidth /= codeToGlyph.Count;
            }
            ReadGdefTable();
            ReadGsubTable();
            ReadGposTable();
            isVertical = false;
        }
 public virtual void EncryptedDocumentCustomFilterStandartTest()
 {
     NUnit.Framework.Assert.That(() => {
         PdfDocument doc = new PdfDocument(new PdfReader(sourceFolder + "customSecurityHandler.pdf"));
         doc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <UnsupportedSecurityHandlerException>().With.Message.EqualTo(MessageFormatUtil.Format(UnsupportedSecurityHandlerException.UnsupportedSecurityHandler, "/Standart")))
     ;
 }
        public override void AddChild(IRenderer renderer)
        {
            LayoutTaggingHelper taggingHelper = this.GetProperty <LayoutTaggingHelper>(Property.TAGGING_HELPER);

            if (taggingHelper != null)
            {
                LayoutTaggingHelper.AddTreeHints(taggingHelper, renderer);
            }
            // Some positioned renderers might have been fetched from non-positioned child and added to this renderer,
            // so we use this generic mechanism of determining which renderers have been just added.
            int numberOfChildRenderers           = childRenderers.Count;
            int numberOfPositionedChildRenderers = positionedRenderers.Count;

            base.AddChild(renderer);
            IList <IRenderer> addedRenderers           = new List <IRenderer>(1);
            IList <IRenderer> addedPositionedRenderers = new List <IRenderer>(1);

            while (childRenderers.Count > numberOfChildRenderers)
            {
                addedRenderers.Add(childRenderers[numberOfChildRenderers]);
                childRenderers.JRemoveAt(numberOfChildRenderers);
            }
            while (positionedRenderers.Count > numberOfPositionedChildRenderers)
            {
                addedPositionedRenderers.Add(positionedRenderers[numberOfPositionedChildRenderers]);
                positionedRenderers.JRemoveAt(numberOfPositionedChildRenderers);
            }
            bool marginsCollapsingEnabled = true.Equals(GetPropertyAsBoolean(Property.COLLAPSING_MARGINS));

            if (currentArea == null)
            {
                UpdateCurrentAndInitialArea(null);
                if (marginsCollapsingEnabled)
                {
                    marginsCollapseHandler = new MarginsCollapseHandler(this, null);
                }
            }
            // Static layout
            for (int i = 0; currentArea != null && i < addedRenderers.Count; i++)
            {
                renderer = addedRenderers[i];
                bool rendererIsFloat = FloatingHelper.IsRendererFloating(renderer);
                bool clearanceOverflowsToNextPage = FloatingHelper.IsClearanceApplied(waitingNextPageRenderers, renderer.GetProperty
                                                                                      <ClearPropertyValue?>(Property.CLEAR));
                if (rendererIsFloat && (floatOverflowedCompletely || clearanceOverflowsToNextPage))
                {
                    waitingNextPageRenderers.Add(renderer);
                    floatOverflowedCompletely = true;
                    continue;
                }
                ProcessWaitingKeepWithNextElement(renderer);
                IList <IRenderer>   resultRenderers  = new List <IRenderer>();
                LayoutResult        result           = null;
                RootLayoutArea      storedArea       = null;
                RootLayoutArea      nextStoredArea   = null;
                MarginsCollapseInfo childMarginsInfo = null;
                if (marginsCollapsingEnabled && currentArea != null && renderer != null)
                {
                    childMarginsInfo = marginsCollapseHandler.StartChildMarginsHandling(renderer, currentArea.GetBBox());
                }
                while (clearanceOverflowsToNextPage || currentArea != null && renderer != null && (result = renderer.SetParent
                                                                                                                (this).Layout(new LayoutContext(currentArea.Clone(), childMarginsInfo, floatRendererAreas))).GetStatus
                           () != LayoutResult.FULL)
                {
                    bool currentAreaNeedsToBeUpdated = false;
                    if (clearanceOverflowsToNextPage)
                    {
                        result = new LayoutResult(LayoutResult.NOTHING, null, null, renderer);
                        currentAreaNeedsToBeUpdated = true;
                    }
                    if (result.GetStatus() == LayoutResult.PARTIAL)
                    {
                        if (rendererIsFloat)
                        {
                            waitingNextPageRenderers.Add(result.GetOverflowRenderer());
                            break;
                        }
                        else
                        {
                            ProcessRenderer(result.GetSplitRenderer(), resultRenderers);
                            if (nextStoredArea != null)
                            {
                                currentArea       = nextStoredArea;
                                currentPageNumber = nextStoredArea.GetPageNumber();
                                nextStoredArea    = null;
                            }
                            else
                            {
                                currentAreaNeedsToBeUpdated = true;
                            }
                        }
                    }
                    else
                    {
                        if (result.GetStatus() == LayoutResult.NOTHING && !clearanceOverflowsToNextPage)
                        {
                            if (result.GetOverflowRenderer() is ImageRenderer)
                            {
                                float imgHeight = ((ImageRenderer)result.GetOverflowRenderer()).GetOccupiedArea().GetBBox().GetHeight();
                                if (!floatRendererAreas.IsEmpty() || currentArea.GetBBox().GetHeight() < imgHeight && !currentArea.IsEmptyArea
                                        ())
                                {
                                    if (rendererIsFloat)
                                    {
                                        waitingNextPageRenderers.Add(result.GetOverflowRenderer());
                                        floatOverflowedCompletely = true;
                                        break;
                                    }
                                    currentAreaNeedsToBeUpdated = true;
                                }
                                else
                                {
                                    ((ImageRenderer)result.GetOverflowRenderer()).AutoScale(currentArea);
                                    result.GetOverflowRenderer().SetProperty(Property.FORCED_PLACEMENT, true);
                                    ILog logger = LogManager.GetLogger(typeof(RootRenderer));
                                    logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, ""));
                                }
                            }
                            else
                            {
                                if (currentArea.IsEmptyArea() && result.GetAreaBreak() == null)
                                {
                                    if (true.Equals(result.GetOverflowRenderer().GetModelElement().GetProperty <bool?>(Property.KEEP_TOGETHER))
                                        )
                                    {
                                        result.GetOverflowRenderer().GetModelElement().SetProperty(Property.KEEP_TOGETHER, false);
                                        ILog logger = LogManager.GetLogger(typeof(RootRenderer));
                                        logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, "KeepTogether property will be ignored."
                                                                             ));
                                        if (storedArea != null)
                                        {
                                            nextStoredArea    = currentArea;
                                            currentArea       = storedArea;
                                            currentPageNumber = storedArea.GetPageNumber();
                                        }
                                        storedArea = currentArea;
                                    }
                                    else
                                    {
                                        if (null != result.GetCauseOfNothing() && true.Equals(result.GetCauseOfNothing().GetProperty <bool?>(Property
                                                                                                                                             .KEEP_TOGETHER)))
                                        {
                                            // set KEEP_TOGETHER false on the deepest parent (maybe the element itself) to have KEEP_TOGETHER == true
                                            IRenderer theDeepestKeptTogether = result.GetCauseOfNothing();
                                            IRenderer parent;
                                            while (null == theDeepestKeptTogether.GetModelElement() || null == theDeepestKeptTogether.GetModelElement(
                                                       ).GetOwnProperty <bool?>(Property.KEEP_TOGETHER))
                                            {
                                                parent = ((AbstractRenderer)theDeepestKeptTogether).parent;
                                                if (parent == null)
                                                {
                                                    break;
                                                }
                                                theDeepestKeptTogether = parent;
                                            }
                                            theDeepestKeptTogether.GetModelElement().SetProperty(Property.KEEP_TOGETHER, false);
                                            ILog logger = LogManager.GetLogger(typeof(RootRenderer));
                                            logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, "KeepTogether property of inner element will be ignored."
                                                                                 ));
                                        }
                                        else
                                        {
                                            if (!true.Equals(renderer.GetProperty <bool?>(Property.FORCED_PLACEMENT)))
                                            {
                                                result.GetOverflowRenderer().SetProperty(Property.FORCED_PLACEMENT, true);
                                                ILog logger = LogManager.GetLogger(typeof(RootRenderer));
                                                logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, ""));
                                            }
                                            else
                                            {
                                                // FORCED_PLACEMENT was already set to the renderer and
                                                // LogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA message was logged.
                                                // This else-clause should never be hit, otherwise there is a bug in FORCED_PLACEMENT implementation.
                                                System.Diagnostics.Debug.Assert(false);
                                                // Still handling this case in order to avoid nasty infinite loops.
                                                break;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    storedArea = currentArea;
                                    if (nextStoredArea != null)
                                    {
                                        currentArea       = nextStoredArea;
                                        currentPageNumber = nextStoredArea.GetPageNumber();
                                        nextStoredArea    = null;
                                    }
                                    else
                                    {
                                        if (rendererIsFloat)
                                        {
                                            waitingNextPageRenderers.Add(result.GetOverflowRenderer());
                                            floatOverflowedCompletely = true;
                                            break;
                                        }
                                        currentAreaNeedsToBeUpdated = true;
                                    }
                                }
                            }
                        }
                    }
                    renderer = result.GetOverflowRenderer();
                    if (marginsCollapsingEnabled)
                    {
                        marginsCollapseHandler.EndChildMarginsHandling(currentArea.GetBBox());
                    }
                    if (currentAreaNeedsToBeUpdated)
                    {
                        UpdateCurrentAndInitialArea(result);
                    }
                    if (marginsCollapsingEnabled)
                    {
                        marginsCollapseHandler = new MarginsCollapseHandler(this, null);
                        childMarginsInfo       = marginsCollapseHandler.StartChildMarginsHandling(renderer, currentArea.GetBBox());
                    }
                    clearanceOverflowsToNextPage = clearanceOverflowsToNextPage && FloatingHelper.IsClearanceApplied(waitingNextPageRenderers
                                                                                                                     , renderer.GetProperty <ClearPropertyValue?>(Property.CLEAR));
                }
                if (marginsCollapsingEnabled)
                {
                    marginsCollapseHandler.EndChildMarginsHandling(currentArea.GetBBox());
                }
                if (null != result && null != result.GetSplitRenderer())
                {
                    renderer = result.GetSplitRenderer();
                }
                // Keep renderer until next element is added for future keep with next adjustments
                if (renderer != null && result != null)
                {
                    if (true.Equals(renderer.GetProperty <bool?>(Property.KEEP_WITH_NEXT)))
                    {
                        if (true.Equals(renderer.GetProperty <bool?>(Property.FORCED_PLACEMENT)))
                        {
                            ILog logger = LogManager.GetLogger(typeof(RootRenderer));
                            logger.Warn(iText.IO.LogMessageConstant.ELEMENT_WAS_FORCE_PLACED_KEEP_WITH_NEXT_WILL_BE_IGNORED);
                            ShrinkCurrentAreaAndProcessRenderer(renderer, resultRenderers, result);
                        }
                        else
                        {
                            keepWithNextHangingRenderer             = renderer;
                            keepWithNextHangingRendererLayoutResult = result;
                        }
                    }
                    else
                    {
                        if (result.GetStatus() != LayoutResult.NOTHING)
                        {
                            ShrinkCurrentAreaAndProcessRenderer(renderer, resultRenderers, result);
                        }
                    }
                }
            }
            for (int i = 0; i < addedPositionedRenderers.Count; i++)
            {
                positionedRenderers.Add(addedPositionedRenderers[i]);
                renderer = positionedRenderers[positionedRenderers.Count - 1];
                int?positionedPageNumber = renderer.GetProperty <int?>(Property.PAGE_NUMBER);
                if (positionedPageNumber == null)
                {
                    positionedPageNumber = currentPageNumber;
                }
                LayoutArea layoutArea;
                // For position=absolute, if none of the top, bottom, left, right properties are provided,
                // the content should be displayed in the flow of the current content, not overlapping it.
                // The behavior is just if it would be statically positioned except it does not affect other elements
                if (Convert.ToInt32(LayoutPosition.ABSOLUTE).Equals(renderer.GetProperty <int?>(Property.POSITION)) && AbstractRenderer
                    .NoAbsolutePositionInfo(renderer))
                {
                    layoutArea = new LayoutArea((int)positionedPageNumber, currentArea.GetBBox().Clone());
                }
                else
                {
                    layoutArea = new LayoutArea((int)positionedPageNumber, initialCurrentArea.GetBBox().Clone());
                }
                Rectangle fullBbox = layoutArea.GetBBox().Clone();
                PreparePositionedRendererAndAreaForLayout(renderer, fullBbox, layoutArea.GetBBox());
                renderer.Layout(new PositionedLayoutContext(new LayoutArea(layoutArea.GetPageNumber(), fullBbox), layoutArea
                                                            ));
                if (immediateFlush)
                {
                    FlushSingleRenderer(renderer);
                    positionedRenderers.JRemoveAt(positionedRenderers.Count - 1);
                }
            }
        }
Exemple #9
0
        /* (non-Javadoc)
         * @see com.itextpdf.styledxmlparser.css.resolve.shorthand.IShorthandResolver#resolveShorthand(java.lang.String)
         */
        public virtual IList <CssDeclaration> ResolveShorthand(String shorthandExpression)
        {
            String[]   props      = iText.IO.Util.StringUtil.Split(shorthandExpression, "\\s*\\/\\s*");
            String[][] properties = new String[props.Length][];
            for (int i = 0; i < props.Length; i++)
            {
                properties[i] = iText.IO.Util.StringUtil.Split(props[i], "\\s+");
            }
            String[] resultExpressions = new String[4];
            for (int i = 0; i < resultExpressions.Length; i++)
            {
                resultExpressions[i] = "";
            }
            IList <CssDeclaration> resolvedDecl = new List <CssDeclaration>();
            String topLeftProperty     = MessageFormatUtil.Format(_0_TOP_LEFT_1, GetPrefix(), GetPostfix());
            String topRightProperty    = MessageFormatUtil.Format(_0_TOP_RIGHT_1, GetPrefix(), GetPostfix());
            String bottomRightProperty = MessageFormatUtil.Format(_0_BOTTOM_RIGHT_1, GetPrefix(), GetPostfix());
            String bottomLeftProperty  = MessageFormatUtil.Format(_0_BOTTOM_LEFT_1, GetPrefix(), GetPostfix());

            for (int i = 0; i < properties.Length; i++)
            {
                if (properties[i].Length == 1)
                {
                    resultExpressions[0] += properties[i][0] + " ";
                    resultExpressions[1] += properties[i][0] + " ";
                    resultExpressions[2] += properties[i][0] + " ";
                    resultExpressions[3] += properties[i][0] + " ";
                }
                else
                {
                    if (properties[i].Length == 2)
                    {
                        resultExpressions[0] += properties[i][0] + " ";
                        resultExpressions[1] += properties[i][1] + " ";
                        resultExpressions[2] += properties[i][0] + " ";
                        resultExpressions[3] += properties[i][1] + " ";
                    }
                    else
                    {
                        if (properties[i].Length == 3)
                        {
                            resultExpressions[0] += properties[i][0] + " ";
                            resultExpressions[1] += properties[i][1] + " ";
                            resultExpressions[2] += properties[i][2] + " ";
                            resultExpressions[3] += properties[i][1] + " ";
                        }
                        else
                        {
                            if (properties[i].Length == 4)
                            {
                                resultExpressions[0] += properties[i][0] + " ";
                                resultExpressions[1] += properties[i][1] + " ";
                                resultExpressions[2] += properties[i][2] + " ";
                                resultExpressions[3] += properties[i][3] + " ";
                            }
                        }
                    }
                }
            }
            resolvedDecl.Add(new CssDeclaration(topLeftProperty, resultExpressions[0]));
            resolvedDecl.Add(new CssDeclaration(topRightProperty, resultExpressions[1]));
            resolvedDecl.Add(new CssDeclaration(bottomRightProperty, resultExpressions[2]));
            resolvedDecl.Add(new CssDeclaration(bottomLeftProperty, resultExpressions[3]));
            return(resolvedDecl);
        }
Exemple #10
0
 /// <summary>Adds @font-face fonts to the FontProvider.</summary>
 /// <param name="cssResolver">the css styles resolver</param>
 public virtual void AddFontFaceFonts(ICssResolver cssResolver)
 {
     if (cssResolver is SvgStyleResolver)
     {
         foreach (CssFontFaceRule fontFace in ((SvgStyleResolver)cssResolver).GetFonts())
         {
             bool     findSupportedSrc = false;
             FontFace ff = FontFace.Create(fontFace.GetProperties());
             if (ff != null)
             {
                 foreach (FontFace.FontFaceSrc src in ff.GetSources())
                 {
                     if (CreateFont(ff.GetFontFamily(), src))
                     {
                         findSupportedSrc = true;
                         break;
                     }
                 }
             }
             if (!findSupportedSrc)
             {
                 LogManager.GetLogger(typeof(iText.Svg.Processors.Impl.Font.SvgFontProcessor)).Error(MessageFormatUtil.Format
                                                                                                         (iText.StyledXmlParser.LogMessageConstant.UNABLE_TO_RETRIEVE_FONT, fontFace));
             }
         }
     }
 }
Exemple #11
0
 public virtual void InvalidWidth()
 {
     NUnit.Framework.Assert.That(() => {
         ConvertAndCompare(SOURCE_FOLDER, DESTINATION_FOLDER, "invalidWidth");
     }
                                 , NUnit.Framework.Throws.InstanceOf <StyledXMLParserException>().With.Message.EqualTo(MessageFormatUtil.Format(StyledXMLParserException.NAN, "abc")))
     ;
 }
Exemple #12
0
        public virtual void PageGetMediaBoxNotEnoughArgumentsTest()
        {
            PdfReader   reader  = new PdfReader(sourceFolder + "helloWorldMediaboxNotEnoughArguments.pdf");
            PdfDocument pdfDoc  = new PdfDocument(reader);
            PdfPage     pageOne = pdfDoc.GetPage(1);

            NUnit.Framework.Assert.That(() => {
                pageOne.GetPageSize();
            }
                                        , NUnit.Framework.Throws.InstanceOf <PdfException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfException.WRONGMEDIABOXSIZETOOFEWARGUMENTS, 3)))
            ;
        }
 /// <summary>
 /// Creates a
 /// <see cref="TagWorkerInitializationException"/>
 /// instance.
 /// </summary>
 /// <param name="message">the message</param>
 /// <param name="classNames">the class names</param>
 /// <param name="tag">the tag</param>
 /// <param name="cause">the cause</param>
 public TagWorkerInitializationException(String message, String classNames, String tag, Exception cause)
     : base(MessageFormatUtil.Format(message, classNames, tag), cause)
 {
 }
Exemple #14
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));
            }
        }
Exemple #15
0
 public virtual PdfName ToPdfName()
 {
     return(new PdfName(MessageFormatUtil.Format("{0}.{1}", major, minor)));
 }
        /// <summary>Parses a length with an allowed metric unit (px, pt, in, cm, mm, pc, q) or numeric value (e.g.</summary>
        /// <remarks>
        /// Parses a length with an allowed metric unit (px, pt, in, cm, mm, pc, q) or numeric value (e.g. 123, 1.23,
        /// .123) to pt.<br />
        /// A numeric value (without px, pt, etc in the given length string) is considered to be in the default metric that
        /// was given.
        /// </remarks>
        /// <param name="length">the string containing the length.</param>
        /// <param name="defaultMetric">
        /// the string containing the metric if it is possible that the length string does not contain
        /// one. If null the length is considered to be in px as is default in HTML/CSS.
        /// </param>
        /// <returns>parsed value</returns>
        public static float ParseAbsoluteLength(String length, String defaultMetric)
        {
            int pos = DeterminePositionBetweenValueAndUnit(length);

            if (pos == 0)
            {
                if (length == null)
                {
                    length = "null";
                }
                throw new StyledXMLParserException(MessageFormatUtil.Format(iText.StyledXmlParser.LogMessageConstant.NAN,
                                                                            length));
            }
            float  f    = float.Parse(length.JSubstring(0, pos), System.Globalization.CultureInfo.InvariantCulture);
            String unit = length.Substring(pos);

            //points
            if (unit.StartsWith(CommonCssConstants.PT) || unit.Equals("") && defaultMetric.Equals(CommonCssConstants.PT
                                                                                                  ))
            {
                return(f);
            }
            // inches
            if (unit.StartsWith(CommonCssConstants.IN) || (unit.Equals("") && defaultMetric.Equals(CommonCssConstants.
                                                                                                   IN)))
            {
                return(f * 72f);
            }
            else
            {
                // centimeters
                if (unit.StartsWith(CommonCssConstants.CM) || (unit.Equals("") && defaultMetric.Equals(CommonCssConstants.
                                                                                                       CM)))
                {
                    return((f / 2.54f) * 72f);
                }
                else
                {
                    // quarter of a millimeter (1/40th of a centimeter).
                    if (unit.StartsWith(CommonCssConstants.Q) || (unit.Equals("") && defaultMetric.Equals(CommonCssConstants.Q
                                                                                                          )))
                    {
                        return((f / 2.54f) * 72f / 40);
                    }
                    else
                    {
                        // millimeters
                        if (unit.StartsWith(CommonCssConstants.MM) || (unit.Equals("") && defaultMetric.Equals(CommonCssConstants.
                                                                                                               MM)))
                        {
                            return((f / 25.4f) * 72f);
                        }
                        else
                        {
                            // picas
                            if (unit.StartsWith(CommonCssConstants.PC) || (unit.Equals("") && defaultMetric.Equals(CommonCssConstants.
                                                                                                                   PC)))
                            {
                                return(f * 12f);
                            }
                            else
                            {
                                // pixels (1px = 0.75pt).
                                if (unit.StartsWith(CommonCssConstants.PX) || (unit.Equals("") && defaultMetric.Equals(CommonCssConstants.
                                                                                                                       PX)))
                                {
                                    return(f * 0.75f);
                                }
                            }
                        }
                    }
                }
            }
            ILog logger = LogManager.GetLogger(typeof(iText.StyledXmlParser.Css.Util.CssUtils));

            logger.Error(MessageFormatUtil.Format(iText.StyledXmlParser.LogMessageConstant.UNKNOWN_ABSOLUTE_METRIC_LENGTH_PARSED
                                                  , unit.Equals("") ? defaultMetric : unit));
            return(f);
        }
Exemple #17
0
 public override String ToString()
 {
     return(MessageFormatUtil.Format("[id={0}, chars={1}, uni={2}, width={3}]", ToHex(code), chars != null ? iText.IO.Util.JavaUtil.ArraysToString
                                         (chars) : "null", ToHex(unicode), width));
 }
Exemple #18
0
 public virtual void ExceptionMessageTest()
 {
     NUnit.Framework.Assert.That(() => {
         FontProgramFactory.CreateFont(notExistingFont);
     }
                                 , NUnit.Framework.Throws.InstanceOf <System.IO.IOException>().With.Message.EqualTo(MessageFormatUtil.Format(iText.IO.IOException._1NotFoundAsFileOrResource, notExistingFont)))
     ;
 }
 public virtual void FontCheckPdfA1_02()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer = new PdfWriter(new MemoryStream());
         Stream @is       = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfDocument doc  = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", ""
                                                                                                        , "http://www.color.org", "sRGB IEC61966-2.1", @is));
         PdfPage page     = doc.AddNewPage();
         PdfFont font     = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi");
         PdfCanvas canvas = new PdfCanvas(page);
         canvas.SaveState().SetFillColor(ColorConstants.GREEN).BeginText().MoveText(36, 700).SetFontAndSize(font, 36
                                                                                                            ).ShowText("Hello World! Pdf/A-1B").EndText().RestoreState();
         doc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfAConformanceException.ALL_THE_FONTS_MUST_BE_EMBEDDED_THIS_ONE_IS_NOT_0, "FreeSans")))
     ;
 }
 public virtual void ImageTransparencyTest()
 {
     NUnit.Framework.Assert.That(() => {
         PdfDocument pdfDoc = new PdfADocument(new PdfWriter(new MemoryStream()), PdfAConformanceLevel.PDF_A_3B, null
                                               );
         PdfPage page     = pdfDoc.AddNewPage();
         PdfCanvas canvas = new PdfCanvas(page);
         page.GetResources().SetDefaultRgb(new PdfCieBasedCs.CalRgb(new float[] { 0.3f, 0.4f, 0.5f }));
         canvas.SaveState();
         canvas.AddImage(ImageDataFactory.Create(sourceFolder + "itext.png"), 0, 0, page.GetPageSize().GetWidth() /
                         2, false);
         canvas.RestoreState();
         pdfDoc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfAConformanceException.THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE)))
     ;
 }
Exemple #21
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);
        }
 public virtual void NestedXObjectWithTransparencyTest()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer        = new PdfWriter(new MemoryStream());
         PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, null);
         PdfFormXObject form1    = new PdfFormXObject(new Rectangle(0, 0, 50, 50));
         PdfCanvas canvas1       = new PdfCanvas(form1, pdfDocument);
         canvas1.SaveState();
         PdfExtGState state = new PdfExtGState();
         state.SetFillOpacity(0.6f);
         canvas1.SetExtGState(state);
         canvas1.Circle(25, 25, 10);
         canvas1.Fill();
         canvas1.RestoreState();
         canvas1.Release();
         form1.Flush();
         //Create form XObject and flush to document.
         PdfFormXObject form = new PdfFormXObject(new Rectangle(0, 0, 50, 50));
         PdfCanvas canvas    = new PdfCanvas(form, pdfDocument);
         canvas.Rectangle(10, 10, 30, 30);
         canvas.Stroke();
         canvas.AddXObject(form1, 0, 0);
         canvas.Release();
         form.Flush();
         //Create page1 and add forms to the page.
         PdfPage page1 = pdfDocument.AddNewPage();
         canvas        = new PdfCanvas(page1);
         canvas.AddXObject(form, 0, 0);
         canvas.Release();
         pdfDocument.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfAConformanceException.THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE)))
     ;
 }
Exemple #23
0
        // TODO may be use here TABLOID? based on w3c tests, ledger in html is interpreted as portrait-oriented page
        /// <summary>Fetch the page size.</summary>
        /// <param name="pageSizeStr">the name of the page size ("a4", "letter",...)</param>
        /// <param name="em">the em value</param>
        /// <param name="rem">the root em value</param>
        /// <param name="defaultPageSize">the default page size</param>
        /// <returns>the page size</returns>
        internal static PageSize FetchPageSize(String pageSizeStr, float em, float rem, PageSize defaultPageSize)
        {
            PageSize pageSize = (PageSize)defaultPageSize.Clone();

            if (pageSizeStr == null || CssConstants.AUTO.Equals(pageSizeStr))
            {
                return(pageSize);
            }
            String[] pageSizeChunks = iText.IO.Util.StringUtil.Split(pageSizeStr, " ");
            String   firstChunk     = pageSizeChunks[0];

            if (IsLengthValue(firstChunk))
            {
                PageSize pageSizeBasedOnLength = ParsePageLengthValue(pageSizeChunks, em, rem);
                if (pageSizeBasedOnLength != null)
                {
                    pageSize = pageSizeBasedOnLength;
                }
                else
                {
                    ILog logger = LogManager.GetLogger(typeof(PageSizeParser));
                    logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.PAGE_SIZE_VALUE_IS_INVALID, pageSizeStr
                                                          ));
                }
            }
            else
            {
                bool?    landscape     = null;
                PageSize namedPageSize = null;
                if (IsLandscapePortraitValue(firstChunk))
                {
                    landscape = CssConstants.LANDSCAPE.Equals(firstChunk);
                }
                else
                {
                    namedPageSize = pageSizeConstants.Get(firstChunk);
                }
                if (pageSizeChunks.Length > 1)
                {
                    String secondChunk = pageSizeChunks[1];
                    if (IsLandscapePortraitValue(secondChunk))
                    {
                        landscape = CssConstants.LANDSCAPE.Equals(secondChunk);
                    }
                    else
                    {
                        namedPageSize = pageSizeConstants.Get(secondChunk);
                    }
                }
                bool b1 = pageSizeChunks.Length == 1 && (namedPageSize != null || landscape != null);
                bool b2 = namedPageSize != null && landscape != null;
                if (b1 || b2)
                {
                    if (namedPageSize != null)
                    {
                        pageSize = namedPageSize;
                    }
                    if (true.Equals(landscape))
                    {
                        pageSize = pageSize.Rotate();
                    }
                }
                else
                {
                    ILog logger = LogManager.GetLogger(typeof(PageSizeParser));
                    logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.PAGE_SIZE_VALUE_IS_INVALID, pageSizeStr
                                                          ));
                }
            }
            return(pageSize);
        }
 public virtual void TextTransparencyNoOutputIntentTest()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer        = new PdfWriter(new MemoryStream());
         PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, null);
         PdfFont font            = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "Identity-H", true);
         PdfPage page1           = pdfDocument.AddNewPage();
         PdfCanvas canvas        = new PdfCanvas(page1);
         canvas.SaveState();
         canvas.BeginText().MoveText(36, 750).SetFontAndSize(font, 16).ShowText("Page 1 without transparency").EndText
             ().RestoreState();
         PdfPage page2 = pdfDocument.AddNewPage();
         canvas        = new PdfCanvas(page2);
         canvas.SaveState();
         PdfExtGState state = new PdfExtGState();
         state.SetFillOpacity(0.6f);
         canvas.SetExtGState(state);
         canvas.BeginText().MoveText(36, 750).SetFontAndSize(font, 16).ShowText("Page 2 with transparency").EndText
             ().RestoreState();
         pdfDocument.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfAConformanceException.THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE)))
     ;
 }
 /// <summary><inheritDoc/></summary>
 public override String ToString()
 {
     return(MessageFormatUtil.Format("{0}, page {1}", bBox.ToString(), pageNumber));
 }
Exemple #26
0
 private LayoutResult InitializeListSymbols(LayoutContext layoutContext)
 {
     if (!HasOwnProperty(Property.LIST_SYMBOLS_INITIALIZED))
     {
         IList <IRenderer> symbolRenderers = new List <IRenderer>();
         int listItemNum = (int)this.GetProperty <int?>(Property.LIST_START, 1);
         for (int i = 0; i < childRenderers.Count; i++)
         {
             childRenderers[i].SetParent(this);
             listItemNum = (childRenderers[i].GetProperty <int?>(Property.LIST_SYMBOL_ORDINAL_VALUE) != null) ? (int)childRenderers
                           [i].GetProperty <int?>(Property.LIST_SYMBOL_ORDINAL_VALUE) : listItemNum;
             IRenderer currentSymbolRenderer = MakeListSymbolRenderer(listItemNum, childRenderers[i]);
             if (BaseDirection.RIGHT_TO_LEFT.Equals(this.GetProperty <BaseDirection?>(Property.BASE_DIRECTION)))
             {
                 currentSymbolRenderer.SetProperty(Property.BASE_DIRECTION, BaseDirection.RIGHT_TO_LEFT);
             }
             LayoutResult listSymbolLayoutResult = null;
             if (currentSymbolRenderer != null)
             {
                 ++listItemNum;
                 currentSymbolRenderer.SetParent(childRenderers[i]);
                 listSymbolLayoutResult = currentSymbolRenderer.Layout(layoutContext);
                 currentSymbolRenderer.SetParent(null);
             }
             childRenderers[i].SetParent(null);
             bool isForcedPlacement = true.Equals(GetPropertyAsBoolean(Property.FORCED_PLACEMENT));
             bool listSymbolNotFit  = listSymbolLayoutResult != null && listSymbolLayoutResult.GetStatus() != LayoutResult
                                      .FULL;
             // TODO DEVSIX-1001: partially not fitting list symbol not shown at all, however this might be improved
             if (listSymbolNotFit && isForcedPlacement)
             {
                 currentSymbolRenderer = null;
             }
             symbolRenderers.Add(currentSymbolRenderer);
             if (listSymbolNotFit && !isForcedPlacement)
             {
                 return(new LayoutResult(LayoutResult.NOTHING, null, null, this, listSymbolLayoutResult.GetCauseOfNothing()
                                         ));
             }
         }
         float maxSymbolWidth = 0;
         for (int i = 0; i < childRenderers.Count; i++)
         {
             IRenderer symbolRenderer = symbolRenderers[i];
             if (symbolRenderer != null)
             {
                 IRenderer listItemRenderer = childRenderers[i];
                 if ((ListSymbolPosition)GetListItemOrListProperty(listItemRenderer, this, Property.LIST_SYMBOL_POSITION) !=
                     ListSymbolPosition.INSIDE)
                 {
                     maxSymbolWidth = Math.Max(maxSymbolWidth, symbolRenderer.GetOccupiedArea().GetBBox().GetWidth());
                 }
             }
         }
         float?symbolIndent = this.GetPropertyAsFloat(Property.LIST_SYMBOL_INDENT);
         listItemNum = 0;
         foreach (IRenderer childRenderer in childRenderers)
         {
             childRenderer.SetParent(this);
             childRenderer.DeleteOwnProperty(Property.MARGIN_LEFT);
             UnitValue marginLeftUV = childRenderer.GetProperty(Property.MARGIN_LEFT, UnitValue.CreatePointValue(0f));
             if (!marginLeftUV.IsPointValue())
             {
                 ILog logger = LogManager.GetLogger(typeof(iText.Layout.Renderer.ListRenderer));
                 logger.Error(MessageFormatUtil.Format(iText.IO.LogMessageConstant.PROPERTY_IN_PERCENTS_NOT_SUPPORTED, Property
                                                       .MARGIN_LEFT));
             }
             float calculatedMargin = marginLeftUV.GetValue();
             if ((ListSymbolPosition)GetListItemOrListProperty(childRenderer, this, Property.LIST_SYMBOL_POSITION) == ListSymbolPosition
                 .DEFAULT)
             {
                 calculatedMargin += maxSymbolWidth + (float)(symbolIndent != null ? symbolIndent : 0f);
             }
             childRenderer.SetProperty(Property.MARGIN_LEFT, UnitValue.CreatePointValue(calculatedMargin));
             IRenderer symbolRenderer = symbolRenderers[listItemNum++];
             ((ListItemRenderer)childRenderer).AddSymbolRenderer(symbolRenderer, maxSymbolWidth);
             if (symbolRenderer != null)
             {
                 LayoutTaggingHelper taggingHelper = this.GetProperty <LayoutTaggingHelper>(Property.TAGGING_HELPER);
                 if (taggingHelper != null)
                 {
                     if (symbolRenderer is LineRenderer)
                     {
                         taggingHelper.SetRoleHint(symbolRenderer.GetChildRenderers()[1], StandardRoles.LBL);
                     }
                     else
                     {
                         taggingHelper.SetRoleHint(symbolRenderer, StandardRoles.LBL);
                     }
                 }
             }
         }
     }
     return(null);
 }
 /* (non-Javadoc)
  * @see java.lang.Object#toString()
  */
 public override String ToString()
 {
     return(MessageFormatUtil.Format("{0}: {1}", property, expression));
 }
 public virtual void AnnotationCheckTest12()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());
         Stream @is       = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent("Custom", ""
                                                                                                        , "http://www.color.org", "sRGB IEC61966-2.1", @is));
         doc.SetTagged();
         doc.GetCatalog().SetLang(new PdfString("en-US"));
         PdfPage page        = doc.AddNewPage();
         Rectangle rect      = new Rectangle(100, 650, 400, 100);
         PdfAnnotation annot = new PdfStampAnnotation(rect);
         annot.SetFlags(PdfAnnotation.PRINT);
         page.AddAnnotation(annot);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(MessageFormatUtil.Format(PdfAConformanceException.ANNOTATION_OF_TYPE_0_SHOULD_HAVE_CONTENTS_KEY, PdfName.Stamp.GetValue())))
     ;
 }
        /// <exception cref="System.IO.IOException"/>
        private static void ReadPng(Stream pngStream, PngImageHelper.PngParameters png)
        {
            for (int i = 0; i < PNGID.Length; i++)
            {
                if (PNGID[i] != pngStream.Read())
                {
                    throw new System.IO.IOException("file.is.not.a.valid.png");
                }
            }
            byte[] buffer = new byte[TRANSFERSIZE];
            while (true)
            {
                int    len    = GetInt(pngStream);
                String marker = GetString(pngStream);
                if (len < 0 || !CheckMarker(marker))
                {
                    throw new System.IO.IOException("corrupted.png.file");
                }
                if (IDAT.Equals(marker))
                {
                    int size;
                    while (len != 0)
                    {
                        size = pngStream.JRead(buffer, 0, Math.Min(len, TRANSFERSIZE));
                        if (size < 0)
                        {
                            return;
                        }
                        png.idat.Write(buffer, 0, size);
                        len -= size;
                    }
                }
                else
                {
                    if (tRNS.Equals(marker))
                    {
                        switch (png.colorType)
                        {
                        case 0: {
                            if (len >= 2)
                            {
                                len -= 2;
                                int gray = GetWord(pngStream);
                                if (png.bitDepth == 16)
                                {
                                    png.transRedGray = gray;
                                }
                                else
                                {
                                    png.additional.Put("Mask", MessageFormatUtil.Format("[{0} {1}]", gray, gray));
                                }
                            }
                            break;
                        }

                        case 2: {
                            if (len >= 6)
                            {
                                len -= 6;
                                int red   = GetWord(pngStream);
                                int green = GetWord(pngStream);
                                int blue  = GetWord(pngStream);
                                if (png.bitDepth == 16)
                                {
                                    png.transRedGray = red;
                                    png.transGreen   = green;
                                    png.transBlue    = blue;
                                }
                                else
                                {
                                    png.additional.Put("Mask", MessageFormatUtil.Format("[{0} {1} {2} {3} {4} {5}]", red, red, green, green, blue
                                                                                        , blue));
                                }
                            }
                            break;
                        }

                        case 3: {
                            if (len > 0)
                            {
                                png.trans = new byte[len];
                                for (int k = 0; k < len; ++k)
                                {
                                    png.trans[k] = (byte)pngStream.Read();
                                }
                                len = 0;
                            }
                            break;
                        }
                        }
                        StreamUtil.Skip(pngStream, len);
                    }
                    else
                    {
                        if (IHDR.Equals(marker))
                        {
                            png.width             = GetInt(pngStream);
                            png.height            = GetInt(pngStream);
                            png.bitDepth          = pngStream.Read();
                            png.colorType         = pngStream.Read();
                            png.compressionMethod = pngStream.Read();
                            png.filterMethod      = pngStream.Read();
                            png.interlaceMethod   = pngStream.Read();
                        }
                        else
                        {
                            if (PLTE.Equals(marker))
                            {
                                if (png.colorType == 3)
                                {
                                    Object[] colorspace = new Object[4];
                                    colorspace[0] = "/Indexed";
                                    colorspace[1] = GetColorspace(png);
                                    colorspace[2] = len / 3 - 1;
                                    ByteBuffer colorTableBuf = new ByteBuffer();
                                    while ((len--) > 0)
                                    {
                                        colorTableBuf.Append(pngStream.Read());
                                    }
                                    png.colorTable = colorTableBuf.ToByteArray();
                                    colorspace[3]  = PdfEncodings.ConvertToString(png.colorTable, null);
                                    png.additional.Put("ColorSpace", colorspace);
                                }
                                else
                                {
                                    StreamUtil.Skip(pngStream, len);
                                }
                            }
                            else
                            {
                                if (pHYs.Equals(marker))
                                {
                                    int dx   = GetInt(pngStream);
                                    int dy   = GetInt(pngStream);
                                    int unit = pngStream.Read();
                                    if (unit == 1)
                                    {
                                        png.dpiX = (int)(dx * 0.0254f + 0.5f);
                                        png.dpiY = (int)(dy * 0.0254f + 0.5f);
                                    }
                                    else
                                    {
                                        if (dy != 0)
                                        {
                                            png.XYRatio = (float)dx / (float)dy;
                                        }
                                    }
                                }
                                else
                                {
                                    if (cHRM.Equals(marker))
                                    {
                                        png.xW      = GetInt(pngStream) / 100000f;
                                        png.yW      = GetInt(pngStream) / 100000f;
                                        png.xR      = GetInt(pngStream) / 100000f;
                                        png.yR      = GetInt(pngStream) / 100000f;
                                        png.xG      = GetInt(pngStream) / 100000f;
                                        png.yG      = GetInt(pngStream) / 100000f;
                                        png.xB      = GetInt(pngStream) / 100000f;
                                        png.yB      = GetInt(pngStream) / 100000f;
                                        png.hasCHRM = !(Math.Abs(png.xW) < 0.0001f || Math.Abs(png.yW) < 0.0001f || Math.Abs(png.xR) < 0.0001f ||
                                                        Math.Abs(png.yR) < 0.0001f || Math.Abs(png.xG) < 0.0001f || Math.Abs(png.yG) < 0.0001f || Math.Abs(png
                                                                                                                                                           .xB) < 0.0001f || Math.Abs(png.yB) < 0.0001f);
                                    }
                                    else
                                    {
                                        if (sRGB.Equals(marker))
                                        {
                                            int ri = pngStream.Read();
                                            png.intent  = intents[ri];
                                            png.gamma   = 2.2f;
                                            png.xW      = 0.3127f;
                                            png.yW      = 0.329f;
                                            png.xR      = 0.64f;
                                            png.yR      = 0.33f;
                                            png.xG      = 0.3f;
                                            png.yG      = 0.6f;
                                            png.xB      = 0.15f;
                                            png.yB      = 0.06f;
                                            png.hasCHRM = true;
                                        }
                                        else
                                        {
                                            if (gAMA.Equals(marker))
                                            {
                                                int gm = GetInt(pngStream);
                                                if (gm != 0)
                                                {
                                                    png.gamma = 100000f / gm;
                                                    if (!png.hasCHRM)
                                                    {
                                                        png.xW      = 0.3127f;
                                                        png.yW      = 0.329f;
                                                        png.xR      = 0.64f;
                                                        png.yR      = 0.33f;
                                                        png.xG      = 0.3f;
                                                        png.yG      = 0.6f;
                                                        png.xB      = 0.15f;
                                                        png.yB      = 0.06f;
                                                        png.hasCHRM = true;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (iCCP.Equals(marker))
                                                {
                                                    do
                                                    {
                                                        --len;
                                                    }while (pngStream.Read() != 0);
                                                    pngStream.Read();
                                                    --len;
                                                    byte[] icccom = new byte[len];
                                                    int    p      = 0;
                                                    while (len > 0)
                                                    {
                                                        int r = pngStream.JRead(icccom, p, len);
                                                        if (r < 0)
                                                        {
                                                            throw new System.IO.IOException("premature.end.of.file");
                                                        }
                                                        p   += r;
                                                        len -= r;
                                                    }
                                                    byte[] iccp = FilterUtil.FlateDecode(icccom, true);
                                                    icccom = null;
                                                    try {
                                                        png.iccProfile = IccProfile.GetInstance(iccp);
                                                    }
                                                    catch (Exception) {
                                                        png.iccProfile = null;
                                                    }
                                                }
                                                else
                                                {
                                                    if (IEND.Equals(marker))
                                                    {
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        StreamUtil.Skip(pngStream, len);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                StreamUtil.Skip(pngStream, 4);
            }
        }
 public virtual void ParseAbsoluteLengthFromNAN()
 {
     NUnit.Framework.Assert.That(() => {
         String value = "Definitely not a number";
         CssUtils.ParseAbsoluteLength(value);
     }
                                 , NUnit.Framework.Throws.InstanceOf <StyledXMLParserException>().With.Message.EqualTo(MessageFormatUtil.Format(StyledXMLParserException.NAN, "Definitely not a number")))
     ;
 }