Esempio n. 1
0
        internal static float?AdjustFloatedBlockLayoutBox(AbstractRenderer renderer, Rectangle parentBBox, float?
                                                          blockWidth, IList <Rectangle> floatRendererAreas, FloatPropertyValue?floatPropertyValue, OverflowPropertyValue?
                                                          overflowX)
        {
            renderer.SetProperty(Property.HORIZONTAL_ALIGNMENT, null);
            float floatElemWidth;
            bool  overflowFit = AbstractRenderer.IsOverflowFit(overflowX);

            if (blockWidth != null)
            {
                floatElemWidth = (float)blockWidth + AbstractRenderer.CalculateAdditionalWidth(renderer);
                if (overflowFit && floatElemWidth > parentBBox.GetWidth())
                {
                    floatElemWidth = parentBBox.GetWidth();
                }
            }
            else
            {
                MinMaxWidth minMaxWidth = CalculateMinMaxWidthForFloat(renderer, floatPropertyValue);
                float       maxWidth    = minMaxWidth.GetMaxWidth();
                if (maxWidth > parentBBox.GetWidth())
                {
                    maxWidth = parentBBox.GetWidth();
                }
                if (!overflowFit && minMaxWidth.GetMinWidth() > parentBBox.GetWidth())
                {
                    maxWidth = minMaxWidth.GetMinWidth();
                }
                floatElemWidth = maxWidth + AbstractRenderer.EPS;
                blockWidth     = maxWidth - minMaxWidth.GetAdditionalWidth() + AbstractRenderer.EPS;
            }
            AdjustBlockAreaAccordingToFloatRenderers(floatRendererAreas, parentBBox, floatElemWidth, FloatPropertyValue
                                                     .LEFT.Equals(floatPropertyValue));
            return(blockWidth);
        }
Esempio n. 2
0
        public virtual void MultipleDivTest()
        {
            String      outFileName = destinationFolder + "multipleDivTest01.pdf";
            String      cmpFileName = sourceFolder + "cmp_multipleDivTest01.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName));
            Document    doc         = new Document(pdfDocument);

            Border[] borders = new Border[] { new SolidBorder(ColorConstants.BLUE, 2f), new SolidBorder(ColorConstants
                                                                                                        .RED, 2f), new SolidBorder(ColorConstants.GREEN, 2f) };
            Div externalDiv = new Div().SetPadding(2f).SetBorder(borders[2]);
            Div curr        = externalDiv;

            for (int i = 0; i < 100; ++i)
            {
                Div d = new Div().SetBorder(borders[i % 3]);
                curr.Add(d);
                curr = d;
            }
            String    str = "Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me.";
            Paragraph p   = new Paragraph(new Text(str)).SetPadding(1f).SetBorder(new SolidBorder(ColorConstants.BLACK,
                                                                                                  2)).SetMargin(3).SetBackgroundColor(ColorConstants.LIGHT_GRAY);

            curr.Add(p);
            MinMaxWidth result = ((AbstractRenderer)externalDiv.CreateRendererSubTree().SetParent(doc.GetRenderer())).
                                 GetMinMaxWidth();

            externalDiv.SetWidth(ToEffectiveWidth(externalDiv, result.GetMinWidth()));
            doc.Add(externalDiv);
            doc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff"));
        }
Esempio n. 3
0
        public virtual void CalculateColumnWidthsNotPointValue()
        {
            PdfDocument pdfDoc    = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
            Document    doc       = new Document(pdfDoc);
            Rectangle   layoutBox = new Rectangle(0, 0, 1000, 100);
            Table       table     = new Table(UnitValue.CreatePercentArray(new float[] { 10, 10, 80 }));

            // Set margins and paddings in percents, which is not expected
            table.SetProperty(Property.MARGIN_RIGHT, UnitValue.CreatePercentValue(7));
            table.SetProperty(Property.MARGIN_LEFT, UnitValue.CreatePercentValue(7));
            table.SetProperty(Property.PADDING_RIGHT, UnitValue.CreatePercentValue(7));
            table.SetProperty(Property.PADDING_LEFT, UnitValue.CreatePercentValue(7));
            // Fill the table somehow. The layout area is wide enough to calculate the widths as expected
            for (int i = 0; i < 3; i++)
            {
                table.AddCell("Hello");
            }
            // Create a TableRenderer, the instance of which will be used to test the application of margins and paddings
            TableRenderer tableRenderer = (TableRenderer)table.CreateRendererSubTree().SetParent(doc.GetRenderer());

            tableRenderer.bordersHandler = (TableBorders) new SeparatedTableBorders(tableRenderer.rows, 3, tableRenderer
                                                                                    .GetBorders(), 0);
            tableRenderer.ApplyMarginsAndPaddingsAndCalculateColumnWidths(layoutBox);
            // Specify that the render is not original in order not to recalculate the column widths
            tableRenderer.isOriginalNonSplitRenderer = false;
            MinMaxWidth minMaxWidth = tableRenderer.GetMinMaxWidth();

            // TODO DEVSIX-3676: currently margins and paddings are still applied as if they are in points. After the mentioned ticket is fixed, the expected values should be updated.
            NUnit.Framework.Assert.AreEqual(minMaxWidth.GetMaxWidth(), 332.46f, 0.001);
            NUnit.Framework.Assert.AreEqual(minMaxWidth.GetMinWidth(), 332.46f, 0.001);
        }
Esempio n. 4
0
        public virtual void ImageWidthTest02()
        {
            PdfImageXObject xObject = new PdfImageXObject(ImageDataFactory.Create(imageFolder + "Desert.jpg"));

            iText.Layout.Element.Image image = new iText.Layout.Element.Image(xObject);
            ImageRenderer renderer           = new ImageRenderer(image);

            image.SetProperty(Property.MAX_WIDTH, UnitValue.CreatePointValue(50));
            MinMaxWidth minMaxWidth = renderer.GetMinMaxWidth();

            NUnit.Framework.Assert.AreEqual(50.0, minMaxWidth.GetMaxWidth(), EPSILON);
            NUnit.Framework.Assert.AreEqual(0.0, minMaxWidth.GetMaxWidth() - minMaxWidth.GetMinWidth(), EPSILON);
            image.SetProperty(Property.MAX_WIDTH, UnitValue.CreatePercentValue(50));
            minMaxWidth = renderer.GetMinMaxWidth();
            NUnit.Framework.Assert.AreEqual(1024.0, minMaxWidth.GetMaxWidth(), EPSILON);
            image.SetProperty(Property.MAX_HEIGHT, UnitValue.CreatePointValue(100f));
            minMaxWidth = renderer.GetMinMaxWidth();
            NUnit.Framework.Assert.AreEqual(100.0 * 1024.0 / 768.0, minMaxWidth.GetMaxWidth(), EPSILON);
            image    = new iText.Layout.Element.Image(xObject);
            renderer = new ImageRenderer(image);
            image.SetProperty(Property.MIN_WIDTH, UnitValue.CreatePointValue(2000));
            image.SetProperty(Property.MAX_WIDTH, UnitValue.CreatePointValue(3000));
            minMaxWidth = renderer.GetMinMaxWidth();
            NUnit.Framework.Assert.AreEqual(2000.0, minMaxWidth.GetMaxWidth(), EPSILON);
            NUnit.Framework.Assert.AreEqual(0.0, minMaxWidth.GetMaxWidth() - minMaxWidth.GetMinWidth(), EPSILON);
            image.SetProperty(Property.MIN_HEIGHT, UnitValue.CreatePointValue(100f));
            image.SetProperty(Property.HEIGHT, UnitValue.CreatePointValue(100f));
            minMaxWidth = renderer.GetMinMaxWidth();
            NUnit.Framework.Assert.AreEqual(100.0 * 1024.0 / 768.0, minMaxWidth.GetMaxWidth(), EPSILON);
        }
        public WidthDimensionContainer(CssContextNode node, float maxWidth, IRenderer renderer, float additionalWidthFix
                                       )
        {
            String width = node.GetStyles().Get(CssConstants.WIDTH);

            if (width != null && !CssConstants.AUTO.Equals(width))
            {
                dimension = ParseDimension(node, width, maxWidth, additionalWidthFix);
            }
            minDimension = GetMinWidth(node, maxWidth, additionalWidthFix);
            maxDimension = GetMaxWidth(node, maxWidth, additionalWidthFix);
            if (!IsAutoDimension())
            {
                // According to point 3 of paragraph "5.3.2.3. Handling min-width and max-width" of the specification
                // maxContentDimension and minContentDimension will always be equal
                maxContentDimension = dimension;
                minContentDimension = dimension;
            }
            else
            {
                if (renderer is BlockRenderer)
                {
                    MinMaxWidth minMaxWidth = ((BlockRenderer)renderer).GetMinMaxWidth();
                    maxContentDimension = minMaxWidth.GetMaxWidth();
                    minContentDimension = minMaxWidth.GetMinWidth();
                }
            }
        }
        protected override bool SetMinMaxWidthBasedOnFixedWidth(MinMaxWidth minMaxWidth)
        {
            bool result = false;

            if (HasRelativeUnitValue(Property.WIDTH))
            {
                UnitValue widthUV      = this.GetProperty <UnitValue>(Property.WIDTH);
                bool      restoreWidth = HasOwnProperty(Property.WIDTH);
                SetProperty(Property.WIDTH, null);
                float?width = RetrieveWidth(0);
                if (width != null)
                {
                    // the field can be shrinked if necessary so only max width is set here
                    minMaxWidth.SetChildrenMaxWidth((float)width);
                    result = true;
                }
                if (restoreWidth)
                {
                    SetProperty(Property.WIDTH, widthUV);
                }
                else
                {
                    DeleteOwnProperty(Property.WIDTH);
                }
            }
            else
            {
                result = base.SetMinMaxWidthBasedOnFixedWidth(minMaxWidth);
            }
            return(result);
        }
Esempio n. 7
0
        public virtual void DivWithRotatedPercentImage()
        {
            String          outFileName  = destinationFolder + "divRotatedPercentImage.pdf";
            String          cmpFileName  = sourceFolder + "cmp_divRotatedPercentImage.pdf";
            PdfDocument     pdfDocument  = new PdfDocument(new PdfWriter(outFileName));
            Document        doc          = new Document(pdfDocument);
            PdfImageXObject imageXObject = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "itis.jpg"));

            iText.Layout.Element.Image img = new iText.Layout.Element.Image(imageXObject).SetRotationAngle(Math.PI * 3
                                                                                                           / 8);
            Div d = new Div().Add(img).SetBorder(new SolidBorder(ColorConstants.BLUE, 2f)).SetMarginBottom(10);

            iText.Layout.Element.Image imgPercent = new iText.Layout.Element.Image(imageXObject).SetWidth(UnitValue.CreatePercentValue
                                                                                                              (50)).SetRotationAngle(Math.PI * 3 / 8);
            Div         dPercent = new Div().Add(imgPercent).SetBorder(new SolidBorder(ColorConstants.BLUE, 2f));
            MinMaxWidth result   = ((AbstractRenderer)d.CreateRendererSubTree().SetParent(doc.GetRenderer())).GetMinMaxWidth
                                       ();

            d.SetWidth(ToEffectiveWidth(d, result.GetMinWidth()));
            MinMaxWidth resultPercent = ((AbstractRenderer)dPercent.CreateRendererSubTree().SetParent(doc.GetRenderer(
                                                                                                          ))).GetMinMaxWidth();

            dPercent.SetWidth(ToEffectiveWidth(dPercent, resultPercent.GetMaxWidth()));
            doc.Add(d);
            doc.Add(dPercent);
            doc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff"));
        }
Esempio n. 8
0
        public WidthDimensionContainer(CssContextNode node, float maxWidth, IRenderer renderer, float additionalWidthFix
                                       )
        {
            String width = node.GetStyles().Get(CssConstants.WIDTH);

            if (width != null && !width.Equals(CssConstants.AUTO))
            {
                dimension = ParseDimension(node, width, maxWidth, additionalWidthFix);
            }
            minDimension = GetMinWidth(node, maxWidth, additionalWidthFix);
            maxDimension = GetMaxWidth(node, maxWidth, additionalWidthFix);
            if (!IsAutoDimension())
            {
                maxContentDimension = dimension;
                maxContentDimension = dimension;
            }
            else
            {
                if (renderer is BlockRenderer)
                {
                    MinMaxWidth minMaxWidth = ((BlockRenderer)renderer).GetMinMaxWidth();
                    maxContentDimension = minMaxWidth.GetMaxWidth();
                    minContentDimension = minMaxWidth.GetMinWidth();
                }
            }
        }
 public virtual void UpdateMinMaxWidth(MinMaxWidth minMaxWidth)
 {
     if (minMaxWidth != null)
     {
         UpdateMaxChildWidth(minMaxWidth.GetMaxWidth());
         UpdateMinChildWidth(minMaxWidth.GetMinWidth());
     }
 }
Esempio n. 10
0
        /* (non-Javadoc)
         * @see com.itextpdf.layout.renderer.BlockRenderer#getMinMaxWidth(float)
         */
        public override MinMaxWidth GetMinMaxWidth()
        {
            childRenderers.Clear();
            flatRenderer = null;
            IRenderer renderer = CreateFlatRenderer();

            AddChild(renderer);
            MinMaxWidth minMaxWidth = base.GetMinMaxWidth();

            return(minMaxWidth);
        }
Esempio n. 11
0
        public override MinMaxWidth GetMinMaxWidth()
        {
            IList <IRenderer> realChildRenderers = childRenderers;

            childRenderers = new List <IRenderer>();
            childRenderers.Add(minMaxWidthRenderer);
            MinMaxWidth minMaxWidth = base.GetMinMaxWidth();

            childRenderers = realChildRenderers;
            return(minMaxWidth);
        }
