Exemplo n.º 1
0
        public virtual void ParseParametersAndCalculateCoordinatesWithBetterPrecisionEllipseTest()
        {
            String      filename = "parseParametersAndCalculateCoordinatesWithBetterPrecisionEllipseTest.pdf";
            PdfDocument doc      = new PdfDocument(new PdfWriter(destinationFolder + filename));

            doc.AddNewPage();
            EllipseSvgNodeRenderer ellipseRenderer = new EllipseSvgNodeRenderer();

            ellipseRenderer.SetAttribute(SvgConstants.Attributes.CX, "170.3");
            ellipseRenderer.SetAttribute(SvgConstants.Attributes.CY, "339.5");
            ellipseRenderer.SetAttribute(SvgConstants.Attributes.RX, "6");
            ellipseRenderer.SetAttribute(SvgConstants.Attributes.RY, "6");
            // Parse parameters with better precision (in double type) in the method CssUtils#parseAbsoluteLength
            ellipseRenderer.SetParameters();
            SvgDrawContext context = new SvgDrawContext(null, null);
            PdfCanvas      cv      = new PdfCanvas(doc, 1);

            context.PushCanvas(cv);
            // Calculate coordinates with better precision (in double type) in the method EllipseSvgNodeRenderer#doDraw
            ellipseRenderer.Draw(context);
            String pageContentBytes = iText.IO.Util.JavaUtil.GetStringForBytes(doc.GetPage(1).GetContentBytes(), System.Text.Encoding
                                                                               .UTF8);

            doc.Close();
            String expectedResult = "132.22 254.63 m\n" + "132.22 257.11 130.21 259.13 127.72 259.13 c\n" + "125.24 259.13 123.22 257.11 123.22 254.63 c\n"
                                    + "123.22 252.14 125.24 250.13 127.72 250.13 c\n" + "130.21 250.13 132.22 252.14 132.22 254.63 c";

            NUnit.Framework.Assert.IsTrue(pageContentBytes.Contains(expectedResult));
        }
        public virtual void ConnectPointsWithSameYCoordinateTest()
        {
            PdfDocument doc = new PdfDocument(new PdfWriter(new MemoryStream()));

            doc.AddNewPage();
            ISvgNodeRenderer             root = new PolygonSvgNodeRenderer();
            IDictionary <String, String> polyLineAttributes = new Dictionary <String, String>();

            polyLineAttributes.Put(SvgConstants.Attributes.POINTS, "100,100 100,200 150,200 150,100");
            polyLineAttributes.Put(SvgConstants.Attributes.FILL, "none");
            polyLineAttributes.Put(SvgConstants.Attributes.STROKE, "black");
            root.SetAttributesAndStyles(polyLineAttributes);
            SvgDrawContext context = new SvgDrawContext(null, null);
            PdfCanvas      cv      = new PdfCanvas(doc, 1);

            context.PushCanvas(cv);
            root.Draw(context);
            doc.Close();
            IList <Point> expectedPoints = new List <Point>();

            expectedPoints.Add(new Point(75, 75));
            expectedPoints.Add(new Point(75, 150));
            expectedPoints.Add(new Point(112.5, 150));
            expectedPoints.Add(new Point(112.5, 75));
            expectedPoints.Add(new Point(75, 75));
            IList <Point> attributePoints = ((PolygonSvgNodeRenderer)root).GetPoints();

            NUnit.Framework.Assert.AreEqual(expectedPoints.Count, attributePoints.Count);
            for (int x = 0; x < attributePoints.Count; x++)
            {
                NUnit.Framework.Assert.AreEqual(expectedPoints[x], attributePoints[x]);
            }
        }
        /// <summary>
        /// Applies transformations set to this object, if any, and delegates the drawing of this element and its children
        /// to the
        /// <see cref="DoDraw(iText.Svg.Renderers.SvgDrawContext)">doDraw</see>
        /// method.
        /// </summary>
        /// <param name="context">the object that knows the place to draw this element and maintains its state</param>
        public void Draw(SvgDrawContext context)
        {
            PdfCanvas currentCanvas = context.GetCurrentCanvas();

            if (this.attributesAndStyles != null)
            {
                String transformString = this.attributesAndStyles.Get(SvgConstants.Attributes.TRANSFORM);
                if (transformString != null && !String.IsNullOrEmpty(transformString))
                {
                    AffineTransform transformation = TransformUtils.ParseTransform(transformString);
                    if (!transformation.IsIdentity())
                    {
                        currentCanvas.ConcatMatrix(transformation);
                    }
                }
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.ID))
                {
                    context.AddUsedId(attributesAndStyles.Get(SvgConstants.Attributes.ID));
                }
            }

            /* If a (non-empty) clipping path exists, drawing operations must be surrounded by q/Q operators
             * and may have to be drawn multiple times
             */
            if (!DrawInClipPath(context))
            {
                PreDraw(context);
                DoDraw(context);
                PostDraw(context);
            }
            if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.ID))
            {
                context.RemoveUsedId(attributesAndStyles.Get(SvgConstants.Attributes.ID));
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Method that will set properties to be inherited by this branch renderer's
 /// children and will iterate over all children in order to draw them.
 /// </summary>
 /// <param name="context">
 /// the object that knows the place to draw this element and
 /// maintains its state
 /// </param>
 protected internal override void DoDraw(SvgDrawContext context)
 {
     if (GetChildren().Count > 0)
     {
         // if branch has no children, don't do anything
         PdfStream stream = new PdfStream();
         stream.Put(PdfName.Type, PdfName.XObject);
         stream.Put(PdfName.Subtype, PdfName.Form);
         PdfFormXObject xObject   = (PdfFormXObject)PdfXObject.MakeXObject(stream);
         PdfCanvas      newCanvas = new PdfCanvas(xObject, context.GetCurrentCanvas().GetDocument());
         ApplyViewBox(context);
         //Bounding box needs to be written after viewbox calculations to account for pdf syntax interaction
         stream.Put(PdfName.BBox, new PdfArray(context.GetCurrentViewPort()));
         context.PushCanvas(newCanvas);
         ApplyViewportClip(context);
         ApplyViewportTranslationCorrection(context);
         foreach (ISvgNodeRenderer child in GetChildren())
         {
             newCanvas.SaveState();
             child.Draw(context);
             newCanvas.RestoreState();
         }
         CleanUp(context);
         context.GetCurrentCanvas().AddXObject(xObject, 0, 0);
     }
 }
Exemplo n.º 5
0
        /// <summary>Calculate the viewport based on the context.</summary>
        /// <param name="context">the SVG draw context</param>
        /// <returns>the viewport that applies to this renderer</returns>
        internal virtual Rectangle CalculateViewPort(SvgDrawContext context)
        {
            Rectangle currentViewPort = context.GetCurrentViewPort();
            // Set default values to parent viewport in the case of a nested svg tag
            float portX = currentViewPort.GetX();
            float portY = currentViewPort.GetY();
            // Default should be parent portWidth if not outermost
            float portWidth = currentViewPort.GetWidth();
            // Default should be parent height if not outermost
            float portHeight = currentViewPort.GetHeight();

            if (attributesAndStyles != null)
            {
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.X))
                {
                    portX = CssUtils.ParseAbsoluteLength(attributesAndStyles.Get(SvgConstants.Attributes.X));
                }
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.Y))
                {
                    portY = CssUtils.ParseAbsoluteLength(attributesAndStyles.Get(SvgConstants.Attributes.Y));
                }
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.WIDTH))
                {
                    portWidth = CssUtils.ParseAbsoluteLength(attributesAndStyles.Get(SvgConstants.Attributes.WIDTH));
                }
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.HEIGHT))
                {
                    portHeight = CssUtils.ParseAbsoluteLength(attributesAndStyles.Get(SvgConstants.Attributes.HEIGHT));
                }
            }
            return(new Rectangle(portX, portY, portWidth, portHeight));
        }
        public virtual void PathNodeRendererMoveToTest1()
        {
            String      filename = "pathNodeRendererMoveToTest1.pdf";
            PdfDocument doc      = new PdfDocument(new PdfWriter(destinationFolder + filename));

            doc.AddNewPage();
            IDictionary <String, String> pathShapes = new Dictionary <String, String>();

            pathShapes.Put("d", "M 100 100 l300 100 L200 300 z");
            ISvgNodeRenderer pathRenderer = new PathSvgNodeRenderer();

            pathRenderer.SetAttributesAndStyles(pathShapes);
            SvgDrawContext context = new SvgDrawContext(null, null);
            PdfCanvas      cv      = new PdfCanvas(doc, 1);

            context.PushCanvas(cv);
            pathRenderer.Draw(context);
            doc.Close();
            String result = new CompareTool().CompareByContent(destinationFolder + filename, sourceFolder + "cmp_" + filename
                                                               , destinationFolder, "diff_");

            if (result != null && !result.Contains("No visual differences"))
            {
                NUnit.Framework.Assert.Fail(result);
            }
        }
        protected internal override void DoDraw(SvgDrawContext context)
        {
            PdfCanvas currentCanvas = context.GetCurrentCanvas();

            foreach (ISvgNodeRenderer child in GetChildren())
            {
                currentCanvas.SaveState();
                if (child is AbstractSvgNodeRenderer)
                {
                    ((AbstractSvgNodeRenderer)child).SetPartOfClipPath(true);
                }
                child.Draw(context);
                if (child is AbstractSvgNodeRenderer)
                {
                    ((AbstractSvgNodeRenderer)child).SetPartOfClipPath(false);
                }
                if (clippedRenderer != null)
                {
                    clippedRenderer.PreDraw(context);
                    clippedRenderer.DoDraw(context);
                    clippedRenderer.PostDraw(context);
                }
                currentCanvas.RestoreState();
            }
        }
