Beispiel #1
0
        /// <summary>
        /// Enhanced measure string function for PdfSharp Xgraphics
        /// wich take to account lineBreaks to calculate the real string
        /// height in a rectagle
        /// </summary>
        /// <param name="gfx"></param>
        /// <param name="text">Text to measure</param>
        /// <param name="maxWitdh">Maximum allowed width</param>
        /// <returns></returns>
        public static XSize MeasureStringExact(this XGraphics gfx, string content, XFont font, double maxWidth)
        {
            //Split by hard line break
            var contents = content.Split(new List <string> {
                "\n", "\r\n"
            }.ToArray(), StringSplitOptions.None);

            Func <string, XFont, XSize> measPdfSharp = (ct, ft) =>
            {
                var size = gfx.MeasureString(ct, ft);

                var lineSpace   = font.GetHeight();
                var cellSpace   = font.FontFamily.GetLineSpacing(ft.Style);
                var cellLeading = cellSpace - font.FontFamily.GetCellAscent(ft.Style) - font.FontFamily.GetCellDescent(ft.Style);
                var leading     = lineSpace * cellLeading / cellSpace;

                size.Height += leading;

                if (size.Width > maxWidth)
                {
                    var nbLine = gfx.GetSplittedLineCount(ct, ft, maxWidth);

                    size.Height = (nbLine * lineSpace) + leading;
                    size.Width  = maxWidth;
                }

                return(size);
            };

            var sizes = contents.Select(c => measPdfSharp(c, font));

            return(new XSize(sizes.Max(w => w.Width), sizes.Sum(h => h.Height)));
        }