/// <summary>
        /// Render text.
        /// </summary>
        /// <param name="renderInfo">render text information</param>
        public void RenderText(TextRenderInfo renderInfo)
        {
            var segment  = renderInfo.GetBaseline();
            var location = new TextChunk(renderInfo.GetText(), segment.GetStartPoint(), segment.GetEndPoint(), renderInfo.GetSingleSpaceWidth())
            {
                PosLeft     = renderInfo.GetDescentLine().GetStartPoint()[Vector.I1],
                PosRight    = renderInfo.GetAscentLine().GetEndPoint()[Vector.I1],
                PosBottom   = renderInfo.GetDescentLine().GetStartPoint()[Vector.I2],
                PosTop      = renderInfo.GetAscentLine().GetEndPoint()[Vector.I2],
                FillColor   = renderInfo.GetFillColor(),
                StrokeColor = renderInfo.GetStrokeColor(),
                Font        = renderInfo.GetFont()
            };

            // Chunk Font Size: (Height)
            location.CurFontSize = location.PosTop - segment.GetStartPoint()[Vector.I2];

            // Use Font name  and Size as Key in the SortedList
            var strKey = renderInfo.GetFont().PostscriptFontName + location.CurFontSize;

            // Add this font to ThisPdfDocFonts SortedList if it's not already present
            if (!_thisPdfDocFonts.ContainsKey(strKey))
            {
                _thisPdfDocFonts.Add(strKey, renderInfo.GetFont());
            }

            // Store the SortedList index in this Chunk, so we can get it later
            location.FontIndex = _thisPdfDocFonts.IndexOfKey(strKey);

            _locationalResult.Add(location);
        }
Exemplo n.º 2
0
        public virtual void RenderText(TextRenderInfo renderInfo)
        {
            LineSegment segment  = renderInfo.GetBaseline();
            TextChunk   location = new TextChunk(renderInfo.GetText(), segment.GetStartPoint(), segment.GetEndPoint(), renderInfo.GetSingleSpaceWidth());

            var _with1 = location;

            //Chunk Location:
            //			Debug.Print(renderInfo.GetText);
            _with1.PosLeft   = renderInfo.GetDescentLine().GetStartPoint()[Vector.I1];
            _with1.PosRight  = renderInfo.GetAscentLine().GetEndPoint()[Vector.I1];
            _with1.PosBottom = renderInfo.GetDescentLine().GetStartPoint()[Vector.I2];
            _with1.PosTop    = renderInfo.GetAscentLine().GetEndPoint()[Vector.I2];
            //Chunk Font Size: (Height)
            _with1.curFontSize = _with1.PosTop - segment.GetStartPoint()[Vector.I2];
            //Use Font name  and Size as Key in the SortedList
            string StrKey = renderInfo.GetFont().PostscriptFontName + _with1.curFontSize.ToString();

            //Add this font to ThisPdfDocFonts SortedList if it's not already present
            if (!ThisPdfDocFonts.ContainsKey(StrKey))
            {
                ThisPdfDocFonts.Add(StrKey, renderInfo.GetFont());
            }
            //Store the SortedList index in this Chunk, so we can get it later
            _with1.FontIndex = ThisPdfDocFonts.IndexOfKey(StrKey);
            locationalResult.Add(location);
        }
        /// <summary>
        /// Obtiene el texto contenido en un pdf en función del parámetro facilitado.
        /// </summary>
        /// <param name="renderInfo">Información para la obtención del texto.</param>
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);

            LineSegment segment = renderInfo.GetBaseline();

            if (renderInfo.GetRise() != 0)
            {
                // remove the rise from the baseline - we do this because the text from a
                // super /subscript render operations should probably be considered as part
                // of the baseline of the text the super/sub is relative to
                Matrix riseOffsetTransform = new Matrix(0, -renderInfo.GetRise());
                segment = segment.TransformBy(riseOffsetTransform);
            }

            var ll = renderInfo.GetDescentLine().GetStartPoint();         // lower left
            var ur = renderInfo.GetAscentLine().GetEndPoint();            // upper right

            string text = renderInfo.GetText();                           //mirando

            string fillColor   = renderInfo.GetFillColor()?.ToString();   // Color del texto.
            string strokeColor = renderInfo.GetStrokeColor()?.ToString(); // Color del texto.

            Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
            Vector topRight    = renderInfo.GetAscentLine().GetEndPoint();

            iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
            double fontSize = Math.Round(rect.Height);                  // Tamaño de la fuente a partir del rectángulo extraído.

            string fontName = renderInfo.GetFont()?.PostscriptFontName; //Nombre de la fuente.

            //base._PdfTextChunks.Add(new PdfTextChunk(renderInfo.GetText(), base.tclStrat.CreateLocation(renderInfo, segment), ll, ur));
            _PdfColorFontTextChunks.Add(new PdfColorFontTextChunk(renderInfo.GetText(), base.tclStrat.CreateLocation(renderInfo, segment), ll, ur, fillColor, strokeColor, fontName, fontSize));
        }
