简体   繁体   English

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

[英]WPF Write Text to Image and send to Printer

i want to create a little image containing a logo and multiple lines of text and send it directly to a printer.我想创建一个包含徽标和多行文本的小图像并将其直接发送到打印机。 However im having trouble with textquality.但是我在文本质量方面遇到了麻烦。

Currently im creating a Bitmap and render text to it via g.DrawString:目前我正在创建一个位图并通过 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();

This Code works so far as expected, except the textquality is too bad to actually print.此代码按预期工作,除了文本质量太差而无法实际打印。
This is the current result:这是当前的结果:

with AntiAliasGridFit:使用 AntiAliasGridFit:

在此处输入图片说明

With AntiAlias:使用抗锯齿:

在此处输入图片说明

This (or better) is the result that i want to achieve:这(或更好)是我想要达到的结果:

在此处输入图片说明

Now my question is, is there any way to get better textquality, maybe somehow using TextRenderer instead of Graphics?现在我的问题是,有没有办法获得更好的文本质量,也许以某种方式使用 TextRenderer 而不是 Graphics? It doesnt have to be a bitmap that I print.它不必是我打印的位图。 I just need to be able to also write a pre-existing image to it and send the whole document to a Printer afterwards.我只需要能够将预先存在的图像写入其中,然后将整个文档发送到打印机。

After some more digging i found a solution to my problem.经过更多的挖掘,我找到了解决我的问题的方法。
Instead of creating a Bitmap and drawing text to it i directly draw text to the PrintPageEventArgs object of the PrintPage Method:我没有创建位图并为其绘制文本,而是直接将文本绘制到 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());
}

Im not 100% sure why this works but i now have perfectly clear text like with vector graphics.我不是 100% 确定为什么会这样,但我现在有完全清晰的文本,就像矢量图形一样。

Example例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM