Ejemplo n.º 1
0
        public TextFormat QueryFont(Font font)
        {
            // load an existing text format
            if (TextFormats.TryGetValue(font, out var textFormat))
            {
                return(textFormat);
            }

            var weight = GetFontWeight(font.Weight);

            // create a new text format
            if (FontCollection.FindFamilyName(font.FamilyName, out int index))
            {
                // load from a font collection
                textFormat = new TextFormat(DirectWriteFactory, font.FamilyName, FontCollection, weight,
                                            FontStyle.Normal, FontStretch.Normal, font.Size);
            }
            else
            {
                // load from system
                textFormat = new TextFormat(DirectWriteFactory, font.FamilyName, weight, FontStyle.Normal, font.Size);
            }

            if (textFormat != null)
            {
                TextFormats.Add(font, textFormat);
            }

            return(textFormat);
        }
Ejemplo n.º 2
0
        private async Task <List <string> > LoadCustomFontCharacters(string fontfamilyname, string fontFilePath)
        {
            var uri         = new Uri(fontFilePath);
            var storageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);

            CurrentResourceFontLoader = new ResourceFontLoader(FactoryDWrite, await storageFile.OpenStreamForReadAsync());
            CurrentFontCollection     = new FontCollection(FactoryDWrite, CurrentResourceFontLoader,
                                                           CurrentResourceFontLoader.Key);

            var character = new List <string>();

            CurrentFontCollection.FindFamilyName(fontfamilyname, out var familyIndex);
            if (familyIndex == -1)
            {
                return(character);
            }

            using (var fontFamily = CurrentFontCollection.GetFontFamily(familyIndex))
            {
                var font  = fontFamily.GetFont(0);
                var count = 65536 * 4 - 1;
                for (var i = 0; i < count; i++)
                {
                    if (font.HasCharacter(i))
                    {
                        character.Add(char.ConvertFromUtf32(i));
                    }
                }
            }

            return(character);
        }
Ejemplo n.º 3
0
        public void CreatePDF(Stream stream)
        {
            var fc = new FontCollection();

            fc.RegisterDirectory(Path.Combine("Resources", "Fonts"));
            var doc = new GcPdfDocument();
            var g   = doc.NewPage().Graphics;
            var rc  = Common.Util.AddNote(
                "TextFormat.FontStyle allows to turn on Bold and/or Italic emulation\n" +
                "on a regular (not a bold/italic) font.", doc.Pages.Last);
            // Text insertion point:
            PointF     ip = new PointF(rc.Left, rc.Bottom + 36);
            TextFormat tf = new TextFormat();

            // We specifically get a non-bold/non-italic version of the font:
            tf.Font     = fc.FindFamilyName("Times New Roman", false, false);
            tf.FontSize = 16;
            g.DrawString($"Regular Times font: {tf.Font.FullFontName}", tf, ip);
            ip.Y += 36;
            // Draw some strings using the same (regular) font but emulating bold and italic:
            tf.FontStyle = FontStyle.Bold;
            g.DrawString($"Bold emulation using font: {tf.Font.FullFontName}", tf, ip);
            ip.Y        += 36;
            tf.FontStyle = FontStyle.Italic;
            g.DrawString($"Italic emulation using font: {tf.Font.FullFontName}", tf, ip);
            ip.Y        += 36;
            tf.FontStyle = FontStyle.BoldItalic;
            g.DrawString($"Bold+Italic emulation using font: {tf.Font.FullFontName}", tf, ip);
            ip.Y += 36;
            //
            // Now we render some strings using the "real" bold/italic variants of the font:
            tf.FontStyle = FontStyle.Regular;
            tf.Font      = fc.FindFamilyName("Times New Roman", true, false);
            g.DrawString($"Using real bold font: {tf.Font.FullFontName}", tf, ip);
            ip.Y   += 36;
            tf.Font = fc.FindFamilyName("Times New Roman", false, true);
            g.DrawString($"Using real italic font: {tf.Font.FullFontName}", tf, ip);
            ip.Y   += 36;
            tf.Font = fc.FindFamilyName("Times New Roman", true, true);
            g.DrawString($"Using real bold italic font: {tf.Font.FullFontName}", tf, ip);
            ip.Y += 36;
            // Done:
            doc.Save(stream);
        }
