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

标签 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;
    }      
}

最佳答案

试试这个

 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;
}    


并删除
private Font _barCodeFont;

关于c# - 使用文件中的字体绘制文本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22618745/

相关文章:

c# - 如何在我的列表框中包含图标?

c# - HTMLAgilityPack Asp.net C#错误处理

c# - 在功能区中使用 .ico 图像

c# - 如何获取数据绑定(bind)的 ComboBox 以反射(reflect)对 BindingList 数据源所做的更改

c# - 如何验证/检查图像是否已存在于数据库中?

c# - 单击富文本框中的链接后如何打开新的浏览器窗口(C#)

C# 与 Selenium Ajax DropdownList 问题

c# - 如何实例化在 C# DLL 中声明的类?

c# - 从其 Processhandle 获取表单

c# - 如何在不打开 excel 文件的情况下将 excel 工作表复制到另一个 excel 工作簿中# winforms?