Esempio n. 12
0
        /// <summary>
        /// This method tries to calculate min-max-width of rotated element using heuristics
        /// of
        /// <see cref="iText.Layout.Minmaxwidth.RotationMinMaxWidth.Calculate(double, double, iText.Layout.Minmaxwidth.MinMaxWidth)
        ///     "/>.
        /// </summary>
        /// <remarks>
        /// This method tries to calculate min-max-width of rotated element using heuristics
        /// of
        /// <see cref="iText.Layout.Minmaxwidth.RotationMinMaxWidth.Calculate(double, double, iText.Layout.Minmaxwidth.MinMaxWidth)
        ///     "/>.
        /// This method may call
        /// <see cref="IRenderer.Layout(iText.Layout.Layout.LayoutContext)"/>
        /// once in best case
        /// (if the width is set on element, or if we are really lucky) and three times in worst case.
        /// </remarks>
        /// <param name="minMaxWidth">the minMaxWidth of NOT rotated renderer</param>
        /// <param name="renderer">the actual renderer</param>
        /// <returns>minMaxWidth of rotated renderer or original value in case rotated value can not be calculated, or renderer isn't rotated.
        ///     </returns>
        public static MinMaxWidth CountRotationMinMaxWidth(MinMaxWidth minMaxWidth, AbstractRenderer renderer)
        {
            RotationUtils.PropertiesBackup backup = new RotationUtils.PropertiesBackup(renderer);
            float?rotation = backup.StoreFloatProperty(Property.ROTATION_ANGLE);

            if (rotation != null)
            {
                float angle = (float)rotation;
                //This width results in more accurate values for min-width calculations.
                float        layoutWidth  = minMaxWidth.GetMaxWidth() + MinMaxWidthUtils.GetEps();
                LayoutResult layoutResult = renderer.Layout(new LayoutContext(new LayoutArea(1, new Rectangle(layoutWidth,
                                                                                                              AbstractRenderer.INF))));
                if (layoutResult.GetOccupiedArea() != null)
                {
                    Rectangle layoutBBox = layoutResult.GetOccupiedArea().GetBBox();
                    if (MinMaxWidthUtils.IsEqual(minMaxWidth.GetMinWidth(), minMaxWidth.GetMaxWidth()))
                    {
                        backup.RestoreProperty(Property.ROTATION_ANGLE);
                        float rotatedWidth = (float)RotationMinMaxWidth.CalculateRotatedWidth(layoutBBox, angle);
                        return(new MinMaxWidth(rotatedWidth, rotatedWidth, 0));
                    }
                    double area = layoutResult.GetOccupiedArea().GetBBox().GetWidth() * layoutResult.GetOccupiedArea().GetBBox
                                      ().GetHeight();
                    RotationMinMaxWidth rotationMinMaxWidth = RotationMinMaxWidth.Calculate(angle, area, minMaxWidth);
                    float?rotatedMinWidth = GetLayoutRotatedWidth(renderer, (float)rotationMinMaxWidth.GetMinWidthOrigin(), layoutBBox
                                                                  , angle);
                    if (rotatedMinWidth != null)
                    {
                        if (rotatedMinWidth > rotationMinMaxWidth.GetMaxWidth())
                        {
                            rotationMinMaxWidth.SetChildrenMinWidth((float)rotatedMinWidth);
                            float?rotatedMaxWidth = GetLayoutRotatedWidth(renderer, (float)rotationMinMaxWidth.GetMaxWidthOrigin(), layoutBBox
                                                                          , angle);
                            if (rotatedMaxWidth != null && rotatedMaxWidth > rotatedMinWidth)
                            {
                                rotationMinMaxWidth.SetChildrenMaxWidth((float)rotatedMaxWidth);
                            }
                            else
                            {
                                rotationMinMaxWidth.SetChildrenMaxWidth((float)rotatedMinWidth);
                            }
                        }
                        else
                        {
                            rotationMinMaxWidth.SetChildrenMinWidth((float)rotatedMinWidth);
                        }
                        backup.RestoreProperty(Property.ROTATION_ANGLE);
                        return(rotationMinMaxWidth);
                    }
                }
            }
            backup.RestoreProperty(Property.ROTATION_ANGLE);
            return(minMaxWidth);
        }
        public virtual void MinMaxWidthWithOneRenderer()
        {
            PdfDocument  pdfDocument  = new PdfDocument(new PdfWriter(new MemoryStream()));
            Document     document     = new Document(pdfDocument);
            TextRenderer textRenderer = new TextRenderer(new Text(""));

            textRenderer.SetParent(document.GetRenderer());
            textRenderer.SetProperty(Property.FONT, PdfFontFactory.CreateFont(THAI_FONT, PdfEncodings.IDENTITY_H));
            textRenderer.SetText(THAI_TEXT);
            textRenderer.SetSpecialScriptsWordBreakPoints(new List <int>(JavaUtil.ArraysAsList(3, 8, 10, 12, 15, 20, 23
                                                                                               , 26, 28, 30, 36)));
            MinMaxWidth minMaxWidth = textRenderer.GetMinMaxWidth();

            NUnit.Framework.Assert.IsTrue(minMaxWidth.GetMinWidth() < minMaxWidth.GetMaxWidth());
        }
        public virtual void OverflowWrapAnywhereProperty()
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new MemoryStream()));

            pdfDoc.AddNewPage();
            Document     doc = new Document(pdfDoc);
            RootRenderer documentRenderer = doc.GetRenderer();
            Text         text             = new Text("wow");

            text.SetProperty(Property.OVERFLOW_WRAP, OverflowWrapPropertyValue.ANYWHERE);
            TextRenderer textRenderer = (TextRenderer)text.GetRenderer();

            textRenderer.SetParent(documentRenderer);
            MinMaxWidth minMaxWidth = textRenderer.GetMinMaxWidth();

            NUnit.Framework.Assert.IsTrue(minMaxWidth.GetMinWidth() < minMaxWidth.GetMaxWidth());
        }
        public virtual void SpecialScriptsWordBreakPointsSplit()
        {
            PdfDocument  pdfDocument  = new PdfDocument(new PdfWriter(new MemoryStream()));
            Document     document     = new Document(pdfDocument);
            TextRenderer textRenderer = new TextRenderer(new Text(""));

            textRenderer.SetProperty(Property.FONT, PdfFontFactory.CreateFont(THAI_FONT, PdfEncodings.IDENTITY_H));
            textRenderer.SetText(THAI_TEXT);
            textRenderer.SetSpecialScriptsWordBreakPoints(new List <int>(JavaUtil.ArraysAsList(3, 8, 10, 12, 15, 20, 23
                                                                                               , 26, 28, 30, 36)));
            LineRenderer lineRenderer = new LineRenderer();

            lineRenderer.SetParent(document.GetRenderer());
            lineRenderer.AddChild(textRenderer);
            MinMaxWidth  minMaxWidth  = lineRenderer.GetMinMaxWidth();
            float        width        = minMaxWidth.GetMinWidth() + minMaxWidth.GetMaxWidth() / 2;
            LayoutResult layoutResult = lineRenderer.Layout(new LayoutContext(new LayoutArea(1, new Rectangle(width, 500
                                                                                                              ))));
            IRenderer lineSplitRenderer = layoutResult.GetSplitRenderer();

            NUnit.Framework.Assert.IsNotNull(lineSplitRenderer);
            NUnit.Framework.Assert.IsNotNull(lineSplitRenderer.GetChildRenderers());
            NUnit.Framework.Assert.IsTrue(lineSplitRenderer.GetChildRenderers()[0] is TextRenderer);
            TextRenderer textSplitRenderer = (TextRenderer)lineSplitRenderer.GetChildRenderers()[0];

            NUnit.Framework.Assert.IsNotNull(textSplitRenderer.GetSpecialScriptsWordBreakPoints());
            IRenderer lineOverflowRenderer = layoutResult.GetOverflowRenderer();

            NUnit.Framework.Assert.IsNotNull(lineOverflowRenderer);
            NUnit.Framework.Assert.IsNotNull(lineOverflowRenderer.GetChildRenderers());
            NUnit.Framework.Assert.IsTrue(lineOverflowRenderer.GetChildRenderers()[0] is TextRenderer);
            TextRenderer textOverflowRenderer = (TextRenderer)lineOverflowRenderer.GetChildRenderers()[0];

            NUnit.Framework.Assert.IsNotNull(textOverflowRenderer.GetSpecialScriptsWordBreakPoints());
            int textSplitRendererTextLength = textSplitRenderer.text.ToString().Length;

            foreach (int specialScriptsWordBreakPoint in textSplitRenderer.GetSpecialScriptsWordBreakPoints())
            {
                NUnit.Framework.Assert.IsTrue(specialScriptsWordBreakPoint <= textSplitRendererTextLength);
            }
            foreach (int specialScriptsWordBreakPoint in textOverflowRenderer.GetSpecialScriptsWordBreakPoints())
            {
                NUnit.Framework.Assert.IsTrue(specialScriptsWordBreakPoint > textSplitRendererTextLength && specialScriptsWordBreakPoint
                                              <= textOverflowRenderer.text.Size());
            }
        }
Esempio n. 16
0
        /// <summary>This method tries to calculate width of not rotated renderer, so after rotation it fits availableWidth.
        ///     </summary>
        /// <remarks>
        /// This method tries to calculate width of not rotated renderer, so after rotation it fits availableWidth.
        /// This method uses heuristics of
        /// <see cref="iText.Layout.Minmaxwidth.RotationMinMaxWidth.Calculate(double, double, iText.Layout.Minmaxwidth.MinMaxWidth, double)
        ///     "/>.
        /// It doesn't take into account any of height properties of renderer or height of layoutArea.
        /// The minMaxWidth calculations and initial layout may take long time, but they won't be called if the renderer have width property.
        /// </remarks>
        /// <param name="availableWidth">the width of layoutArea</param>
        /// <param name="renderer">the actual renderer</param>
        /// <returns>
        /// the width that should be set as width of layout area to properly layout element, or fallback to
        /// <see cref="AbstractRenderer.RetrieveWidth(float)"/>
        /// in case it can not be calculated, or renderer isn't rotated.
        /// </returns>
        public static float?RetrieveRotatedLayoutWidth(float availableWidth, AbstractRenderer renderer)
        {
            RotationUtils.PropertiesBackup backup = new RotationUtils.PropertiesBackup(renderer);
            float?rotation = backup.StoreFloatProperty(Property.ROTATION_ANGLE);

            if (rotation != null && renderer.GetProperty <UnitValue>(Property.WIDTH) == null)
            {
                float angle = (float)rotation;
                backup.StoreProperty <UnitValue>(Property.HEIGHT);
                backup.StoreProperty <UnitValue>(Property.MIN_HEIGHT);
                backup.StoreProperty <UnitValue>(Property.MAX_HEIGHT);
                MinMaxWidth minMaxWidth = renderer.GetMinMaxWidth();
                //Using this width for initial layout helps in case of small elements. They may have more free spaces but it's more likely they fit.
                float        length       = (minMaxWidth.GetMaxWidth() + minMaxWidth.GetMinWidth()) / 2 + MinMaxWidthUtils.GetEps();
                LayoutResult layoutResult = renderer.Layout(new LayoutContext(new LayoutArea(1, new Rectangle(length, AbstractRenderer
                                                                                                              .INF))));
                backup.RestoreProperty(Property.HEIGHT);
                backup.RestoreProperty(Property.MIN_HEIGHT);
                backup.RestoreProperty(Property.MAX_HEIGHT);
                Rectangle additions = new Rectangle(0, 0);
                renderer.ApplyPaddings(additions, true);
                renderer.ApplyBorderBox(additions, true);
                renderer.ApplyMargins(additions, true);
                if (layoutResult.GetOccupiedArea() != null)
                {
                    double area = layoutResult.GetOccupiedArea().GetBBox().GetWidth() * layoutResult.GetOccupiedArea().GetBBox
                                      ().GetHeight();
                    RotationMinMaxWidth result = RotationMinMaxWidth.Calculate(angle, area, minMaxWidth, availableWidth);
                    if (result != null)
                    {
                        backup.RestoreProperty(Property.ROTATION_ANGLE);
                        if (result.GetMaxWidthHeight() > result.GetMinWidthHeight())
                        {
                            return((float)(result.GetMinWidthOrigin() - additions.GetWidth() + MinMaxWidthUtils.GetEps()));
                        }
                        else
                        {
                            return((float)(result.GetMaxWidthOrigin() - additions.GetWidth() + MinMaxWidthUtils.GetEps()));
                        }
                    }
                }
            }
            backup.RestoreProperty(Property.ROTATION_ANGLE);
            return(renderer.RetrieveWidth(availableWidth));
        }