Exemplo n.º 4
0
        public override void EventOccurred(IEventData data, EventType type)
        {
            if (!type.Equals(EventType.RENDER_TEXT))
            {
                return;
            }

            TextRenderInfo renderInfo = (TextRenderInfo)data;

            string curFont     = renderInfo.GetFont().GetFontProgram().ToString();
            float  curFontSize = renderInfo.GetFontSize();

            IList <TextRenderInfo> text = renderInfo.GetCharacterRenderInfos();

            foreach (TextRenderInfo t in text)
            {
                string letter  = t.GetText();
                Vector l_start = t.GetBaseline().GetStartPoint(),
                       l_end   = t.GetAscentLine().GetEndPoint();

                Rectangle l_rect = new Rectangle(l_start.Get(0), l_start.Get(1),
                                                 l_end.Get(0) - l_start.Get(0), l_end.Get(1) - l_start.Get(1));

                if (letter != " " && !letter.Contains(' '))
                {
                    TextResult.Add(new TextChunk()
                    {
                        Text       = letter,
                        Rect       = l_rect,
                        FontFamily = curFont,
                        FontSize   = curFontSize,
                    });
                }
            }
        }
    public override bool AllowText(TextRenderInfo renderInfo)
    {
        DocumentFont  font     = renderInfo.GetFont();
        PdfDictionary fontDict = font.FontDictionary;
        PdfName       subType  = fontDict.GetAsName(PdfName.SUBTYPE);

        if (PdfName.TYPE0.Equals(subType))
        {
            PdfArray      descendantFonts = fontDict.GetAsArray(PdfName.DESCENDANTFONTS);
            PdfDictionary descendantFont  = descendantFonts[0] as PdfDictionary;
            PdfDictionary fontDescriptor  = descendantFont.GetAsDict(PdfName.FONTDESCRIPTOR);
            PdfStream     fontStream      = fontDescriptor.GetAsStream(PdfName.FONTFILE2);
            byte[]        fontData        = PdfReader.GetStreamBytes((PRStream)fontStream);
            MemoryStream  dataStream      = new MemoryStream(fontData);
            dataStream.Position = 0;
            MemoryPackage        memoryPackage = new MemoryPackage();
            Uri                  uri           = memoryPackage.CreatePart(dataStream);
            GlyphTypeface        glyphTypeface = new GlyphTypeface(uri);
            ICollection <string> names         = glyphTypeface.FamilyNames.Values;
            return(names.Where(name => name.Contains("Arial")).Count() > 0);
        }
        else
        {
            // analogous code for other font subtypes
            return(false);
        }
    }
Exemplo n.º 6
0
 public LineInfo(TextRenderInfo info, string text)
 {
     this.Text    = text;
     this.Font    = info.GetFont().GetFontProgram().GetFontNames();
     this.Object  = info.GetPdfString();
     this.Ascent  = info.GetAscentLine();
     this.Descent = info.GetDescentLine();
 }
    public override void RenderText(TextRenderInfo renderInfo)
    {
        LineSegment segment  = renderInfo.GetBaseline();
        TextChunk   location = new TextChunk(renderInfo.GetText(), segment.GetStartPoint(), segment.GetEndPoint(), renderInfo.GetSingleSpaceWidth());

        location.PosLeft     = renderInfo.GetDescentLine().GetStartPoint()[Vector.I1];
        location.PosRight    = renderInfo.GetAscentLine().GetEndPoint()[Vector.I1];
        location.PosBottom   = renderInfo.GetDescentLine().GetStartPoint()[Vector.I2];
        location.PosTop      = renderInfo.GetAscentLine().GetEndPoint()[Vector.I2];
        location.curFontSize = location.PosTop - segment.GetStartPoint()[Vector.I2];
        string StrKey = renderInfo.GetFont().PostscriptFontName + location.curFontSize.ToString();

        if (!ThisPdfDocFonts.ContainsKey(StrKey))
        {
            ThisPdfDocFonts.Add(StrKey, renderInfo.GetFont());
        }
        location.FontIndex = ThisPdfDocFonts.IndexOfKey(StrKey);
        locationalResult.Add(location);
    }
