使用来自文件的字体绘制文本无法工作

6
我正在尝试使用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;
    }      
}

2
我认为这是设计问题。通过谷歌搜索,可以发现许多人都在尝试解决这个问题,但没有得到什么答案。最终,我认为字体需要安装在机器上才能打印它。否则,一个常见的解决方法是将其变成位图图像,但质量显然会受到影响。 - LarsTech
@LarsTech:这个链接提供了一个可工作的示例:http://msdn.microsoft.com/zh-cn/library/y505zzfw(v=vs.110).aspx - Sam Axe
3
并不适用于PrintPreviewDialog,这就是这位用户遇到问题的地方。我尝试复现了一下,在窗体中可以使用,但在预览对话框中却不行。 - LarsTech
你是否正在尝试打印条形码字体?这会带来很大的麻烦,因为这些东西会创建巨大的多MB spool文件,并且由于驱动程序尝试进行抖动和反锯齿处理,打印效果非常糟糕。我强烈建议使用图形基元来绘制条形码;有许多.NET库可以实现这一点。 - Dour High Arch
@MiguelSv:这个链接可能会有帮助:http://stackoverflow.com/questions/10946986/unable-to-view-micr-font-in-print-preview - Sam Axe
显示剩余2条评论
1个回答

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


并移除
私有字体_barCodeFont;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接