Exemplo n.º 8
0
        public override Color CreateColor(SvgDrawContext context, Rectangle objectBoundingBox, float objectBoundingBoxMargin
                                          , float parentOpacity)
        {
            if (objectBoundingBox == null)
            {
                return(null);
            }
            LinearGradientBuilder builder = new LinearGradientBuilder();

            foreach (GradientColorStop stopColor in ParseStops(parentOpacity))
            {
                builder.AddColorStop(stopColor);
            }
            builder.SetSpreadMethod(ParseSpreadMethod());
            bool isObjectBoundingBox = IsObjectBoundingBoxUnits();

            Point[] coordinates = GetCoordinates(context, isObjectBoundingBox);
            builder.SetGradientVector(coordinates[0].GetX(), coordinates[0].GetY(), coordinates[1].GetX(), coordinates
                                      [1].GetY());
            AffineTransform gradientTransform = GetGradientTransformToUserSpaceOnUse(objectBoundingBox, isObjectBoundingBox
                                                                                     );

            builder.SetCurrentSpaceToGradientVectorSpaceTransformation(gradientTransform);
            return(builder.BuildColor(objectBoundingBox.ApplyMargins(objectBoundingBoxMargin, objectBoundingBoxMargin,
                                                                     objectBoundingBoxMargin, objectBoundingBoxMargin, true), context.GetCurrentCanvasTransform(), context.
                                      GetCurrentCanvas().GetDocument()));
        }
        internal virtual void ResolveFont(SvgDrawContext context)
        {
            FontProvider provider  = context.GetFontProvider();
            FontSet      tempFonts = context.GetTempFonts();

            font = null;
            if (!provider.GetFontSet().IsEmpty() || (tempFonts != null && !tempFonts.IsEmpty()))
            {
                String fontFamily = this.attributesAndStyles.Get(SvgConstants.Attributes.FONT_FAMILY);
                String fontWeight = this.attributesAndStyles.Get(SvgConstants.Attributes.FONT_WEIGHT);
                String fontStyle  = this.attributesAndStyles.Get(SvgConstants.Attributes.FONT_STYLE);
                fontFamily = fontFamily != null?fontFamily.Trim() : "";

                FontInfo fontInfo = ResolveFontName(fontFamily, fontWeight, fontStyle, provider, tempFonts);
                font = provider.GetPdfFont(fontInfo, tempFonts);
            }
            if (font == null)
            {
                try {
                    // TODO: DEVSIX-2057 each call of createFont() create a new instance of PdfFont.
                    // FontProvider shall be used instead.
                    font = PdfFontFactory.CreateFont();
                }
                catch (System.IO.IOException e) {
                    throw new SvgProcessingException(SvgLogMessageConstant.FONT_NOT_FOUND, e);
                }
            }
        }