Exemplo n.º 8
0
            public override void EventOccurred(IEventData data, EventType type)
            {
                base.EventOccurred(data, type);

                TextRenderInfo tri = data as TextRenderInfo;

                //if (type != EventType.RENDER_TEXT)
                if (tri == null)
                {
                    return;
                }

                PdfFont font     = tri.GetFont();//it has been checked that it returns the same font object.
                float   fontSize = Math.Abs/*sometimes it is negative in iText7*/ (tri.GetFontSize());
                //if (font.GetAscent("I", fontSize) == 0)
                //    fontSize = 0;

                List <CharBox>         cbs  = new List <CharBox>();
                IList <TextRenderInfo> cris = tri.GetCharacterRenderInfos();

                foreach (TextRenderInfo cri in cris)
                {
                    Vector baseLeft = cri.GetBaseline().GetStartPoint();
                    Vector topRight = cri.GetAscentLine().GetEndPoint();
                    //float rise = cri.GetRise();
                    //if (rise != 0)
                    //    rise = rise;
                    float fontHeightFromBaseLine = topRight.Get(Vector.I2) - baseLeft.Get(Vector.I2);
                    //if (fontSize > 0)
                    //{
                    //    float fontHeightFromBaseLine2 = fontSize * 0.75f/*(?)convertion from PX to PT*/;//!!!this calculation is heuristic and coincides with cri.GetAscentLine().GetEndPoint().Get(Vector.I2) - bottomLeft.Get(Vector.I2) in iText5
                    //    if (fontHeightFromBaseLine > fontHeightFromBaseLine2)
                    //        fontHeightFromBaseLine = fontHeightFromBaseLine2;
                    //}
                    float x = baseLeft.Get(Vector.I1);
                    //float y = topRight.Get(Vector.I2);
                    CharBox cb = new CharBox
                    {
                        Char = cri.GetText(),
                        R    = new System.Drawing.RectangleF
                        {
                            X     = x - pageSize.X,
                            Y     = pageSize.Height + pageSize.Y - baseLeft.Get(Vector.I2) - fontHeightFromBaseLine,//(!)basic positioning point is char's baseLine, not ascentLine
                            Width = topRight.Get(Vector.I1) - x,
                            //Height = y - bottomLeft.Get(Vector.I2)// + d,
                            Height = fontHeightFromBaseLine
                        },
                        Font     = font,
                        FontSize = fontSize
                    };
                    cbs.Add(cb);
                }
                CharBoxs.AddRange(cbs);
            }
Exemplo n.º 9
0
        private PdfFontDetails GetFont(TextRenderInfo textRenderInfo)
        {
            var pdfFont = textRenderInfo.GetFont();

            if (!fonts.TryGetValue(pdfFont, out var font))
            {
                font = FontManager.Instance.CreateFont(pdfFont);
                fonts.Add(pdfFont, font);
            }

            return(font);
        }