Ejemplo n.º 4
0
        private static FontFamily GetFontFamily(string familyName)
        {
            int fontIndex = 0;

            _currentFontCollection.FindFamilyName(familyName, out fontIndex);
            if (fontIndex < 0)
            {
                return(null);
            }

            var fontFamily = _currentFontCollection.GetFontFamily(fontIndex);

            return(fontFamily);
        }
Ejemplo n.º 5
0
        void Create(string familyName, float sizeInPoints, FontStyle style, FontDecoration decoration)
        {
            Size           = sizeInPoints;
            FontStyle      = style;
            FontDecoration = decoration;
            int index;

            if (FontCollection.FindFamilyName(familyName, out index))
            {
                sw.FontStyle  fontStyle;
                sw.FontWeight fontWeight;
                Conversions.Convert(style, out fontStyle, out fontWeight);
                Control = FontCollection.GetFontFamily(index).GetFirstMatchingFont(fontWeight, sw.FontStretch.Normal, fontStyle);
            }
        }
Ejemplo n.º 6
0
        private Font GetSystemFont(string fontFamilyName)
        {
            int  fontFamilyIndex;
            bool found = _systemFonts.FindFamilyName(fontFamilyName, out fontFamilyIndex);

            if (!found)
            {
                throw new ArgumentException("Couldn't find the specified font.");
            }

            using (var fontFamily = _systemFonts.GetFontFamily(fontFamilyIndex))
            {
                return(fontFamily.GetFirstMatchingFont(FontWeight.Normal, FontStretch.Normal, FontStyle.Normal));
            }
        }
Ejemplo n.º 7
0
    async Task LoadCustomFonts()
    {
        await Task.Run(() =>
        {
            // Font Families
            FontFamilyNames = new List <string> {
                "Aileron", "Grundschrift"
            };
            // Character codes to check for:
            int[] codes               = { 0x41, 0x6f, 0x7c, 0xc2aa, 0xD7A3 };
            FactoryDWrite             = new SharpDX.DirectWrite.Factory();
            CurrentResourceFontLoader = new ResourceFontLoader(FactoryDWrite, customFontStreams);
            CurrentFontCollection     = new FontCollection(FactoryDWrite, CurrentResourceFontLoader, CurrentResourceFontLoader.Key);

            foreach (var fontfamilyname in FontFamilyNames)
            {
                int familyIndex;
                CurrentFontCollection.FindFamilyName(fontfamilyname, out familyIndex);

                using (var fontFamily = CurrentFontCollection.GetFontFamily(familyIndex))
                {
                    var font = fontFamily.GetFont(0);

                    using (var fontface = new FontFace(font))
                    {
                        var results = fontface.GetGlyphIndices(codes);
                        for (int i = 0; i < codes.Length - 1; i++)
                        {
                            if (results[i] > 0)
                            {
                                Debug.WriteLine("Contains the unicode character " + codes[i]);
                            }
                            else
                            {
                                Debug.WriteLine("Does not contain the unicode character " + codes[i]);
                            }
                        }
                    }
                }
            }
        });
    }