Exemplo n.º 10
0
 private void ApplyUserSpaceScaling(SvgDrawContext context)
 {
     if (!this.attributesAndStyles.ContainsKey(SvgConstants.Attributes.MARKER_UNITS) || SvgConstants.Values.STROKEWIDTH
         .Equals(this.attributesAndStyles.Get(SvgConstants.Attributes.MARKER_UNITS)))
     {
         String parentValue = this.GetParent().GetAttribute(SvgConstants.Attributes.STROKE_WIDTH);
         if (parentValue != null)
         {
             float strokeWidthScale;
             if (CssUtils.IsPercentageValue(parentValue))
             {
                 // If stroke width is a percentage value is always computed as a percentage of the normalized viewBox diagonal length.
                 double rootViewPortHeight    = context.GetRootViewPort().GetHeight();
                 double rootViewPortWidth     = context.GetRootViewPort().GetWidth();
                 double viewBoxDiagonalLength = Math.Sqrt(rootViewPortHeight * rootViewPortHeight + rootViewPortWidth * rootViewPortWidth
                                                          );
                 strokeWidthScale = CssUtils.ParseRelativeValue(parentValue, (float)viewBoxDiagonalLength);
             }
             else
             {
                 strokeWidthScale = SvgCssUtils.ConvertPtsToPx(ParseFontRelativeOrAbsoluteLengthOnMarker(parentValue));
             }
             context.GetCurrentCanvas().ConcatMatrix(AffineTransform.GetScaleInstance(strokeWidthScale, strokeWidthScale
                                                                                      ));
         }
     }
 }
        public virtual void PolyPointCheckerTest()
        {
            PdfDocument doc = new PdfDocument(new PdfWriter(new MemoryStream()));

            doc.AddNewPage();
            ISvgNodeRenderer             root = new PolylineSvgNodeRenderer();
            IDictionary <String, String> polyLineAttributes = new Dictionary <String, String>();

            polyLineAttributes.Put(SvgConstants.Attributes.POINTS, "0,0 100,100 200,200 300,300");
            root.SetAttributesAndStyles(polyLineAttributes);
            SvgDrawContext context = new SvgDrawContext(null, null);
            PdfCanvas      cv      = new PdfCanvas(doc, 1);

            context.PushCanvas(cv);
            root.Draw(context);
            IList <Point> expectedPoints = new List <Point>();

            expectedPoints.Add(new Point(0, 0));
            expectedPoints.Add(new Point(75, 75));
            expectedPoints.Add(new Point(150, 150));
            expectedPoints.Add(new Point(225, 225));
            IList <Point> attributePoints = ((PolylineSvgNodeRenderer)root).GetPoints();

            NUnit.Framework.Assert.AreEqual(expectedPoints.Count, attributePoints.Count);
            for (int x = 0; x < attributePoints.Count; x++)
            {
                NUnit.Framework.Assert.AreEqual(expectedPoints[x], attributePoints[x]);
            }
        }