Exemplo n.º 10
0
        public virtual void RenderText(TextRenderInfo renderInfo)
        {
            LineSegment baseline     = renderInfo.GetBaseline();
            TextChunk   renderedItem = new TextChunk(renderInfo.GetText(), baseline.GetStartPoint(), baseline.GetEndPoint(), renderInfo.GetSingleSpaceWidth());
            TextChunk   foundChunk   = renderedItem;

            Debug.Print(renderInfo.GetText());
            foundChunk.PosLeft     = renderInfo.GetDescentLine().GetStartPoint()[0];
            foundChunk.PosRight    = renderInfo.GetAscentLine().GetEndPoint()[0];
            foundChunk.PosBottom   = renderInfo.GetDescentLine().GetStartPoint()[1];
            foundChunk.PosTop      = renderInfo.GetAscentLine().GetEndPoint()[1];
            foundChunk.curFontSize = foundChunk.PosTop - baseline.GetStartPoint()[1];
            string key = renderInfo.GetFont().PostscriptFontName + foundChunk.curFontSize.ToString();

            if (!this.ThisPdfDocFonts.ContainsKey(key))
            {
                this.ThisPdfDocFonts.Add(key, renderInfo.GetFont());
            }
            foundChunk.FontIndex = this.ThisPdfDocFonts.IndexOfKey(key);
            foundChunk           = null;
            this.locationalResult.Add(renderedItem);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates a TextStyle object by getting the font name and font size
        /// from a TextRenderInfo object.
        /// </summary>
        /// <param name="textRenderInfo">Object that contains info about a text snippet</param>
        public TextStyle(TextRenderInfo textRenderInfo)
        {
            String font = textRenderInfo.GetFont().FullFontName[0][3];

            if (font.Contains("+"))
            {
                font = font.Substring(font.IndexOf("+") + 1, font.Length - font.IndexOf("+") - 1);
            }
            if (font.Contains("-"))
            {
                font = font.Substring(0, font.IndexOf("-"));
            }
            this.fontName = font;
            this.fontSize = textRenderInfo.GetAscentLine().GetStartPoint()[1] - textRenderInfo.GetDescentLine().GetStartPoint()[1];
        }
Exemplo n.º 12
0
            public override bool Accept(IEventData data, EventType type)
            {
                if (type.Equals(EventType.RENDER_TEXT))
                {
                    TextRenderInfo renderInfo = (TextRenderInfo)data;
                    PdfFont        font       = renderInfo.GetFont();
                    if (null != font)
                    {
                        String fontName = font.GetFontProgram().GetFontNames().GetFontName();
                        return(fontName.EndsWith("Bold") || fontName.EndsWith("Oblique"));
                    }
                }

                return(false);
            }
Exemplo n.º 13
0
        public void RenderText(TextRenderInfo renderInfo)
        {
            var curFont = renderInfo.GetFont().PostscriptFontName;

            //Check if faux bold is used
            if (renderInfo.GetTextRenderMode() == (int)TextRenderMode.FillThenStrokeText)
            {
                curFont += "-Bold";
            }

            //This code assumes that if the baseline changes then we're on a newline
            var curBaseline = renderInfo.GetBaseline().GetStartPoint();
            var topRight    = renderInfo.GetAscentLine().GetEndPoint();
            var rect        = new Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1],
                                            topRight[Vector.I2]);
            var curFontSize = rect.Height;

            //See if something has changed, either the baseline, the font or the font size
            if (lastBaseLine == null || curBaseline[Vector.I2] != lastBaseLine[Vector.I2] ||
                curFontSize != lastFontSize || curFont != lastFont)
            {
                //if we've put down at least one span tag close it
                if (lastBaseLine != null)
                {
                    result.AppendLine("</span>");
                }

                //If the baseline has changed then insert a line break
                if (lastBaseLine != null && curBaseline[Vector.I2] != lastBaseLine[Vector.I2])
                {
                    result.AppendLine("<br />");
                }

                //Create an HTML tag with appropriate styles
                result.AppendFormat("<span>");
            }

            //Append the current text
            result.Append(renderInfo.GetText());

            //Set currently used properties
            lastBaseLine = curBaseline;
            lastFontSize = curFontSize;
            lastFont     = curFont;
        }
Exemplo n.º 14
0
        public override void EventOccurred(IEventData data, EventType type)
        {
            if (!type.Equals(EventType.RENDER_TEXT))
            {
                return;
            }

            TextRenderInfo renderInfo = (TextRenderInfo)data;

            string curFont = renderInfo.GetFont().GetFontProgram().ToString();

            float curFontSize = renderInfo.GetFontSize();

            IList <TextRenderInfo> text = renderInfo.GetCharacterRenderInfos();

            foreach (TextRenderInfo t in text)
            {
                string letter = t.GetText();

                Vector letterStart = t.GetDescentLine().GetStartPoint();
                Vector letterEnd   = t.GetAscentLine().GetEndPoint();

                if (letter != " " && !letter.Contains(" "))
                {
                    TextChar c = new TextChar();
                    chars.Add(c);

                    c.text = letter;
                    c.x1   = letterStart.Get(0);
                    c.x2   = letterEnd.Get(0);

                    c.y1 = letterStart.Get(1);
                    c.y2 = letterEnd.Get(1);

                    if (c.y1 > c.y2)
                    {
                        c.y1 = letterEnd.Get(1);
                        c.y2 = letterStart.Get(1);
                    }

                    c.fontFamily = curFont;
                    c.fontSize   = curFontSize;
                }
            }
        }