Esempio n. 17
0
        internal static MinMaxWidth CalculateMinMaxWidthForFloat(AbstractRenderer renderer, FloatPropertyValue?floatPropertyVal
                                                                 )
        {
            bool floatPropIsRendererOwn = renderer.HasOwnProperty(Property.FLOAT);

            renderer.SetProperty(Property.FLOAT, FloatPropertyValue.NONE);
            MinMaxWidth kidMinMaxWidth = renderer.GetMinMaxWidth();

            if (floatPropIsRendererOwn)
            {
                renderer.SetProperty(Property.FLOAT, floatPropertyVal);
            }
            else
            {
                renderer.DeleteOwnProperty(Property.FLOAT);
            }
            return(kidMinMaxWidth);
        }
Esempio n. 18
0
        public virtual void ParagraphTest()
        {
            String      outFileName = destinationFolder + "paragraphTest01.pdf";
            String      cmpFileName = sourceFolder + "cmp_paragraphTest01.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName));
            Document    doc         = new Document(pdfDocument);
            String      str         = "Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me.";
            Paragraph   p           = new Paragraph(new Text(str).SetBorder(new SolidBorder(ColorConstants.BLACK, 5))).SetBorder(new
                                                                                                                                 SolidBorder(ColorConstants.BLUE, 5));
            MinMaxWidth result = ((AbstractRenderer)p.CreateRendererSubTree().SetParent(doc.GetRenderer())).GetMinMaxWidth
                                     ();

            p.SetWidth(ToEffectiveWidth(p, result.GetMinWidth()));
            doc.Add(p);
            doc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff"));
        }
        public override MinMaxWidth GetMinMaxWidth()
        {
            MinMaxWidth minMaxWidth = new MinMaxWidth();
            float?      rotation    = this.GetPropertyAsFloat(Property.ROTATION_ANGLE);

            if (!SetMinMaxWidthBasedOnFixedWidth(minMaxWidth))
            {
                float?minWidth = HasAbsoluteUnitValue(Property.MIN_WIDTH) ? RetrieveMinWidth(0) : null;
                float?maxWidth = HasAbsoluteUnitValue(Property.MAX_WIDTH) ? RetrieveMaxWidth(0) : null;
                if (minWidth == null || maxWidth == null)
                {
                    bool restoreRotation = HasOwnProperty(Property.ROTATION_ANGLE);
                    SetProperty(Property.ROTATION_ANGLE, null);
                    MinMaxWidthLayoutResult result = (MinMaxWidthLayoutResult)Layout(new LayoutContext(new LayoutArea(1, new Rectangle
                                                                                                                          (MinMaxWidthUtils.GetInfWidth(), AbstractRenderer.INF))));
                    if (restoreRotation)
                    {
                        SetProperty(Property.ROTATION_ANGLE, rotation);
                    }
                    else
                    {
                        DeleteOwnProperty(Property.ROTATION_ANGLE);
                    }
                    minMaxWidth = result.GetMinMaxWidth();
                }
                if (minWidth != null)
                {
                    minMaxWidth.SetChildrenMinWidth((float)minWidth);
                }
                if (maxWidth != null)
                {
                    minMaxWidth.SetChildrenMaxWidth((float)maxWidth);
                }
                if (minMaxWidth.GetChildrenMinWidth() > minMaxWidth.GetChildrenMaxWidth())
                {
                    minMaxWidth.SetChildrenMaxWidth(minMaxWidth.GetChildrenMaxWidth());
                }
            }
            else
            {
                minMaxWidth.SetAdditionalWidth(CalculateAdditionalWidth(this));
            }
            return(rotation != null?RotationUtils.CountRotationMinMaxWidth(minMaxWidth, this) : minMaxWidth);
        }
Esempio n. 20
0
 protected override bool SetMinMaxWidthBasedOnFixedWidth(MinMaxWidth minMaxWidth)
 {
     if (!HasAbsoluteUnitValue(Property.WIDTH))
     {
         UnitValue width        = this.GetProperty <UnitValue>(Property.WIDTH);
         bool      restoreWidth = HasOwnProperty(Property.WIDTH);
         SetProperty(Property.WIDTH, null);
         bool result = base.SetMinMaxWidthBasedOnFixedWidth(minMaxWidth);
         if (restoreWidth)
         {
             SetProperty(Property.WIDTH, width);
         }
         else
         {
             DeleteOwnProperty(Property.WIDTH);
         }
         return(result);
     }
     return(base.SetMinMaxWidthBasedOnFixedWidth(minMaxWidth));
 }
Esempio n. 21
0
        public virtual void DivWithBigRotatedParagraph()
        {
            String      outFileName = destinationFolder + "divBigRotatedParagraphTest01.pdf";
            String      cmpFileName = sourceFolder + "cmp_divBigRotatedParagraphTest01.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName));
            Document    doc         = new Document(pdfDocument);
            String      str         = "Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me.";
            Paragraph   p           = new Paragraph(new Text(str)).SetPadding(1f).SetBorder(new SolidBorder(ColorConstants.BLACK,
                                                                                                            2)).SetMargin(3).SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetRotationAngle(Math.PI / 8);
            Div d = new Div().SetPadding(4f).SetBorder(new SolidBorder(ColorConstants.GREEN, 5)).SetMargin(6);

            d.Add(p);
            d.Add(new Paragraph(("iText")));
            MinMaxWidth result = ((AbstractRenderer)d.CreateRendererSubTree().SetParent(doc.GetRenderer())).GetMinMaxWidth
                                     ();

            d.SetWidth(ToEffectiveWidth(d, result.GetMinWidth()));
            doc.Add(d);
            doc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff"));
        }
Esempio n. 22
0
        public virtual void HeaderFooterTableTest()
        {
            String   outFileName = destinationFolder + "headerFooterTableTest.pdf";
            String   cmpFileName = sourceFolder + "cmp_headerFooterTableTest.pdf";
            Document doc         = new Document(new PdfDocument(new PdfWriter(outFileName)));
            Cell     bigCell     = new Cell().Add(new Paragraph("veryveryveryvery big cell")).SetBorder(new SolidBorder(ColorConstants
                                                                                                                        .RED, 40)).SetBorderBottom(Border.NO_BORDER).SetBorderTop(Border.NO_BORDER).SetPadding(0);
            Cell mediumCell = new Cell().Add(new Paragraph("mediumsize cell")).SetBorder(new SolidBorder(ColorConstants
                                                                                                         .GREEN, 30)).SetBorderBottom(Border.NO_BORDER).SetBorderTop(Border.NO_BORDER).SetPadding(0);
            Cell cell = new Cell().Add(new Paragraph("cell")).SetBorder(new SolidBorder(ColorConstants.BLUE, 10)).SetBorderBottom
                            (Border.NO_BORDER).SetBorderTop(Border.NO_BORDER).SetPadding(0);
            Table table = new Table(UnitValue.CreatePercentArray(3)).UseAllAvailableWidth().SetBorder(new SolidBorder(
                                                                                                          ColorConstants.BLACK, 20)).AddCell(mediumCell.Clone(true)).AddCell(mediumCell.Clone(true)).AddCell(mediumCell
                                                                                                                                                                                                             .Clone(true)).AddFooterCell(cell.Clone(true)).AddFooterCell(cell.Clone(true)).AddFooterCell(bigCell.Clone
                                                                                                                                                                                                                                                                                                             (true)).AddHeaderCell(bigCell.Clone(true)).AddHeaderCell(cell.Clone(true)).AddHeaderCell(cell.Clone(true
                                                                                                                                                                                                                                                                                                                                                                                                                 ));
            TableRenderer renderer    = (TableRenderer)table.CreateRendererSubTree().SetParent(doc.GetRenderer());
            MinMaxWidth   minMaxWidth = renderer.GetMinMaxWidth();
            Table         minTable    = new Table(new float[] { -1, -1, -1 }).SetWidth(UnitValue.CreatePointValue(1)).SetBorder(new
                                                                                                                                SolidBorder(ColorConstants.BLACK, 20)).SetMarginTop(20).AddCell(mediumCell.Clone(true)).AddCell(mediumCell
                                                                                                                                                                                                                                .Clone(true)).AddCell(mediumCell.Clone(true)).AddFooterCell(cell.Clone(true)).AddFooterCell(cell.Clone
                                                                                                                                                                                                                                                                                                                                (true)).AddFooterCell(bigCell.Clone(true)).AddHeaderCell(bigCell.Clone(true)).AddHeaderCell(cell.Clone
                                                                                                                                                                                                                                                                                                                                                                                                                                (true)).AddHeaderCell(cell.Clone(true));
            Table maxTable = new Table(new float[] { -1, -1, -1 }).SetBorder(new SolidBorder(ColorConstants.BLACK, 20)
                                                                             ).SetMarginTop(20).AddCell(mediumCell.Clone(true)).AddCell(mediumCell.Clone(true)).AddCell(mediumCell.
                                                                                                                                                                        Clone(true)).AddFooterCell(cell.Clone(true)).AddFooterCell(cell.Clone(true)).AddFooterCell(bigCell.Clone
                                                                                                                                                                                                                                                                       (true)).AddHeaderCell(bigCell.Clone(true)).AddHeaderCell(cell.Clone(true)).AddHeaderCell(cell.Clone(true
                                                                                                                                                                                                                                                                                                                                                                           ));

            doc.Add(table);
            doc.Add(minTable);
            doc.Add(maxTable);
            doc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , "diff"));
        }