Exemplo n.º 12
0
        public virtual void CalculateNestedViewportDifferentFromParentTest()
        {
            Rectangle      expected = new Rectangle(0, 0, 500, 500);
            SvgDrawContext context  = new SvgDrawContext(null, null);
            PdfDocument    document = new PdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().SetCompressionLevel
                                                                        (0)));

            document.AddNewPage();
            PdfFormXObject pdfForm = new PdfFormXObject(expected);
            PdfCanvas      canvas  = new PdfCanvas(pdfForm, document);

            context.PushCanvas(canvas);
            context.AddViewPort(expected);
            SvgTagSvgNodeRenderer        parent   = new SvgTagSvgNodeRenderer();
            SvgTagSvgNodeRenderer        renderer = new SvgTagSvgNodeRenderer();
            PdfRootSvgNodeRenderer       root     = new PdfRootSvgNodeRenderer(parent);
            IDictionary <String, String> styles   = new Dictionary <String, String>();

            styles.Put("width", "500");
            styles.Put("height", "500");
            renderer.SetAttributesAndStyles(styles);
            renderer.SetParent(parent);
            Rectangle actual = root.CalculateViewPort(context);

            NUnit.Framework.Assert.IsTrue(expected.EqualsWithEpsilon(actual));
        }
Exemplo n.º 13
0
 private void ApplyRotation(SvgDrawContext context)
 {
     if (this.attributesAndStyles.ContainsKey(SvgConstants.Attributes.ORIENT))
     {
         String orient   = this.attributesAndStyles.Get(SvgConstants.Attributes.ORIENT);
         double rotAngle = double.NaN;
         // If placed by marker-start, the marker is oriented 180° different from
         // the orientation that would be used if auto was specified.
         // For all other markers, auto-start-reverse means the same as auto.
         if (SvgConstants.Values.AUTO.Equals(orient) || (SvgConstants.Values.AUTO_START_REVERSE.Equals(orient) && !
                                                         SvgConstants.Attributes.MARKER_START.Equals(this.attributesAndStyles.Get(SvgConstants.Tags.MARKER))))
         {
             rotAngle = ((IMarkerCapable)GetParent()).GetAutoOrientAngle(this, false);
         }
         else
         {
             if (SvgConstants.Values.AUTO_START_REVERSE.Equals(orient) && SvgConstants.Attributes.MARKER_START.Equals(this
                                                                                                                      .attributesAndStyles.Get(SvgConstants.Tags.MARKER)))
             {
                 rotAngle = ((IMarkerCapable)GetParent()).GetAutoOrientAngle(this, true);
             }
             else
             {
                 if (CssUtils.IsAngleValue(orient) || CssUtils.IsNumericValue(orient))
                 {
                     rotAngle = CssUtils.ParseAngle(this.attributesAndStyles.Get(SvgConstants.Attributes.ORIENT));
                 }
             }
         }
         if (!double.IsNaN(rotAngle))
         {
             context.GetCurrentCanvas().ConcatMatrix(AffineTransform.GetRotateInstance(rotAngle));
         }
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Create an
        /// <see cref="iText.Kernel.Pdf.Xobject.PdfFormXObject"/>
        /// tied to the passed
        /// <c>PdfDocument</c>
        /// using the SVG processing result.
        /// </summary>
        /// <param name="result">Processing result containing the SVG information</param>
        /// <param name="pdfDocument">pdf that shall contain the image</param>
        /// <returns>PdfFormXObject instance</returns>
        public virtual PdfFormXObject CreateXObjectFromProcessingResult(ISvgProcessorResult result, PdfDocument pdfDocument
                                                                        )
        {
            ISvgNodeRenderer topSvgRenderer = result.GetRootRenderer();
            float            width;
            float            height;

            float[] wh = SvgConverter.ExtractWidthAndHeight(topSvgRenderer);
            width  = wh[0];
            height = wh[1];
            PdfFormXObject   pdfForm      = new PdfFormXObject(new Rectangle(0, 0, width, height));
            PdfCanvas        canvas       = new PdfCanvas(pdfForm, pdfDocument);
            ResourceResolver tempResolver = new ResourceResolver(null, resourceResolver.GetRetriever());
            // TODO DEVSIX-4107 pass the resourceResolver variable (not tempResolver variable) to the
            //  SvgDrawContext constructor so that the SVG inside the SVG is processed.
            SvgDrawContext context = new SvgDrawContext(tempResolver, result.GetFontProvider(), result.GetRootRenderer
                                                            ());

            context.AddNamedObjects(result.GetNamedObjects());
            context.PushCanvas(canvas);
            ISvgNodeRenderer root = new PdfRootSvgNodeRenderer(topSvgRenderer);

            root.Draw(context);
            return(pdfForm);
        }
Exemplo n.º 15
0
        protected internal override void DoDraw(SvgDrawContext context)
        {
            if (this.attributesAndStyles != null && this.attributesAndStyles.ContainsKey(SvgConstants.Attributes.TEXT_CONTENT
                                                                                         ))
            {
                PdfCanvas      currentCanvas    = context.GetCurrentCanvas();
                String         xRawValue        = this.attributesAndStyles.Get(SvgConstants.Attributes.X);
                String         yRawValue        = this.attributesAndStyles.Get(SvgConstants.Attributes.Y);
                String         fontSizeRawValue = this.attributesAndStyles.Get(SvgConstants.Attributes.FONT_SIZE);
                IList <String> xValuesList      = SvgCssUtils.SplitValueList(xRawValue);
                IList <String> yValuesList      = SvgCssUtils.SplitValueList(yRawValue);
                float          x        = 0f;
                float          y        = 0f;
                float          fontSize = 0f;
                if (fontSizeRawValue != null && !String.IsNullOrEmpty(fontSizeRawValue))
                {
                    fontSize = CssUtils.ParseAbsoluteLength(fontSizeRawValue, CommonCssConstants.PT);
                }
                if (!xValuesList.IsEmpty())
                {
                    x = CssUtils.ParseAbsoluteLength(xValuesList[0]);
                }
                if (!yValuesList.IsEmpty())
                {
                    y = CssUtils.ParseAbsoluteLength(yValuesList[0]);
                }
                currentCanvas.BeginText();
                FontProvider provider  = context.GetFontProvider();
                FontSet      tempFonts = context.GetTempFonts();
                PdfFont      font      = null;
                if (!provider.GetFontSet().IsEmpty() || (tempFonts != null && !tempFonts.IsEmpty()))
                {
                    String fontFamily = this.attributesAndStyles.Get(SvgConstants.Attributes.FONT_FAMILY);
                    String fontWeight = this.attributesAndStyles.Get(SvgConstants.Attributes.FONT_WEIGHT);
                    String fontStyle  = this.attributesAndStyles.Get(SvgConstants.Attributes.FONT_STYLE);
                    fontFamily = fontFamily != null?fontFamily.Trim() : "";

                    FontInfo fontInfo = ResolveFontName(fontFamily, fontWeight, fontStyle, provider, tempFonts);
                    font = provider.GetPdfFont(fontInfo, tempFonts);
                }
                if (font == null)
                {
                    try {
                        // TODO (DEVSIX-2057)
                        // TODO each call of createFont() create a new instance of PdfFont.
                        // TODO FontProvider shall be used instead.
                        font = PdfFontFactory.CreateFont();
                    }
                    catch (System.IO.IOException e) {
                        throw new SvgProcessingException(SvgLogMessageConstant.FONT_NOT_FOUND, e);
                    }
                }
                currentCanvas.SetFontAndSize(font, fontSize);
                //Current transformation matrix results in the character glyphs being mirrored, correct with inverse tf
                currentCanvas.SetTextMatrix(1, 0, 0, -1, x, y);
                currentCanvas.SetColor(ColorConstants.BLACK, true);
                currentCanvas.ShowText(this.attributesAndStyles.Get(SvgConstants.Attributes.TEXT_CONTENT));
                currentCanvas.EndText();
            }
        }
Exemplo n.º 16
0
        protected internal override void DoDraw(SvgDrawContext context)
        {
            PdfCanvas canvas = context.GetCurrentCanvas();

            canvas.WriteLiteral("% line\n");
            if (attributesAndStyles.Count > 0)
            {
                float x1 = 0f;
                float y1 = 0f;
                float x2 = 0f;
                float y2 = 0f;
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.X1))
                {
                    x1 = GetAttribute(attributesAndStyles, SvgConstants.Attributes.X1);
                }
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.Y1))
                {
                    y1 = GetAttribute(attributesAndStyles, SvgConstants.Attributes.Y1);
                }
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.X2))
                {
                    x2 = GetAttribute(attributesAndStyles, SvgConstants.Attributes.X2);
                }
                if (attributesAndStyles.ContainsKey(SvgConstants.Attributes.Y2))
                {
                    y2 = GetAttribute(attributesAndStyles, SvgConstants.Attributes.Y2);
                }
                canvas.MoveTo(x1, y1).LineTo(x2, y2);
            }
        }
