FontFromFile.cs
// 完毕:
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;
using GCTEXT = GrapeCity.Documents.Text;
using GCDRAW = GrapeCity.Documents.Drawing;

namespace DsPdfWeb.Demos.Basics
{
    // 这个简短的示例演示了如何从文件加载字体
    // 并在您的代码中用于呈现文本。
    // 该示例依赖于存在于
    // 资源/字体文件夹。
    // 
    // 注1:当使用Font.FromFile()时,实际数据是按需加载的,
    // 因此通常 Font 实例不会占用太多空间。
    // 对于使用 Font.FromArray() 创建的字体,情况有所不同
    // nd Font.FromStream() 方法 - 在这些情况下,整个字体是
    // 立即加载到内存中。字体仍将被解析
    // 只能按需使用,但内存消耗稍高,
    // 因此,通常应该首选使用 Font.FromFile() 。
    // 
    // 注 2:当不同的 Font 实例(使用任何静态因子创建)
    // 上面提到的)用于渲染 PDF 中的文本,每个实例都会产生
    // 即使字形相同,也嵌入单独的字形子集,
    // 因为 GcDocs.Pdf 无法知道两个不同的 Font 实例
    // 代表相同的物理字体。因此,要么确保只有一个 Font 实例
    // 为每种物理字体创建,或者更好的是使用 FontCollection 类
    // 添加您需要的字体,并通过 TextFormat.FontName 指定它们。
    public class FontFromFile
    {
        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");

            // 现在我们有了字体,用它来渲染一些文本:
            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));
            // 我们可以改变字体大小:
            tf.FontSize += 4;
            g.DrawString("The quick brown fox jumps over the lazy dog.", tf, new PointF(72, 72 * 2));
            // 我们可以强制 GcDocs.Pdf 使用非粗体(非斜体)字体模拟粗体或斜体样式,例如:
            tf.FontStyle = GCTEXT.FontStyle.Bold;
            g.DrawString("This line prints with the same font, using emulated bold style.", tf, new PointF(72, 72 * 3));
            // 但当然,使用真正的粗体/斜体字体比模拟字体要好得多。
            // 最后,获得一个真正的粗体斜体字体并用它打印一行:
            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));
            // 完毕:
            doc.Save(stream);
            return doc.Pages.Count;
        }
    }
}