[]
        
(Showing Draft Content)

Load Fonts From a File

There are multiple ways to load fonts with DsPdf. When Font.FromFile() is used, the actual data is loaded on demand, thus the Font instance will generally not take up too much memory. The situation is different for fonts created using the Font.FromArray() and Font.FromStream() methods - with these methods, the whole font is immediately loaded into memory, thus using these methods is generally not recommended if memory is a concern.

When different Font instances (created using any of the static methods mentioned above) are used to render text in a PDF, each instance will result in embedding a separate subset of glyphs, even if the glyphs are the same, since DsPdf has no way of knowing that two different Font instances represent the same physical font.

Therefore, the best options are either to make sure that only one Font instance is created for each physical font, or (even better) to use the FontCollection class to add the fonts you need and then specify them via the TextFormat.FontName property.

Refer to the following code sample to see how to load a font from a file:

public int CreatePDF(Stream stream)
        {
            var gabriola = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "Gabriola.ttf"));
            if (gabriola == null)
                throw new Exception("Could not load font Gabriola");
 
            // Now that we have our font, use it to render some text:
            var tf = new TextFormat() { Font = gabriola, FontSize = 16 };
            var doc = new GcPdfDocument();
            var g = doc.NewPage().Graphics;
            g.DrawString($"Sample text drawn with font {gabriola.FontFamilyName}.", tf, new PointF(72, 72));
            // We can change the font size:
            tf.FontSize += 4;
            g.DrawString("The quick brown fox jumps over the lazy dog.", tf, new PointF(72, 72 * 2));
            // We can force DsPdf to emulate bold or italic style with a non-bold (non-italic) font, e.g.:
            tf.FontStyle = GCTEXT.FontStyle.Bold;
            g.DrawString("This line prints with the same font, using emulated bold style.", tf, new PointF(72, 72 * 3));
            // But of course rather than emulated, it is much better to use real bold/italic fonts.
            // So finally, get a real bold italic font and print a line with it:
            var timesbi = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "timesbi.ttf"));
            tf.Font = timesbi ?? throw new Exception("Could not load font timesbi");
            tf.FontStyle = GCTEXT.FontStyle.Regular;
            g.DrawString($"This line prints with {timesbi.FullFontName}.", tf, new PointF(72, 72 * 4));
            // Done:
            doc.Save(stream);
            return doc.Pages.Count;
        }

Limitations

  • When different font instances are used to render text, each instance will result in embedding a separate subset of glyphs, even if the glyphs are the same.