Exemplo n.º 17
0
        private Point[] GetCoordinates(SvgDrawContext context, bool isObjectBoundingBox)
        {
            Point start;
            Point end;

            if (isObjectBoundingBox)
            {
                start = new Point(GetCoordinateForObjectBoundingBox(SvgConstants.Attributes.X1, 0), GetCoordinateForObjectBoundingBox
                                      (SvgConstants.Attributes.Y1, 0));
                end = new Point(GetCoordinateForObjectBoundingBox(SvgConstants.Attributes.X2, 1), GetCoordinateForObjectBoundingBox
                                    (SvgConstants.Attributes.Y2, 0));
            }
            else
            {
                Rectangle currentViewPort = context.GetCurrentViewPort();
                double    x      = currentViewPort.GetX();
                double    y      = currentViewPort.GetY();
                double    width  = currentViewPort.GetWidth();
                double    height = currentViewPort.GetHeight();
                float     em     = GetCurrentFontSize();
                float     rem    = context.GetRemValue();
                start = new Point(GetCoordinateForUserSpaceOnUse(SvgConstants.Attributes.X1, x, x, width, em, rem), GetCoordinateForUserSpaceOnUse
                                      (SvgConstants.Attributes.Y1, y, y, height, em, rem));
                end = new Point(GetCoordinateForUserSpaceOnUse(SvgConstants.Attributes.X2, x + width, x, width, em, rem),
                                GetCoordinateForUserSpaceOnUse(SvgConstants.Attributes.Y2, y, y, height, em, rem));
            }
            return(new Point[] { start, end });
        }
 protected internal override Rectangle GetObjectBoundingBox(SvgDrawContext context)
 {
     SetPoints(GetAttribute(SvgConstants.Attributes.POINTS));
     if (points.Count > 1)
     {
         Point  firstPoint = points[0];
         double minX       = firstPoint.GetX();
         double minY       = firstPoint.GetY();
         double maxX       = minX;
         double maxY       = minY;
         for (int i = 1; i < points.Count; ++i)
         {
             Point  current  = points[i];
             double currentX = current.GetX();
             minX = Math.Min(minX, currentX);
             maxX = Math.Max(maxX, currentX);
             double currentY = current.GetY();
             minY = Math.Min(minY, currentY);
             maxY = Math.Max(maxY, currentY);
         }
         double width  = maxX - minX;
         double height = maxY - minY;
         return(new Rectangle((float)minX, (float)minY, (float)width, (float)height));
     }
     else
     {
         return(base.GetObjectBoundingBox(context));
     }
 }
Exemplo n.º 19
0
        public virtual void LineRendererTest()
        {
            String      filename = "lineSvgRendererTest.pdf";
            PdfDocument doc      = new PdfDocument(new PdfWriter(destinationFolder + filename));

            doc.AddNewPage();
            IDictionary <String, String> lineProperties = new Dictionary <String, String>();

            lineProperties.Put("x1", "100");
            lineProperties.Put("y1", "800");
            lineProperties.Put("x2", "300");
            lineProperties.Put("y2", "800");
            lineProperties.Put("stroke", "green");
            lineProperties.Put("stroke-width", "25");
            LineSvgNodeRenderer root = new LineSvgNodeRenderer();

            root.SetAttributesAndStyles(lineProperties);
            SvgDrawContext context = new SvgDrawContext(null, null);
            PdfCanvas      cv      = new PdfCanvas(doc, 1);

            context.PushCanvas(cv);
            root.Draw(context);
            doc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + filename, sourceFolder
                                                                             + "cmp_" + filename, destinationFolder, "diff_"));
        }
Exemplo n.º 20
0
 /// <summary>Cleans up the SvgDrawContext by removing the current viewport and by popping the current canvas.</summary>
 /// <param name="context">context to clean</param>
 private void CleanUp(SvgDrawContext context)
 {
     if (GetParent() != null)
     {
         context.RemoveCurrentViewPort();
     }
     context.PopCanvas();
 }