Ejemplo n.º 8
0
        public void SetTextFormat(TextFormat textFormat)
        {
            // Initializes properties using a text format, like font family, font size,
            // and reading direction. For simplicity, this custom layout supports
            // minimal formatting. No mixed formatting or alignment modes are supported.
            readingDirection_ = textFormat.ReadingDirection;
            fontEmSize_       = textFormat.FontSize;
            localName_        = textFormat.LocaleName;

            // Map font and style to fontFace.
            FontCollection fontCollection = textFormat.FontCollection;// Need the font collection to map from font name to actual font.

            if (fontCollection == null)
            {
                fontCollection = dwriteFactory_.GetSystemFontCollection(false);// No font collection was set in the format, so use the system default.
            }
            // Find matching family name in collection.
            String fontFamilyName = textFormat.FontFamilyName;

            int fontIndex;

            // If the given font does not exist, take what we can get
            // (displaying something instead nothing), choosing the foremost
            // font in the collection.
            if (!fontCollection.FindFamilyName(fontFamilyName, out fontIndex))
            {
                fontIndex = 0;
            }

            FontFamily fontFamily = fontCollection.GetFontFamily(fontIndex);
            Font       font       = fontFamily.GetFirstMatchingFont(textFormat.FontWeight, textFormat.FontStretch, textFormat.FontStyle);

            fontFace_ = new FontFace(font);

            font.Dispose();
            fontFamily.Dispose();
            fontCollection.Dispose();
        }
        public static Font GetFont(Typeface typeface)
        {
            var fontFamily     = typeface.FontFamily;
            var fontCollection = GetOrAddFontCollection(fontFamily);

            foreach (var familyName in fontFamily.FamilyNames)
            {
                if (fontCollection.FindFamilyName(familyName, out var index))
                {
                    return(fontCollection.GetFontFamily(index).GetFirstMatchingFont(
                               (FontWeight)typeface.Weight,
                               FontStretch.Normal,
                               (FontStyle)typeface.Style));
                }
            }

            InstalledFontCollection.FindFamilyName(FontFamily.Default.Name, out var i);

            return(InstalledFontCollection.GetFontFamily(i).GetFirstMatchingFont(
                       (FontWeight)typeface.Weight,
                       FontStretch.Normal,
                       (FontStyle)typeface.Style));
        }
        public static Font GetFont(Typeface typeface)
        {
            var fontFamily     = typeface.FontFamily;
            var fontCollection = GetOrAddFontCollection(fontFamily);
            int index;

            foreach (var name in fontFamily.FamilyNames)
            {
                if (fontCollection.FindFamilyName(name, out index))
                {
                    return(fontCollection.GetFontFamily(index).GetFirstMatchingFont(
                               (FontWeight)typeface.Weight,
                               (FontStretch)typeface.Stretch,
                               (FontStyle)typeface.Style));
                }
            }

            InstalledFontCollection.FindFamilyName("Segoe UI", out index);

            return(InstalledFontCollection.GetFontFamily(index).GetFirstMatchingFont(
                       (FontWeight)typeface.Weight,
                       (FontStretch)typeface.Stretch,
                       (FontStyle)typeface.Style));
        }
Ejemplo n.º 11
0
        public void CreatePDF(Stream stream)
        {
            var doc  = new GcPdfDocument();
            var page = doc.NewPage();

            // Use Landscape orientation:
            page.Landscape = true;
            var g = page.Graphics;
            // Some sample texts in Japanese, English and Arabic:
            string text1 = "学校教育の「国語」で教えられる。";
            string text2 = " flow direction. ";
            string text3 = "النص العربي 12 + 34 = 46 مع الأرقام ";
            // Init font cache and get the required fonts:
            var fc = new FontCollection();

            fc.RegisterDirectory(Path.Combine("Resources", "Fonts"));
            var fYuMin = fc.FindFamilyName("Yu Mincho");
            var fTimes = fc.FindFamilyName("Times New Roman");
            var fArial = fc.FindFamilyName("Arial");
            // Create text formats:
            var tf1 = new TextFormat()
            {
                Font = fYuMin
            };
            var tf2 = new TextFormat()
            {
                Font = fTimes
            };
            var tf3 = new TextFormat()
            {
                Font = fArial
            };
            // Create TextLayout and set some options on it:
            var tl = g.CreateTextLayout();

            tl.FirstLineIndent = 36;
            tl.TextAlignment   = TextAlignment.Justified;
            // This setting justifies the last line too:
            tl.LastLineIsEndOfParagraph = false;
            // Set all margins to 1":
            tl.MarginAll = tl.Resolution;
            tl.MaxWidth  = page.Size.Width;
            tl.MaxHeight = page.Size.Height;
            // RTL layout:
            tl.RightToLeft = false;
            // Build a list of objects for the text to flow around:
            tl.ObjectRects = new List <ObjectRect>()
            {
                new ObjectRect(540, 100, 120, 160),
                new ObjectRect(100, 290, 170, 100),
                new ObjectRect(500, 350, 170, 100)
            };
            // Fill corresponding rectangels on page so that we can see them:
            foreach (var or in tl.ObjectRects)
            {
                g.FillRectangle(or.ToRectangleF(), Color.PaleVioletRed);
            }

            // Add text to layout:
            for (int i = 0; i < 3; i++)
            {
                tl.Append(text1, tf1);
                tl.Append("Horizontal Top To Bottom" + text2, tf2);
                tl.AppendLine(text3, tf3);
            }
            // Perform and draw first layout:
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, PointF.Empty);
            g.FillRectangle(tl.ContentRectangle, Color.FromArgb(20, Color.Red));

            // Create 2nd layout - vertical rotated counter-clockwise:
            var t = tl.ContentHeight;

            tl.Clear();
            tl.RotateSidewaysCounterclockwise = true;
            tl.FlowDirection = FlowDirection.VerticalLeftToRight;
            tl.MarginTop    += t;
            // Add text to layout:
            for (int i = 0; i < 3; i++)
            {
                tl.Append(text1, tf1);
                tl.Append("Vertical Left To Right" + text2, tf2);
                tl.AppendLine(text3, tf3);
            }
            // Perform and draw second layout:
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, PointF.Empty);
            g.FillRectangle(tl.ContentRectangle, Color.FromArgb(20, Color.Green));

            // Create 3rd layout - vertical:
            tl.Clear();
            tl.FlowDirection = FlowDirection.VerticalRightToLeft;
            tl.RotateSidewaysCounterclockwise = false;
            // Add text to layout:
            for (int i = 0; i < 3; i++)
            {
                tl.Append(text1, tf1);
                tl.Append("Vertical Right To Left" + text2, tf2);
                tl.AppendLine(text3, tf3);
            }
            // Perform and draw third layout:
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, PointF.Empty);
            g.FillRectangle(tl.ContentRectangle, Color.FromArgb(20, Color.Blue));
            // Done:
            doc.Save(stream);
        }
Ejemplo n.º 12
0
        public void CreatePDF(Stream stream)
        {
            // Test string using EUDC codes and two regular chars (& and !): 0xE620 0xE621 0xE622 0xE624 & 0xE623 !
            const string tstr = "&!";
            // Set up:
            var doc  = new GcPdfDocument();
            var page = doc.NewPage();
            var g    = page.Graphics;
            var tf   = new TextFormat()
            {
                FontSize = 20
            };
            var rc = Common.Util.AddNote(
                "This sample demonstrates how to render private use Unicode characters (PUA) with custom EUDC fonts (.tte).\n" +
                "A GrapeCity.Documents.Text.Font can be created from an EUDC .tte file, " +
                "and linked to one or more fonts using Font.AddEudcFont() method.",
                page);
            const float dy = 36;
            var         ip = new PointF(rc.X, rc.Bottom + dy / 2);

            // Use FontCollection to allow fetching fonts by family names:
            var fc = new FontCollection();

            // Assign the font collection to the graphics so that MeasureString/DrawString
            // methods on the graphics can find fallback fonts:
            g.FontCollection = fc;

            // Register some regular fonts with the FontCollection:
            fc.RegisterFont(Path.Combine("Resources", "Fonts", "arial.ttf"));
            fc.RegisterFont(Path.Combine("Resources", "Fonts", "times.ttf"));
            fc.RegisterFont(Path.Combine("Resources", "Fonts", "yumin.ttf"));
            fc.RegisterFont(Path.Combine("Resources", "Fonts", "msgothic.ttc"));
            fc.RegisterFont(Path.Combine("Resources", "Fonts", "YuGothR.ttc"));

            // Tell the font collection to use Yu Mincho as a fallback:
            fc.AppendFallbackFonts(fc.FindFamilyName("Yu Mincho"));

            // Using Arial font renders the test string as empty rectangles, as suitable glyphs are not present in Arial:
            tf.Font = fc.FindFamilyName("Arial", false, false);
            g.DrawString($"Arial: {tstr} (no EUDC font has been linked yet)", tf, ip);
            ip.Y += dy;

            // Load two custome EUDC fonts:
            var eudcF0 = Font.FromFile(Path.Combine("Resources", "Fonts", "Eudc0.tte"));
            var eudcF1 = Font.FromFile(Path.Combine("Resources", "Fonts", "Eudc1.tte"));

            // Link one EUDC font to Arial - now in strings rendered with Arial, EUDC chars will be looked up in this font:
            var font = fc.FindFamilyName("Arial");

            font.AddEudcFont(eudcF0);
            // Ditto for Yu Mincho font:
            font = fc.FindFamilyName("Yu Mincho");
            font.AddEudcFont(eudcF0);
            // Link another EUDC font to Yu Gothic:
            font = fc.FindFamilyName("Yu Gothic");
            font.AddEudcFont(eudcF1);

            // Render strings with EUDC chars using fonts to which our custom EUDC font is linked:
            tf.Font = fc.FindFamilyName("Arial", false, false);
            g.DrawString($"Arial, linked with Eudc0.tte: {tstr}", tf, ip);
            ip.Y   += dy;
            tf.Font = fc.FindFileName("times.ttf");
            g.DrawString($"Times, fallback via Yu Mincho: {tstr}", tf, ip);
            ip.Y   += dy;
            tf.Font = fc.FindFamilyName("MS Gothic");
            g.DrawString($"MS Gothic, fallback via Yu Mincho: {tstr}", tf, ip);
            ip.Y   += dy;
            tf.Font = fc.FindFamilyName("Yu Gothic");
            g.DrawString($"Yu Gothic, linked with Eudc1.tte: {tstr}", tf, ip);
            ip.Y += dy;

            // FontCollection adds some services (like font lookup by family name),
            // but EUDC fonts can be linked to fonts that are not in a collection:
            font = Font.FromFile(Path.Combine("Resources", "Fonts", "Gabriola.ttf"));
            font.AddEudcFont(eudcF0);
            tf.Font = font;
            g.DrawString($"Gabriola Font, linked with Eudc0.tte: {tstr}", tf, ip);
            ip.Y += dy;
            // Done:
            doc.Save(stream);
        }
Ejemplo n.º 13
0
        public void CreatePDF(Stream stream)
        {
            // Function to generate sample text quoting its formatting options:
            Func <TextFormat, string> makeSampleText = (tf_) =>
            {
                string boldItalic = string.Empty;
                if (tf_.Font.FontBold)
                {
                    boldItalic = "bold ";
                }
                if (tf_.Font.FontItalic)
                {
                    boldItalic += "italic ";
                }
                if (boldItalic == string.Empty)
                {
                    boldItalic = "normal ";
                }
                return($"This is {boldItalic}text drawn using font '{tf_.Font.FullFontName}', font size {tf_.FontSize} points, " +
                       $"text color {tf_.ForeColor}, background color {tf_.BackColor}. ");
            };
            // Font names:
            const string times = "times new roman";
            const string arial = "arial";
            // Create document and text layout:
            var doc  = new GcPdfDocument();
            var page = doc.NewPage();
            var g    = page.Graphics;
            var tl   = g.CreateTextLayout();

            // Use TextLayout to layout the whole page and maintain margins:
            tl.MaxHeight = page.Size.Height;
            tl.MaxWidth  = page.Size.Width;
            tl.MarginAll = 72;
            // Get some fonts:
            var fc = new FontCollection();

            fc.RegisterDirectory(Path.Combine("Resources", "Fonts"));
            var fTimes           = fc.FindFamilyName(times, false, false);
            var fTimesBold       = fc.FindFamilyName(times, true, false);
            var fTimesItalic     = fc.FindFamilyName(times, false, true);
            var fTimesBoldItalic = fc.FindFamilyName(times, true, true);
            var fArial           = fc.FindFamilyName(arial, false, false);
            // Add text to TextLayout using different fonts and font sizes:
            TextFormat tf = new TextFormat()
            {
                Font = fTimes, FontSize = 12,
            };

            tl.Append(makeSampleText(tf), tf);
            tf.Font      = fTimesBold;
            tf.FontSize += 2;
            tl.Append(makeSampleText(tf), tf);
            tf.Font      = fTimesItalic;
            tf.FontSize += 2;
            tl.Append(makeSampleText(tf), tf);
            tf.Font      = fTimesBoldItalic;
            tf.FontSize += 2;
            tl.Append(makeSampleText(tf), tf);
            tf.Font      = fArial;
            tf.FontSize += 2;
            tl.Append(makeSampleText(tf), tf);
            // Add text with different foreground and background colors:
            tf.Font      = fTimesBold;
            tf.ForeColor = Color.Tomato;
            tl.Append(makeSampleText(tf), tf);
            tf.Font      = fTimesBoldItalic;
            tf.FontSize  = 16;
            tf.ForeColor = Color.SlateBlue;
            tf.BackColor = Color.Orange;
            tl.Append(makeSampleText(tf), tf);
            // Finish with plain black on transparent again:
            tl.Append("The end.", new TextFormat()
            {
                Font = fTimes, FontSize = 14,
            });
            // Layout and draw text:
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, PointF.Empty);
            // Done:
            doc.Save(stream);
        }