Esempio n. 23
0
 public MinMaxWidthLayoutResult(int status, LayoutArea occupiedArea, IRenderer splitRenderer, IRenderer overflowRenderer
                                , IRenderer cause)
     : base(status, occupiedArea, splitRenderer, overflowRenderer, cause)
 {
     minMaxWidth = new MinMaxWidth();
 }
Esempio n. 24
0
 public MaxSumWidthHandler(MinMaxWidth minMaxWidth)
     : base(minMaxWidth)
 {
 }
Esempio n. 25
0
        public override LayoutResult Layout(LayoutContext layoutContext)
        {
            LayoutArea      area         = layoutContext.GetArea().Clone();
            Rectangle       layoutBox    = area.GetBBox().Clone();
            AffineTransform t            = new AffineTransform();
            Image           modelElement = (Image)(GetModelElement());
            PdfXObject      xObject      = modelElement.GetXObject();

            imageWidth  = modelElement.GetImageWidth();
            imageHeight = modelElement.GetImageHeight();
            CalculateImageDimensions(layoutBox, t, xObject);
            OverflowPropertyValue?overflowX = null != parent?parent.GetProperty <OverflowPropertyValue?>(Property.OVERFLOW_X
                                                                                                         ) : OverflowPropertyValue.FIT;

            bool nowrap = false;

            if (parent is LineRenderer)
            {
                nowrap = true.Equals(this.parent.GetOwnProperty <bool?>(Property.NO_SOFT_WRAP_INLINE));
            }
            IList <Rectangle> floatRendererAreas    = layoutContext.GetFloatRendererAreas();
            float             clearHeightCorrection = FloatingHelper.CalculateClearHeightCorrection(this, floatRendererAreas, layoutBox
                                                                                                    );
            FloatPropertyValue?floatPropertyValue = this.GetProperty <FloatPropertyValue?>(Property.FLOAT);

            if (FloatingHelper.IsRendererFloating(this, floatPropertyValue))
            {
                layoutBox.DecreaseHeight(clearHeightCorrection);
                FloatingHelper.AdjustFloatedBlockLayoutBox(this, layoutBox, width, floatRendererAreas, floatPropertyValue,
                                                           overflowX);
            }
            else
            {
                clearHeightCorrection = FloatingHelper.AdjustLayoutBoxAccordingToFloats(floatRendererAreas, layoutBox, width
                                                                                        , clearHeightCorrection, null);
            }
            ApplyMargins(layoutBox, false);
            Border[] borders = GetBorders();
            ApplyBorderBox(layoutBox, borders, false);
            float?declaredMaxHeight         = RetrieveMaxHeight();
            OverflowPropertyValue?overflowY = null == parent || ((null == declaredMaxHeight || declaredMaxHeight > layoutBox
                                                                  .GetHeight()) && !layoutContext.IsClippedHeight()) ? OverflowPropertyValue.FIT : parent.GetProperty <OverflowPropertyValue?
                                                                                                                                                                       >(Property.OVERFLOW_Y);
            bool processOverflowX = !IsOverflowFit(overflowX) || nowrap;
            bool processOverflowY = !IsOverflowFit(overflowY);

            if (IsAbsolutePosition())
            {
                ApplyAbsolutePosition(layoutBox);
            }
            occupiedArea = new LayoutArea(area.GetPageNumber(), new Rectangle(layoutBox.GetX(), layoutBox.GetY() + layoutBox
                                                                              .GetHeight(), 0, 0));
            float imageItselfScaledWidth  = (float)width;
            float imageItselfScaledHeight = (float)height;

            if (IsFixedLayout())
            {
                fixedXPosition = this.GetPropertyAsFloat(Property.LEFT);
                fixedYPosition = this.GetPropertyAsFloat(Property.BOTTOM);
            }
            float?angle = this.GetPropertyAsFloat(Property.ROTATION_ANGLE);

            // See in adjustPositionAfterRotation why angle = 0 is necessary
            if (null == angle)
            {
                angle = 0f;
            }
            t.Rotate((float)angle);
            initialOccupiedAreaBBox = GetOccupiedAreaBBox().Clone();
            float scaleCoef = AdjustPositionAfterRotation((float)angle, layoutBox.GetWidth(), layoutBox.GetHeight());

            imageItselfScaledHeight *= scaleCoef;
            imageItselfScaledWidth  *= scaleCoef;
            initialOccupiedAreaBBox.MoveDown(imageItselfScaledHeight);
            initialOccupiedAreaBBox.SetHeight(imageItselfScaledHeight);
            initialOccupiedAreaBBox.SetWidth(imageItselfScaledWidth);
            if (xObject is PdfFormXObject)
            {
                t.Scale(scaleCoef, scaleCoef);
            }
            GetMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
            // indicates whether the placement is forced
            bool isPlacingForced = false;

            if (width > layoutBox.GetWidth() || height > layoutBox.GetHeight())
            {
                if (true.Equals(GetPropertyAsBoolean(Property.FORCED_PLACEMENT)) || (width > layoutBox.GetWidth() && processOverflowX
                                                                                     ) || (height > layoutBox.GetHeight() && processOverflowY))
                {
                    isPlacingForced = true;
                }
                else
                {
                    ApplyMargins(initialOccupiedAreaBBox, true);
                    ApplyBorderBox(initialOccupiedAreaBBox, true);
                    occupiedArea.GetBBox().SetHeight(initialOccupiedAreaBBox.GetHeight());
                    return(new MinMaxWidthLayoutResult(LayoutResult.NOTHING, occupiedArea, null, this, this));
                }
            }
            occupiedArea.GetBBox().MoveDown((float)height);
            if (borders[3] != null)
            {
                height += (float)Math.Sin((float)angle) * borders[3].GetWidth();
            }
            occupiedArea.GetBBox().SetHeight((float)height);
            occupiedArea.GetBBox().SetWidth((float)width);
            UnitValue leftMargin = this.GetPropertyAsUnitValue(Property.MARGIN_LEFT);

            if (!leftMargin.IsPointValue())
            {
                ILog logger = LogManager.GetLogger(typeof(iText.Layout.Renderer.ImageRenderer));
                logger.Error(MessageFormatUtil.Format(iText.IO.LogMessageConstant.PROPERTY_IN_PERCENTS_NOT_SUPPORTED, Property
                                                      .MARGIN_LEFT));
            }
            UnitValue topMargin = this.GetPropertyAsUnitValue(Property.MARGIN_TOP);

            if (!topMargin.IsPointValue())
            {
                ILog logger = LogManager.GetLogger(typeof(iText.Layout.Renderer.ImageRenderer));
                logger.Error(MessageFormatUtil.Format(iText.IO.LogMessageConstant.PROPERTY_IN_PERCENTS_NOT_SUPPORTED, Property
                                                      .MARGIN_TOP));
            }
            if (0 != leftMargin.GetValue() || 0 != topMargin.GetValue())
            {
                TranslateImage(leftMargin.GetValue(), topMargin.GetValue(), t);
                GetMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
            }
            ApplyBorderBox(occupiedArea.GetBBox(), borders, true);
            ApplyMargins(occupiedArea.GetBBox(), true);
            if (angle != 0)
            {
                ApplyRotationLayout((float)angle);
            }
            float       unscaledWidth = occupiedArea.GetBBox().GetWidth() / scaleCoef;
            MinMaxWidth minMaxWidth   = new MinMaxWidth(unscaledWidth, unscaledWidth, 0);
            UnitValue   rendererWidth = this.GetProperty <UnitValue>(Property.WIDTH);

            if (rendererWidth != null && rendererWidth.IsPercentValue())
            {
                minMaxWidth.SetChildrenMinWidth(0);
                float coeff = imageWidth / (float)RetrieveWidth(area.GetBBox().GetWidth());
                minMaxWidth.SetChildrenMaxWidth(unscaledWidth * coeff);
            }
            else
            {
                bool autoScale      = HasProperty(Property.AUTO_SCALE) && (bool)this.GetProperty <bool?>(Property.AUTO_SCALE);
                bool autoScaleWidth = HasProperty(Property.AUTO_SCALE_WIDTH) && (bool)this.GetProperty <bool?>(Property.AUTO_SCALE_WIDTH
                                                                                                               );
                if (autoScale || autoScaleWidth)
                {
                    minMaxWidth.SetChildrenMinWidth(0);
                }
            }
            FloatingHelper.RemoveFloatsAboveRendererBottom(floatRendererAreas, this);
            LayoutArea editedArea = FloatingHelper.AdjustResultOccupiedAreaForFloatAndClear(this, floatRendererAreas,
                                                                                            layoutContext.GetArea().GetBBox(), clearHeightCorrection, false);

            ApplyAbsolutePositionIfNeeded(layoutContext);
            return(new MinMaxWidthLayoutResult(LayoutResult.FULL, editedArea, null, null, isPlacingForced ? this : null
                                               ).SetMinMaxWidth(minMaxWidth));
        }
 public AbstractWidthHandler(MinMaxWidth minMaxWidth)
 {
     this.minMaxWidth = minMaxWidth;
 }
        protected internal virtual LayoutResult DirectLayout(LayoutContext layoutContext)
        {
            bool                   wasHeightClipped        = false;
            bool                   wasParentsHeightClipped = layoutContext.IsClippedHeight();
            int                    pageNumber               = layoutContext.GetArea().GetPageNumber();
            bool                   anythingPlaced           = false;
            bool                   firstLineInBox           = true;
            LineRenderer           currentRenderer          = (LineRenderer) new LineRenderer().SetParent(this);
            Rectangle              parentBBox               = layoutContext.GetArea().GetBBox().Clone();
            MarginsCollapseHandler marginsCollapseHandler   = null;
            bool                   marginsCollapsingEnabled = true.Equals(GetPropertyAsBoolean(Property.COLLAPSING_MARGINS));

            if (marginsCollapsingEnabled)
            {
                marginsCollapseHandler = new MarginsCollapseHandler(this, layoutContext.GetMarginsCollapseInfo());
            }
            OverflowPropertyValue?overflowX = this.GetProperty <OverflowPropertyValue?>(Property.OVERFLOW_X);
            bool?nowrapProp = this.GetPropertyAsBoolean(Property.NO_SOFT_WRAP_INLINE);

            currentRenderer.SetProperty(Property.NO_SOFT_WRAP_INLINE, nowrapProp);
            bool notAllKidsAreFloats = false;
            IList <Rectangle>  floatRendererAreas = layoutContext.GetFloatRendererAreas();
            FloatPropertyValue?floatPropertyValue = this.GetProperty <FloatPropertyValue?>(Property.FLOAT);
            float clearHeightCorrection           = FloatingHelper.CalculateClearHeightCorrection(this, floatRendererAreas, parentBBox
                                                                                                  );

            FloatingHelper.ApplyClearance(parentBBox, marginsCollapseHandler, clearHeightCorrection, FloatingHelper.IsRendererFloating
                                              (this));
            float?blockWidth = RetrieveWidth(parentBBox.GetWidth());

            if (FloatingHelper.IsRendererFloating(this, floatPropertyValue))
            {
                blockWidth = FloatingHelper.AdjustFloatedBlockLayoutBox(this, parentBBox, blockWidth, floatRendererAreas,
                                                                        floatPropertyValue, overflowX);
                floatRendererAreas = new List <Rectangle>();
            }
            if (0 == childRenderers.Count)
            {
                anythingPlaced  = true;
                currentRenderer = null;
            }
            bool  isPositioned              = IsPositioned();
            float?rotation                  = this.GetPropertyAsFloat(Property.ROTATION_ANGLE);
            float?blockMaxHeight            = RetrieveMaxHeight();
            OverflowPropertyValue?overflowY = (null == blockMaxHeight || blockMaxHeight > parentBBox.GetHeight()) &&
                                              !wasParentsHeightClipped ? OverflowPropertyValue.FIT : this.GetProperty <OverflowPropertyValue?>(Property
                                                                                                                                               .OVERFLOW_Y);

            if (rotation != null || IsFixedLayout())
            {
                parentBBox.MoveDown(AbstractRenderer.INF - parentBBox.GetHeight()).SetHeight(AbstractRenderer.INF);
            }
            if (rotation != null && !FloatingHelper.IsRendererFloating(this))
            {
                blockWidth = RotationUtils.RetrieveRotatedLayoutWidth(parentBBox.GetWidth(), this);
            }
            if (marginsCollapsingEnabled)
            {
                marginsCollapseHandler.StartMarginsCollapse(parentBBox);
            }
            Border[]    borders         = GetBorders();
            UnitValue[] paddings        = GetPaddings();
            float       additionalWidth = ApplyBordersPaddingsMargins(parentBBox, borders, paddings);

            ApplyWidth(parentBBox, blockWidth, overflowX);
            wasHeightClipped = ApplyMaxHeight(parentBBox, blockMaxHeight, marginsCollapseHandler, false, wasParentsHeightClipped
                                              , overflowY);
            MinMaxWidth          minMaxWidth  = new MinMaxWidth(additionalWidth);
            AbstractWidthHandler widthHandler = new MaxMaxWidthHandler(minMaxWidth);
            IList <Rectangle>    areas;

            if (isPositioned)
            {
                areas = JavaCollectionsUtil.SingletonList(parentBBox);
            }
            else
            {
                areas = InitElementAreas(new LayoutArea(pageNumber, parentBBox));
            }
            occupiedArea = new LayoutArea(pageNumber, new Rectangle(parentBBox.GetX(), parentBBox.GetY() + parentBBox.
                                                                    GetHeight(), parentBBox.GetWidth(), 0));
            ShrinkOccupiedAreaForAbsolutePosition();
            int       currentAreaPos = 0;
            Rectangle layoutBox      = areas[0].Clone();

            lines = new List <LineRenderer>();
            foreach (IRenderer child in childRenderers)
            {
                notAllKidsAreFloats = notAllKidsAreFloats || !FloatingHelper.IsRendererFloating(child);
                currentRenderer.AddChild(child);
            }
            float             lastYLine                            = layoutBox.GetY() + layoutBox.GetHeight();
            float             previousDescent                      = 0;
            float             lastLineBottomLeadingIndent          = 0;
            bool              onlyOverflowedFloatsLeft             = false;
            IList <IRenderer> inlineFloatsOverflowedToNextPage     = new List <IRenderer>();
            bool              floatOverflowedToNextPageWithNothing = false;
            // rectangles are compared by instances
            ICollection <Rectangle> nonChildFloatingRendererAreas = new HashSet <Rectangle>(floatRendererAreas);

            if (marginsCollapsingEnabled && childRenderers.Count > 0)
            {
                // passing null is sufficient to notify that there is a kid, however we don't care about it and it's margins
                marginsCollapseHandler.StartChildMarginsHandling(null, layoutBox);
            }
            bool includeFloatsInOccupiedArea = BlockFormattingContextUtil.IsRendererCreateBfc(this);

            while (currentRenderer != null)
            {
                currentRenderer.SetProperty(Property.TAB_DEFAULT, this.GetPropertyAsFloat(Property.TAB_DEFAULT));
                currentRenderer.SetProperty(Property.TAB_STOPS, this.GetProperty <Object>(Property.TAB_STOPS));
                float     lineIndent     = anythingPlaced ? 0 : (float)this.GetPropertyAsFloat(Property.FIRST_LINE_INDENT);
                Rectangle childLayoutBox = new Rectangle(layoutBox.GetX(), layoutBox.GetY(), layoutBox.GetWidth(), layoutBox
                                                         .GetHeight());
                currentRenderer.SetProperty(Property.OVERFLOW_X, overflowX);
                currentRenderer.SetProperty(Property.OVERFLOW_Y, overflowY);
                LineLayoutContext lineLayoutContext = new LineLayoutContext(new LayoutArea(pageNumber, childLayoutBox), null
                                                                            , floatRendererAreas, wasHeightClipped || wasParentsHeightClipped).SetTextIndent(lineIndent).SetFloatOverflowedToNextPageWithNothing
                                                          (floatOverflowedToNextPageWithNothing);
                LineLayoutResult result = (LineLayoutResult)((LineRenderer)currentRenderer.SetParent(this)).Layout(lineLayoutContext
                                                                                                                   );
                if (result.GetStatus() == LayoutResult.NOTHING)
                {
                    float?lineShiftUnderFloats = FloatingHelper.CalculateLineShiftUnderFloats(floatRendererAreas, layoutBox);
                    if (lineShiftUnderFloats != null)
                    {
                        layoutBox.DecreaseHeight((float)lineShiftUnderFloats);
                        firstLineInBox = true;
                        continue;
                    }
                    bool allRemainingKidsAreFloats = !currentRenderer.childRenderers.IsEmpty();
                    foreach (IRenderer renderer in currentRenderer.childRenderers)
                    {
                        allRemainingKidsAreFloats = allRemainingKidsAreFloats && FloatingHelper.IsRendererFloating(renderer);
                    }
                    if (allRemainingKidsAreFloats)
                    {
                        onlyOverflowedFloatsLeft = true;
                    }
                }
                floatOverflowedToNextPageWithNothing = lineLayoutContext.IsFloatOverflowedToNextPageWithNothing();
                if (result.GetFloatsOverflowedToNextPage() != null)
                {
                    inlineFloatsOverflowedToNextPage.AddAll(result.GetFloatsOverflowedToNextPage());
                }
                float minChildWidth = 0;
                float maxChildWidth = 0;
                if (result is MinMaxWidthLayoutResult)
                {
                    minChildWidth = ((MinMaxWidthLayoutResult)result).GetMinMaxWidth().GetMinWidth();
                    maxChildWidth = ((MinMaxWidthLayoutResult)result).GetMinMaxWidth().GetMaxWidth();
                }
                widthHandler.UpdateMinChildWidth(minChildWidth);
                widthHandler.UpdateMaxChildWidth(maxChildWidth);
                LineRenderer processedRenderer = null;
                if (result.GetStatus() == LayoutResult.FULL)
                {
                    processedRenderer = currentRenderer;
                }
                else
                {
                    if (result.GetStatus() == LayoutResult.PARTIAL)
                    {
                        processedRenderer = (LineRenderer)result.GetSplitRenderer();
                    }
                }
                if (onlyOverflowedFloatsLeft)
                {
                    // This is done to trick ParagraphRenderer to break rendering and to overflow to the next page.
                    // The `onlyOverflowedFloatsLeft` is set to true only when no other content is left except
                    // overflowed floating elements.
                    processedRenderer = null;
                }
                TextAlignment?textAlignment = (TextAlignment?)this.GetProperty <TextAlignment?>(Property.TEXT_ALIGNMENT, TextAlignment
                                                                                                .LEFT);
                ApplyTextAlignment(textAlignment, result, processedRenderer, layoutBox, floatRendererAreas, onlyOverflowedFloatsLeft
                                   , lineIndent);
                Leading leading = RenderingMode.HTML_MODE.Equals(this.GetProperty <RenderingMode?>(Property.RENDERING_MODE)
                                                                 ) ? null : this.GetProperty <Leading>(Property.LEADING);
                // could be false if e.g. line contains only floats
                bool lineHasContent = processedRenderer != null && processedRenderer.GetOccupiedArea().GetBBox().GetHeight
                                          () > 0;
                bool  isFit  = processedRenderer != null;
                float deltaY = 0;
                if (isFit && !RenderingMode.HTML_MODE.Equals(this.GetProperty <RenderingMode?>(Property.RENDERING_MODE)))
                {
                    if (lineHasContent)
                    {
                        float indentFromLastLine = previousDescent - lastLineBottomLeadingIndent - (leading != null ? processedRenderer
                                                                                                    .GetTopLeadingIndent(leading) : 0) - processedRenderer.GetMaxAscent();
                        // TODO this is a workaround. To be refactored
                        if (processedRenderer != null && processedRenderer.ContainsImage())
                        {
                            indentFromLastLine += previousDescent;
                        }
                        deltaY = lastYLine + indentFromLastLine - processedRenderer.GetYLine();
                        lastLineBottomLeadingIndent = leading != null?processedRenderer.GetBottomLeadingIndent(leading) : 0;

                        // TODO this is a workaround. To be refactored
                        if (lastLineBottomLeadingIndent < 0 && processedRenderer.ContainsImage())
                        {
                            lastLineBottomLeadingIndent = 0;
                        }
                    }
                    // for the first and last line in a paragraph, leading is smaller
                    if (firstLineInBox)
                    {
                        deltaY = processedRenderer != null && leading != null ? -processedRenderer.GetTopLeadingIndent(leading) :
                                 0;
                    }
                    isFit = leading == null || processedRenderer.GetOccupiedArea().GetBBox().GetY() + deltaY >= layoutBox.GetY
                                ();
                }
                if (!isFit && (null == processedRenderer || IsOverflowFit(overflowY)))
                {
                    if (currentAreaPos + 1 < areas.Count)
                    {
                        layoutBox      = areas[++currentAreaPos].Clone();
                        lastYLine      = layoutBox.GetY() + layoutBox.GetHeight();
                        firstLineInBox = true;
                    }
                    else
                    {
                        bool keepTogether = IsKeepTogether();
                        if (keepTogether)
                        {
                            floatRendererAreas.RetainAll(nonChildFloatingRendererAreas);
                            return(new MinMaxWidthLayoutResult(LayoutResult.NOTHING, null, null, this, null == result.GetCauseOfNothing
                                                                   () ? this : result.GetCauseOfNothing()));
                        }
                        else
                        {
                            if (marginsCollapsingEnabled)
                            {
                                if (anythingPlaced && notAllKidsAreFloats)
                                {
                                    marginsCollapseHandler.EndChildMarginsHandling(layoutBox);
                                }
                            }
                            // On page split, if not only overflowed floats left, content will be drawn on next page, i.e. under all floats on this page
                            bool includeFloatsInOccupiedAreaOnSplit = !onlyOverflowedFloatsLeft || includeFloatsInOccupiedArea;
                            if (includeFloatsInOccupiedAreaOnSplit)
                            {
                                FloatingHelper.IncludeChildFloatsInOccupiedArea(floatRendererAreas, this, nonChildFloatingRendererAreas);
                                FixOccupiedAreaIfOverflowedX(overflowX, layoutBox);
                            }
                            if (marginsCollapsingEnabled)
                            {
                                marginsCollapseHandler.EndMarginsCollapse(layoutBox);
                            }
                            bool minHeightOverflowed = false;
                            if (!includeFloatsInOccupiedAreaOnSplit)
                            {
                                AbstractRenderer minHeightOverflow = ApplyMinHeight(overflowY, layoutBox);
                                minHeightOverflowed = minHeightOverflow != null;
                                ApplyVerticalAlignment();
                            }
                            iText.Layout.Renderer.ParagraphRenderer[] split = Split();
                            split[0].lines = lines;
                            foreach (LineRenderer line in lines)
                            {
                                split[0].childRenderers.AddAll(line.GetChildRenderers());
                            }
                            split[1].childRenderers.AddAll(inlineFloatsOverflowedToNextPage);
                            if (processedRenderer != null)
                            {
                                split[1].childRenderers.AddAll(processedRenderer.GetChildRenderers());
                            }
                            if (result.GetOverflowRenderer() != null)
                            {
                                split[1].childRenderers.AddAll(result.GetOverflowRenderer().GetChildRenderers());
                            }
                            if (onlyOverflowedFloatsLeft && !includeFloatsInOccupiedArea && !minHeightOverflowed)
                            {
                                FloatingHelper.RemoveParentArtifactsOnPageSplitIfOnlyFloatsOverflow(split[1]);
                            }
                            float usedHeight = occupiedArea.GetBBox().GetHeight();
                            if (!includeFloatsInOccupiedAreaOnSplit)
                            {
                                Rectangle commonRectangle = Rectangle.GetCommonRectangle(layoutBox, occupiedArea.GetBBox());
                                usedHeight = commonRectangle.GetHeight();
                            }
                            UpdateHeightsOnSplit(usedHeight, wasHeightClipped, this, split[1], includeFloatsInOccupiedAreaOnSplit);
                            CorrectFixedLayout(layoutBox);
                            ApplyPaddings(occupiedArea.GetBBox(), paddings, true);
                            ApplyBorderBox(occupiedArea.GetBBox(), borders, true);
                            ApplyMargins(occupiedArea.GetBBox(), true);
                            ApplyAbsolutePositionIfNeeded(layoutContext);
                            LayoutArea editedArea = FloatingHelper.AdjustResultOccupiedAreaForFloatAndClear(this, layoutContext.GetFloatRendererAreas
                                                                                                                (), layoutContext.GetArea().GetBBox(), clearHeightCorrection, marginsCollapsingEnabled);
                            if (wasHeightClipped)
                            {
                                return(new MinMaxWidthLayoutResult(LayoutResult.FULL, editedArea, split[0], null).SetMinMaxWidth(minMaxWidth
                                                                                                                                 ));
                            }
                            else
                            {
                                if (anythingPlaced)
                                {
                                    return(new MinMaxWidthLayoutResult(LayoutResult.PARTIAL, editedArea, split[0], split[1]).SetMinMaxWidth(minMaxWidth
                                                                                                                                            ));
                                }
                                else
                                {
                                    if (true.Equals(GetPropertyAsBoolean(Property.FORCED_PLACEMENT)))
                                    {
                                        occupiedArea.SetBBox(Rectangle.GetCommonRectangle(occupiedArea.GetBBox(), currentRenderer.GetOccupiedArea(
                                                                                              ).GetBBox()));
                                        FixOccupiedAreaIfOverflowedX(overflowX, layoutBox);
                                        parent.SetProperty(Property.FULL, true);
                                        lines.Add(currentRenderer);
                                        // Force placement of children we have and do not force placement of the others
                                        if (LayoutResult.PARTIAL == result.GetStatus())
                                        {
                                            IRenderer childNotRendered = result.GetCauseOfNothing();
                                            int       firstNotRendered = currentRenderer.childRenderers.IndexOf(childNotRendered);
                                            currentRenderer.childRenderers.RetainAll(currentRenderer.childRenderers.SubList(0, firstNotRendered));
                                            split[1].childRenderers.RemoveAll(split[1].childRenderers.SubList(0, firstNotRendered));
                                            return(new MinMaxWidthLayoutResult(LayoutResult.PARTIAL, editedArea, this, split[1], null).SetMinMaxWidth(
                                                       minMaxWidth));
                                        }
                                        else
                                        {
                                            return(new MinMaxWidthLayoutResult(LayoutResult.FULL, editedArea, null, null, this).SetMinMaxWidth(minMaxWidth
                                                                                                                                               ));
                                        }
                                    }
                                    else
                                    {
                                        floatRendererAreas.RetainAll(nonChildFloatingRendererAreas);
                                        return(new MinMaxWidthLayoutResult(LayoutResult.NOTHING, null, null, this, null == result.GetCauseOfNothing
                                                                               () ? this : result.GetCauseOfNothing()));
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (leading != null)
                    {
                        processedRenderer.ApplyLeading(deltaY);
                        if (lineHasContent)
                        {
                            lastYLine = processedRenderer.GetYLine();
                        }
                    }
                    if (lineHasContent)
                    {
                        occupiedArea.SetBBox(Rectangle.GetCommonRectangle(occupiedArea.GetBBox(), processedRenderer.GetOccupiedArea
                                                                              ().GetBBox()));
                        FixOccupiedAreaIfOverflowedX(overflowX, layoutBox);
                    }
                    firstLineInBox = false;
                    layoutBox.SetHeight(processedRenderer.GetOccupiedArea().GetBBox().GetY() - layoutBox.GetY());
                    lines.Add(processedRenderer);
                    anythingPlaced  = true;
                    currentRenderer = (LineRenderer)result.GetOverflowRenderer();
                    previousDescent = processedRenderer.GetMaxDescent();
                    if (!inlineFloatsOverflowedToNextPage.IsEmpty() && result.GetOverflowRenderer() == null)
                    {
                        onlyOverflowedFloatsLeft = true;
                        // dummy renderer to trick paragraph renderer to continue kids loop
                        currentRenderer = new LineRenderer();
                    }
                }
            }
            if (!RenderingMode.HTML_MODE.Equals(this.GetProperty <RenderingMode?>(Property.RENDERING_MODE)))
            {
                float moveDown = lastLineBottomLeadingIndent;
                if (IsOverflowFit(overflowY) && moveDown > occupiedArea.GetBBox().GetY() - layoutBox.GetY())
                {
                    moveDown = occupiedArea.GetBBox().GetY() - layoutBox.GetY();
                }
                occupiedArea.GetBBox().MoveDown(moveDown);
                occupiedArea.GetBBox().SetHeight(occupiedArea.GetBBox().GetHeight() + moveDown);
            }
            if (marginsCollapsingEnabled)
            {
                if (childRenderers.Count > 0 && notAllKidsAreFloats)
                {
                    marginsCollapseHandler.EndChildMarginsHandling(layoutBox);
                }
            }
            if (includeFloatsInOccupiedArea)
            {
                FloatingHelper.IncludeChildFloatsInOccupiedArea(floatRendererAreas, this, nonChildFloatingRendererAreas);
                FixOccupiedAreaIfOverflowedX(overflowX, layoutBox);
            }
            if (wasHeightClipped)
            {
                FixOccupiedAreaIfOverflowedY(overflowY, layoutBox);
            }
            if (marginsCollapsingEnabled)
            {
                marginsCollapseHandler.EndMarginsCollapse(layoutBox);
            }
            AbstractRenderer overflowRenderer = ApplyMinHeight(overflowY, layoutBox);

            if (overflowRenderer != null && IsKeepTogether())
            {
                floatRendererAreas.RetainAll(nonChildFloatingRendererAreas);
                return(new LayoutResult(LayoutResult.NOTHING, null, null, this, this));
            }
            CorrectFixedLayout(layoutBox);
            ApplyPaddings(occupiedArea.GetBBox(), paddings, true);
            ApplyBorderBox(occupiedArea.GetBBox(), borders, true);
            ApplyMargins(occupiedArea.GetBBox(), true);
            ApplyAbsolutePositionIfNeeded(layoutContext);
            if (rotation != null)
            {
                ApplyRotationLayout(layoutContext.GetArea().GetBBox().Clone());
                if (IsNotFittingLayoutArea(layoutContext.GetArea()))
                {
                    if (IsNotFittingWidth(layoutContext.GetArea()) && !IsNotFittingHeight(layoutContext.GetArea()))
                    {
                        LogManager.GetLogger(GetType()).Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA
                                                                                      , "It fits by height so it will be forced placed"));
                    }
                    else
                    {
                        if (!true.Equals(GetPropertyAsBoolean(Property.FORCED_PLACEMENT)))
                        {
                            floatRendererAreas.RetainAll(nonChildFloatingRendererAreas);
                            return(new MinMaxWidthLayoutResult(LayoutResult.NOTHING, null, null, this, this));
                        }
                    }
                }
            }
            ApplyVerticalAlignment();
            FloatingHelper.RemoveFloatsAboveRendererBottom(floatRendererAreas, this);
            LayoutArea editedArea_1 = FloatingHelper.AdjustResultOccupiedAreaForFloatAndClear(this, layoutContext.GetFloatRendererAreas
                                                                                                  (), layoutContext.GetArea().GetBBox(), clearHeightCorrection, marginsCollapsingEnabled);

            if (null == overflowRenderer)
            {
                return(new MinMaxWidthLayoutResult(LayoutResult.FULL, editedArea_1, null, null, null).SetMinMaxWidth(minMaxWidth
                                                                                                                     ));
            }
            else
            {
                return(new MinMaxWidthLayoutResult(LayoutResult.PARTIAL, editedArea_1, this, overflowRenderer, null).SetMinMaxWidth
                           (minMaxWidth));
            }
        }
Esempio n. 28
0
 public virtual iText.Layout.Layout.MinMaxWidthLayoutResult SetMinMaxWidth(MinMaxWidth minMaxWidth)
 {
     this.minMaxWidth = minMaxWidth;
     return(this);
 }