Exemplo n.º 21
0
        /// <summary>Applies a clipping operation based on the view port.</summary>
        /// <param name="context">the svg draw context</param>
        private void ApplyViewportClip(SvgDrawContext context)
        {
            PdfCanvas currentCanvas = context.GetCurrentCanvas();

            currentCanvas.Rectangle(context.GetCurrentViewPort());
            currentCanvas.Clip();
            currentCanvas.EndPath();
        }
 public override void Draw(SvgDrawContext context)
 {
     if (processed)
     {
         throw new SvgProcessingException("Cannot process svg renderer twice");
     }
     processed = true;
 }
        /// <summary>Calculate the transformation for the viewport based on the context.</summary>
        /// <remarks>
        /// Calculate the transformation for the viewport based on the context. Only used by elements that can create
        /// viewports
        /// </remarks>
        /// <param name="context">the SVG draw context</param>
        /// <returns>the transformation that needs to be applied to this renderer</returns>
        internal virtual AffineTransform CalculateViewPortTranslation(SvgDrawContext context)
        {
            Rectangle       viewPort = context.GetCurrentViewPort();
            AffineTransform transform;

            transform = AffineTransform.GetTranslateInstance(viewPort.GetX(), viewPort.GetY());
            return(transform);
        }
 /// <summary>Operations to be performed after drawing the element.</summary>
 /// <remarks>
 /// Operations to be performed after drawing the element.
 /// This includes filling, stroking.
 /// </remarks>
 /// <param name="context">the svg draw context</param>
 internal virtual void PostDraw(SvgDrawContext context)
 {
     if (this.attributesAndStyles != null)
     {
         PdfCanvas currentCanvas = context.GetCurrentCanvas();
         // fill-rule
         if (partOfClipPath)
         {
             if (SvgConstants.Values.FILL_RULE_EVEN_ODD.EqualsIgnoreCase(this.GetAttribute(SvgConstants.Attributes.CLIP_RULE
                                                                                           )))
             {
                 currentCanvas.EoClip();
             }
             else
             {
                 currentCanvas.Clip();
             }
             currentCanvas.NewPath();
         }
         else
         {
             if (doFill && CanElementFill())
             {
                 String fillRuleRawValue = GetAttribute(SvgConstants.Attributes.FILL_RULE);
                 if (SvgConstants.Values.FILL_RULE_EVEN_ODD.EqualsIgnoreCase(fillRuleRawValue))
                 {
                     if (doStroke)
                     {
                         currentCanvas.EoFillStroke();
                     }
                     else
                     {
                         currentCanvas.EoFill();
                     }
                 }
                 else
                 {
                     if (doStroke)
                     {
                         currentCanvas.FillStroke();
                     }
                     else
                     {
                         currentCanvas.Fill();
                     }
                 }
             }
             else
             {
                 if (doStroke)
                 {
                     currentCanvas.Stroke();
                 }
             }
             currentCanvas.ClosePath();
         }
     }
 }