Exemplo n.º 15
0
        public void RenderText(TextRenderInfo renderInfo)
        {
            var a           = renderInfo.GetBaseline();
            var ascentLine  = renderInfo.GetAscentLine();
            var a2          = renderInfo.GetSingleSpaceWidth();
            var descentLine = renderInfo.GetDescentLine();
            var a4          = renderInfo.GetUnscaledBaseline();
            var a5          = renderInfo.GetFont();
            var a6          = renderInfo.GetRise();
            var a7          = renderInfo.GetText();

            bool        flag1      = this.result.Length == 0;
            bool        flag2      = false;
            LineSegment baseline   = renderInfo.GetBaseline();
            Vector      startPoint = baseline.GetStartPoint();
            Vector      endPoint   = baseline.GetEndPoint();

            if (!flag1)
            {
                Vector v         = startPoint;
                Vector lastStart = this.lastStart;
                Vector lastEnd   = this.lastEnd;
                if ((double)(lastEnd.Subtract(lastStart).Cross(lastStart.Subtract(v)).LengthSquared / lastEnd.Subtract(lastStart).LengthSquared) > 1.0)
                {
                    flag2 = true;
                }
            }

            RectangleF rectCurrent = getRenderRectangleF(renderInfo);


            if (flag2)
            {
                this.AppendTextChunk('\n');
            }
            //else if (!flag1 && this.result[this.result.Length - 1] != ' ' && (renderInfo.GetText().Length > 0 && renderInfo.GetText()[0] != ' ') && (double)this.lastEnd.Subtract(startPoint).Length > (double)renderInfo.GetSingleSpaceWidth() / 2.0)
            //    this.AppendTextChunk(' ');
            this.AppendTextChunk(renderInfo.GetText());
            this.lastStart = startPoint;
            this.lastEnd   = endPoint;
        }
Exemplo n.º 16
0
        public void RenderText(TextRenderInfo renderInfo)
        {
            var block = new TextBlock();

            block.FontName = renderInfo.GetFont().PostscriptFontName;
            // Check if faux bold is used
            if ((renderInfo.GetTextRenderMode() == (int)TextRenderMode.FillThenStrokeText))
            {
                block.ForceBold = true;
            }

            var curBaseline = renderInfo.GetBaseline().GetStartPoint();
            var topRight    = renderInfo.GetAscentLine().GetEndPoint();
            var rect        = MakeRectangle(curBaseline, topRight);

            //block.FontSize = rect.Height;
            block.FontSize  = rect.Height * 1.33f;
            block.Rectangle = rect;

            block.Value = renderInfo.GetText();

            blocks.Add(block);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Obtiene el texto contenido en un pdf en función del parámetro facilitado.
        /// </summary>
        /// <param name="renderInfo">Información para la obtención del texto.</param>
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);

            LineSegment segment = renderInfo.GetBaseline();

            if (renderInfo.GetRise() != 0)
            {
                // remove the rise from the baseline - we do this because the text from a
                // super /subscript render operations should probably be considered as part
                // of the baseline of the text the super/sub is relative to
                Matrix riseOffsetTransform = new Matrix(0, -renderInfo.GetRise());
                segment = segment.TransformBy(riseOffsetTransform);
            }

            string fontName      = renderInfo.GetFont().PostscriptFontName; // Nombre de la fuente del texto.
            string textoExtraido = renderInfo.GetText();                    // Grupo de texto sobre el que estamos iterando.

            var ll = renderInfo.GetDescentLine().GetStartPoint();           // lower left
            var ur = renderInfo.GetAscentLine().GetEndPoint();              // upper right

            _PdfTextChunks.Add(new PdfTextChunk(renderInfo.GetText(), tclStrat.CreateLocation(renderInfo, segment), ll, ur));
        }
Exemplo n.º 18
0
        //Automatically called for each chunk of text in the PDF
        public override void RenderText(TextRenderInfo wholeRenderInfo)
        {
            base.RenderText(wholeRenderInfo);
            GraphicsState gs = (GraphicsState)GsField.GetValue(wholeRenderInfo);

            myChunks.Add(new SizeAndTextAndFont(gs.FontSize, wholeRenderInfo.GetText(), wholeRenderInfo.GetFont().PostscriptFontName));
        }
