使用文件中的字体绘制文本不起作用

Mig*_*Slv 6 c# winforms

我正在尝试使用System.Drawing.Text.PrivateFontCollection加载私有字体.目标不是必须在系统上安装字体.

所有的例子我发现它看起来很简单.只需使用PrivateFontCollection加载,然后从中创建一个字体.

在我的简单类下面测试它.

它只有在我安装字体时才有效.否则,文本将在对话框预览中打印为使用某些默认字体.我检查了字体是否正确加载.我错过了什么?感谢您的帮助.

public partial class Test : Form
{
    private PrintDocument printDocument1 = new PrintDocument();
    System.Drawing.Text.PrivateFontCollection privateFonts;
    private Font _barCodeFont;

    public Test()
    {
        InitializeComponent();
    }
    private void Test_Load(object sender, EventArgs e)
    {
        privateFonts = new System.Drawing.Text.PrivateFontCollection();
        privateFonts.AddFontFile("Code128.ttf");
    }

    private void btbTest_Click(object sender, EventArgs e)
    {
        PrintDocument pd = new PrintDocument();

        pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
        pd.DocumentName = "Label";

        PrintPreviewDialog pp = new PrintPreviewDialog();
        pp.Document = pd;
        pp.WindowState = FormWindowState.Normal;
        pp.ShowDialog();

    }
    private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        _barCodeFont = new Font(privateFonts.Families[0], 12, FontStyle.Regular);
        ev.Graphics.DrawString("Should Be a bar code", _barCodeFont, Brushes.Black, 0, 0);
        ev.HasMorePages = false;
    }      
}
Run Code Online (Sandbox Code Playgroud)

小智 0

尝试这个

 private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
    Font _barCodeFont = new Font(privateFonts.Families[0], 12, FontStyle.Regular);
    ev.Graphics.DrawString("Should Be a bar code", _barCodeFont, Brushes.Black, 0, 0);
    ev.HasMorePages = false;
}    
Run Code Online (Sandbox Code Playgroud)


并删除
私有字体_barCodeFont;