Exemplo n.º 25
0
        protected internal override void DoDraw(SvgDrawContext context)
        {
            PdfCanvas cv = context.GetCurrentCanvas();

            cv.WriteLiteral("% rect\n");
            SetParameters();
            bool singleValuePresent = (rxPresent && !ryPresent) || (!rxPresent && ryPresent);

            if (!rxPresent && !ryPresent)
            {
                cv.Rectangle(x, y, width, height);
            }
            else
            {
                if (singleValuePresent)
                {
                    cv.WriteLiteral("% circle rounded rect\n");
                    // only look for radius in case of circular rounding
                    float radius = FindCircularRadius(rx, ry, width, height);
                    cv.RoundRectangle(x, y, width, height, radius);
                }
                else
                {
                    cv.WriteLiteral("% ellipse rounded rect\n");
                    // TODO (DEVSIX-1878): this should actually be refactored into PdfCanvas.roundRectangle()

                    /*
                     *
                     * y+h    ->    ____________________________
                     * /                            \
                     * /                              \
                     * y+h-ry -> /                                \
                     |                                |
                     |                                |
                     |                                |
                     |                                |
                     | y+ry   -> \                                /
                     \                              /
                     \ y      ->   \____________________________/
                     \ ^  ^                          ^  ^
                     \ x  x+rx                  x+w-rx  x+w
                     \
                     */
                    cv.MoveTo(x + rx, y);
                    cv.LineTo(x + width - rx, y);
                    Arc(x + width - 2 * rx, y, x + width, y + 2 * ry, -90, 90, cv);
                    cv.LineTo(x + width, y + height - ry);
                    Arc(x + width, y + height - 2 * ry, x + width - 2 * rx, y + height, 0, 90, cv);
                    cv.LineTo(x + rx, y + height);
                    Arc(x + 2 * rx, y + height, x, y + height - 2 * ry, 90, 90, cv);
                    cv.LineTo(x, y + ry);
                    Arc(x, y + 2 * ry, x + 2 * rx, y, 180, 90, cv);
                    cv.ClosePath();
                }
            }
        }
        protected internal override void DoDraw(SvgDrawContext context)
        {
            PdfCanvas canvas = context.GetCurrentCanvas();

            canvas.WriteLiteral("% line\n");
            if (SetParameterss())
            {
                canvas.MoveTo(x1, y1).LineTo(x2, y2);
            }
        }
        public virtual void Draw(SvgDrawContext context)
        {
            //Set viewport and transformation for pdf-context
            context.AddViewPort(this.CalculateViewPort(context));
            PdfCanvas currentCanvas = context.GetCurrentCanvas();

            currentCanvas.ConcatMatrix(this.CalculateTransformation(context));
            currentCanvas.WriteLiteral("% svg root\n");
            subTreeRoot.Draw(context);
        }
        public virtual void SetupDrawContextAndCanvas()
        {
            sdc = new SvgDrawContext(new ResourceResolver(""), new FontProvider());
            // set compression to none, in case you want to write to disk and inspect the created document
            PdfWriter   writer = new PdfWriter(new MemoryStream(), new WriterProperties().SetCompressionLevel(0));
            PdfDocument doc    = new PdfDocument(writer);

            cv = new PdfCanvas(doc.AddNewPage());
            sdc.PushCanvas(cv);
        }
Exemplo n.º 29
0
        protected internal override void DoDraw(SvgDrawContext context)
        {
            PdfCanvas canvas = context.GetCurrentCanvas();

            canvas.WriteLiteral("% path\n");
            currentPoint = new Point(0, 0);
            foreach (IPathShape item in GetShapes())
            {
                item.Draw(canvas);
            }
        }
Exemplo n.º 30
0
        private void ApplyViewportTranslationCorrection(SvgDrawContext context)
        {
            PdfCanvas       currentCanvas = context.GetCurrentCanvas();
            AffineTransform tf            = this.CalculateViewPortTranslation(context);

            if (!tf.IsIdentity() && SvgConstants.Values.NONE.Equals(this.GetAttribute(SvgConstants.Attributes.PRESERVE_ASPECT_RATIO
                                                                                      )))
            {
                currentCanvas.ConcatMatrix(tf);
            }
        }