Exemplo n.º 19
0
        public override void RenderText(TextRenderInfo renderInfo)
        {
            DocumentFont font = renderInfo.GetFont();

            byte[]        bytes   = font.ConvertToBytes(renderInfo.GetText());
            StringBuilder partStr = new StringBuilder();

            //PdfDictionary dict = font.FontDictionary;
            //PdfDictionary encoding = dict.GetAsDict(PdfName.ENCODING);
            //if (encoding != null)
            {
                string renderTxt = renderInfo.GetText();
                foreach (char c in renderTxt)
                {
                    string name = c.ToString();
                    if (CharMaps.ContainsKey(name))
                    {
                        string chat = CharMaps[name];
                        partStr.Append(chat);
                    }
                    else
                    {
                        /*
                         * String s = name.ToString().Substring(4);
                         * byte[] nameBytes = this.HexStringToBytes(s);
                         * string text = Encoding.BigEndianUnicode.GetString(nameBytes);
                         * partStr.Append(text);
                         */
                        partStr.Append(name);
                    }
                }

                /*
                 * PdfArray diffs = encoding.GetAsArray(PdfName.DIFFERENCES);
                 * StringBuilder builder = new StringBuilder();
                 * foreach (byte b in renderInfo.PdfString.GetBytes())
                 * {
                 *  string name = "";
                 *  try
                 *  {
                 *      name = diffs.GetAsName((char)b).ToString();
                 *  }
                 *  catch (Exception ex)
                 *  {
                 *      //throw ex;
                 *  }
                 *  if (CharMaps.ContainsKey(name))
                 *  {
                 *      string chat = CharMaps[name];
                 *      //partStr.Append(chat);
                 *  }
                 *  else
                 *  {
                 *      //String s = name.ToString().Substring(4);
                 *      //byte[] nameBytes = this.HexStringToBytes(s);
                 *      //string text = Encoding.BigEndianUnicode.GetString(nameBytes);
                 *      //partStr.Append(text);
                 *  }
                 * }
                 */
            }
            //else
            //{
            //    partStr.Append(renderInfo.GetText());
            //}

            if (partStr.ToString().Trim().Length > 0)
            {
                LineSegment segment    = renderInfo.GetAscentLine();
                Vector      startPoint = segment.GetStartPoint();
                if (LastEndPoint != null)
                {
                    int      charCount    = partStr.Length;
                    float    singleWidth  = renderInfo.GetSingleSpaceWidth();// segment.GetEndPoint().Subtract(segment.GetStartPoint()).Length / (float)charCount;
                    string[] pStartStrs   = startPoint.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    string[] pLastEndStrs = LastEndPoint.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    float    verticalSpan = Math.Abs(float.Parse(pStartStrs[1]) - float.Parse(pLastEndStrs[1]));
                    if (verticalSpan > renderInfo.GetSingleSpaceWidth())
                    {
                        if (verticalSpan > 4 * renderInfo.GetSingleSpaceWidth())
                        {
                            TextBuilder.Append("\r\n\r\n");
                        }
                        else
                        {
                            TextBuilder.Append("\r\n");
                        }
                    }
                    else
                    {
                        Vector spanVector = startPoint.Subtract(LastEndPoint);
                        float  span       = spanVector.Length;
                        if (span > singleWidth / 2f)
                        {
                            TextBuilder.Append(" ");
                        }
                    }
                }
                TextBuilder.Append(partStr.ToString());
                LastEndPoint = segment.GetEndPoint();
            }

            base.RenderText(renderInfo);
        }
