WPF 将文本写入图像并发送到打印机

WPF Write Text to Image and send to Printer

我想创建一个包含徽标和多行文本的小图像并将其直接发送到打印机。但是我在文本质量方面遇到了麻烦。

目前我正在创建位图并通过 g.DrawString 向其渲染文本:

Bitmap bitmap = new Bitmap(240, 240);
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;  // or AntiAlias
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("Charge: 1911", new Font("Arial Narrow", 8.0F, System.Drawing.FontStyle.Regular), Brushes.Black, new PointF(6,119));

PrintDocument pd = new PrintDocument();
[...]
pd.PrintPage += PrintPage;
    pd.Print();
g.Dispose();

除了文本质量太差而无法实际打印外,此代码按预期工作。
这是当前结果:

使用 AntiAliasGridFit:

使用抗锯齿:

这(或更好)是我想要达到的结果:

现在我的问题是,有没有什么方法可以提高文本质量,也许可以使用 TextRenderer 而不是 Graphics? 它不必是我打印的位图。我只需要能够向其写入预先存在的图像,然后将整个文档发送到打印机。

经过进一步挖掘,我找到了解决问题的方法。
我没有创建位图并向其绘制文本,而是直接向 PrintPage 方法的 PrintPageEventArgs 对象绘制文本:

private void PrintPage(object o, PrintPageEventArgs e) {
    e.Graphics.DrawImage(logoImg, xCoordinate, yCoordinate, xSize, ySize);
    e.Graphics.DrawString("Charge: 19011", textFont, Brushes.Black, 0, 0, new StringFormat());
}

我不是 100% 确定为什么会这样,但我现在有非常清晰的文本,就像矢量图形一样。

Example