Ejemplo n.º 14
0
        public override BuiltRichText BuildText(IList <RichTextNode> nodes, int width, float sizeMultiplier = 1)
        {
            if (!customLoader.Valid)
            {
                CreateCustomCollection();
            }
            var paragraphs = new List <List <RichTextNode> >();

            paragraphs.Add(new List <RichTextNode>());
            int first = 0;

            while (nodes[first] is RichTextParagraphNode && first < nodes.Count)
            {
                first++;
            }
            DWrite.TextAlignment ta = CastAlignment((nodes[first] as RichTextTextNode).Alignment);
            paragraphs[paragraphs.Count - 1].Add(nodes[first]);
            foreach (var node in nodes.Skip(first + 1))
            {
                if (node is RichTextParagraphNode)
                {
                    paragraphs.Add(new List <RichTextNode>());
                }
                else
                {
                    var n     = (RichTextTextNode)node;
                    var align = CastAlignment(n.Alignment);
                    if (align != ta && paragraphs[paragraphs.Count - 1].Count > 0)
                    {
                        paragraphs.Add(new List <RichTextNode>());
                    }
                    paragraphs[paragraphs.Count - 1].Add(node);
                    ta = align;
                }
            }
            string lastFont = null;
            float  lastSize = 0;
            //Format text
            var layouts = new List <TextLayout>();

            for (int j = 0; j < paragraphs.Count; j++)
            {
                var p       = paragraphs[j];
                var builder = new StringBuilder();
                foreach (var n in p)
                {
                    builder.Append(((RichTextTextNode)n).Contents);
                }
                var layout = new TextLayout(
                    dwFactory,
                    builder.ToString(),
                    new TextFormat(
                        dwFactory,
                        string.IsNullOrEmpty(lastFont) ? "Arial" : lastFont,
                        lastSize > 0 ? lastSize : (16 * sizeMultiplier)
                        ),
                    width,
                    float.MaxValue
                    );
                if (p.Count > 0)
                {
                    layout.TextAlignment = CastAlignment(((RichTextTextNode)p[0]).Alignment);
                }
                int startIdx = 0;
                foreach (var n in p)
                {
                    var text  = (RichTextTextNode)n;
                    var range = new TextRange(startIdx, text.Contents.Length);
                    if (text.Bold)
                    {
                        layout.SetFontWeight(FontWeight.Bold, range);
                    }
                    if (text.Italic)
                    {
                        layout.SetFontStyle(FontStyle.Italic, range);
                    }
                    if (text.Underline)
                    {
                        layout.SetUnderline(true, range);
                    }
                    if (!string.IsNullOrEmpty(text.FontName))
                    {
                        if (customCollection.FindFamilyName(text.FontName, out int _))
                        {
                            layout.SetFontCollection(customCollection, range);
                        }
                        layout.SetFontFamilyName(text.FontName, range);
                        lastFont = text.FontName;
                    }
                    if (text.FontSize > 0)
                    {
                        layout.SetFontSize(text.FontSize * sizeMultiplier, range);
                        lastSize = text.FontSize * sizeMultiplier;
                    }
                    layout.SetDrawingEffect(new ColorDrawingEffect(text.Color, text.Shadow), range);
                    startIdx += text.Contents.Length;
                }
                layouts.Add(layout);
            }
            //Return
            var built = new DirectWriteBuiltText(this)
            {
                Layout = layouts, Width = width
            };

            built.CacheQuads();
            return(built);
        }