Exemplo n.º 20
0
        public override void EventOccurred(IEventData data, EventType type)
        {
            if (!type.Equals(EventType.RENDER_TEXT))
            {
                return;
            }

            TextRenderInfo renderInfo = (TextRenderInfo)data;

            float counter = increaseCounter();

            var font             = renderInfo.GetFont().GetFontProgram();
            var originalFontName = font.ToString();
            var fontRegex        = Regex.Match(originalFontName, @"(?<=\+)[a-zA-Z\s]+");

            string fontName = fontRegex.Success ? fontRegex.Value : originalFontName;

            var fontStyle = font.GetFontNames().GetFontStyle();

            float curFontSize = renderInfo.GetFontSize();

            float key = counter;

            IList <TextRenderInfo> text = renderInfo.GetCharacterRenderInfos();

            foreach (TextRenderInfo character in text)
            {
                key += 0.001f;

                var textRenderMode = character.GetTextRenderMode();
                var opacity        = character.GetGraphicsState().GetFillOpacity();

                //if (textRenderMode != 0 || opacity != 1)
                //{

                //}

                string letter = character.GetText();

                Color color;

                var fillColor = character.GetFillColor();
                var colors    = fillColor.GetColorValue();
                if (colors.Length == 1)
                {
                    color = Color.FromArgb((int)(255 * (1 - colors[0])), Color.Black);
                }
                else if (colors.Length == 3)
                {
                    color = Color.FromArgb((int)(255 * colors[0]), (int)(255 * colors[1]), (int)(255 * colors[2]));
                }
                else if (colors.Length == 4)
                {
                    color = Color.FromArgb((int)(255 * colors[0]), (int)(255 * colors[1]), (int)(255 * colors[2]), (int)(255 * colors[3]));
                }
                else
                {
                    color = Color.Black;
                }

                //if(letter == "A")
                //{

                //}

                if (string.IsNullOrWhiteSpace(letter))
                {
                    continue;
                }

                //Get the bounding box for the chunk of text
                var bottomLeft = character.GetDescentLine().GetStartPoint();
                var topRight   = character.GetAscentLine().GetEndPoint();

                //Create a rectangle from it
                var rect = new Geom.Rectangle(
                    bottomLeft.Get(Vector.I1),
                    topRight.Get(Vector.I2),
                    topRight.Get(Vector.I1),
                    topRight.Get(Vector.I2)
                    );

                var currentChunk = new itext.pdfimage.Models.TextChunk()
                {
                    Text       = letter,
                    Rect       = rect,
                    FontFamily = fontName,
                    FontSize   = (int)curFontSize,
                    FontStyle  = fontStyle,
                    Color      = color,
                    SpaceWidth = character.GetSingleSpaceWidth() / 2f
                };

                chunkDictionairy.Add(key, currentChunk);
            }

            base.EventOccurred(data, type);
        }
        /// Captures text using a simplified algorithm for inserting hard returns and spaces
        ///     @param   renderInfo  render info
        public virtual void RenderText(TextRenderInfo renderInfo)
        {
            // todo handle adding last line

            string text = renderInfo.GetText().Replace('\t', ' ');

            if (!Utils.FloatsNearlyEqual(renderInfo.GetBaseline().GetStartPoint().Get(Vector.I2), baseline, 0.01f) &&
                !Utils.FloatsNearlyEqual(renderInfo.GetAscentLine().GetStartPoint().Get(Vector.I2), ascent, 0.01f))
            {
                startOfNewline = true;
            }

            if (startOfNewline)
            {
                if (currLine != null)
                {
                    if (currChunk.ChunkStr.Length > 0)
                    {
                        StartNewWord();
                        startOfChunk = true;
                    }
                    currLine.RightMostPos     = bottomRight.Get(Vector.I1);
                    currLine.LineSpacingBelow =
                        currLine.Descent - renderInfo.GetAscentLine().GetStartPoint().Get(Vector.I2);
                }

                currLine = new LineMetrics();
                pageMetrics.AddLine(currLine);
                currLine.Ascent           = renderInfo.GetAscentLine().GetStartPoint().Get(Vector.I2);
                currLine.Descent          = renderInfo.GetDescentLine().GetStartPoint().Get(Vector.I2);
                currLine.Baseline         = renderInfo.GetBaseline().GetStartPoint().Get(Vector.I2);
                currLine.LeftMostPos      = renderInfo.GetBaseline().GetStartPoint().Get(Vector.I1);
                currLine.LineSpacingAbove = descent - currLine.Ascent;

                startOfNewline = false;
            }

            CharMetrics charMetrics;

            // Check if there is space char required between chunks
            if (GetResultantText().Length > 0 &&
                IsSpaceRequired(bottomRight.Get(Vector.I1), renderInfo.GetBaseline().GetStartPoint().Get(Vector.I1),
                                renderInfo.GetBaseline().GetStartPoint().Get(Vector.I2),
                                renderInfo.GetSingleSpaceWidth())) // todo switch order

            {
                charMetrics             = new CharMetrics(' ');
                charMetrics.BottomLeft  = new Vector3D(bottomLeft);
                charMetrics.TopLeft     = new Vector3D(topLeft);
                charMetrics.BottomRight = new Vector3D(renderInfo.GetBaseline().GetStartPoint());
                charMetrics.TopRight    = new Vector3D(renderInfo.GetAscentLine().GetStartPoint());
                this.charMetrices.Add(charMetrics);
                text = " " + text; // todo extra spacing? e.g. handle if it is 4x singlespace width
            }

            TextRenderInfo lastChar = null;
            int            charInd  = 0;

            foreach (TextRenderInfo charInfo in renderInfo.GetCharacterRenderInfos())
            {
                if (charInfo.GetText().Length == 0)
                {
                    continue;
                }

                if (lastChar != null && IsSpaceRequired(lastChar.GetBaseline().GetEndPoint().Get(Vector.I1),
                                                        charInfo.GetBaseline().GetStartPoint().Get(Vector.I1),
                                                        renderInfo.GetSingleSpaceWidth()))
                {
                    charMetrics             = new CharMetrics(' ');
                    charMetrics.FontSize    = charInfo.GetFontSize();
                    charMetrics.BottomLeft  = new Vector3D(lastChar.GetBaseline().GetEndPoint());
                    charMetrics.TopLeft     = new Vector3D(lastChar.GetAscentLine().GetEndPoint());
                    charMetrics.BottomRight = new Vector3D(charInfo.GetBaseline().GetStartPoint());
                    charMetrics.TopRight    = new Vector3D(charInfo.GetAscentLine().GetStartPoint());
                    charMetrices.Add(charMetrics);
                    text = text.Insert(charInd + 1, " ");
                }

                char c = charInfo.GetText()[0] == '\t' ? ' ' : charInfo.GetText()[0];
                charMetrics             = new CharMetrics(c);
                charMetrics.FontSize    = charInfo.GetFontSize();
                charMetrics.BottomLeft  = new Vector3D(charInfo.GetBaseline().GetStartPoint());
                charMetrics.TopLeft     = new Vector3D(charInfo.GetAscentLine().GetStartPoint());
                charMetrics.BottomRight = new Vector3D(charInfo.GetBaseline().GetEndPoint());
                charMetrics.TopRight    = new Vector3D(charInfo.GetAscentLine().GetEndPoint());
                charMetrices.Add(charMetrics);

                lastChar = charInfo;
                charInd++;
            }

            if (startOfChunk)
            {
                if (Utils.FloatsNearlyEqual(currLine.Baseline, baseline, 0.001f))
                {
                    float horSpacing = Math.Abs(
                        bottomRight.Get(Vector.I1) - renderInfo.GetBaseline().GetStartPoint().Get(Vector.I1));
                    if (horSpacing > spaceWidth)
                    {
                        Console.Write("");
                    }
                }

                bottomLeft           = renderInfo.GetBaseline().GetStartPoint();
                topLeft              = renderInfo.GetAscentLine().GetStartPoint();
                currChunk.BottomLeft = new Vector3D(bottomLeft);
                currChunk.TopLeft    = new Vector3D(topLeft);
                baseline             = renderInfo.GetBaseline().GetStartPoint().Get(Vector.I2);
                ascent     = renderInfo.GetAscentLine().GetStartPoint().Get(Vector.I2);
                descent    = renderInfo.GetDescentLine().GetStartPoint().Get(Vector.I2);
                spaceWidth = renderInfo.GetSingleSpaceWidth();

                startOfChunk = false;
            }

            bottomRight = renderInfo.GetBaseline().GetEndPoint();
            topRight    = renderInfo.GetAscentLine().GetEndPoint();

            string currFont = renderInfo.GetFont() != null?renderInfo.GetFont().ToString() : "";

            if (currChunk.FontFamily == null && currFont.Length > 0)
            {
                currChunk.FontFamily = currFont;
            }

            //Check if faux bold is used
            if ((renderInfo.GetTextRenderMode() == (int)TextRenderMode.FillThenStrokeText) || // todo include render mode for outsets etc?
                renderInfo.GetFont().GetFontProgram().GetFontNames().IsBold())
            {
                currChunk.Bold = true;
            }

            if (!(Utils.FloatsNearlyEqual(renderInfo.GetFont().GetFontProgram().GetFontMetrics().GetItalicAngle(), 0, 0.001f)) ||
                renderInfo.GetFont().GetFontProgram().GetFontNames().IsItalic())
            {
                currChunk.Italic = true;
            }

            if (currChunk.FillColor == null && renderInfo.GetFillColor() != null)
            {
                currChunk.FillColor = ProcessColorInfo(renderInfo.GetFillColor());
            }

            if (currChunk.StrokeColor == null && renderInfo.GetStrokeColor() != null)
            {
                currChunk.StrokeColor = ProcessColorInfo(renderInfo.GetStrokeColor());
            }

            currChunk.Append(text);
            result.Append(text); // todo include newlines
        }