使用现有位图旁边的DrawString()打印文本

时间:2017-10-24 13:56:29

标签: c# string bitmap

问候用户,

自从我第一次滥用堆栈溢出问题以来,我的一个处女帖!我一直在尝试获取位图打印以及要打印的字符串。基本上我想要实现的视图是图像和图像右侧的文本,因为我们看到打印输出。以下是我正在使用的代码

 Bitmap qrCodeImage = qrCode.GetGraphic(20);
 senderQR = qrCodeImage;

 PrintDocument pd = new PrintDocument();

 Margins margins = new Margins(10, 10, 10, 10);

 pd.DefaultPageSettings.Margins = margins;
 pd.PrintPage += PrintPage;
 pd.Print();

这是PrintPage方法

private void PrintPage(object sender, PrintPageEventArgs e)
    {
        System.Drawing.Image img = senderQR;

        Bitmap batchCode = new Bitmap(80, 700);

        Rectangle m = e.MarginBounds;
        RectangleF batch1 = new RectangleF(80, 700, 650, 1000);

        m.Width = img.Width / 5;
        m.Height = img.Height / 5;
        Graphics g = Graphics.FromImage(batchCode);
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.DrawString(batch, new Font("Arial", 40), Brushes.Black, batch1);
        g.Flush();

        e.Graphics.DrawImage(img, m);

    }

我做错了什么?似乎是什么问题?我一直在努力实现这一目标,但没有运气!

附加说明:

我希望右边的文字自身包裹,而不是在现有位图的下面或上面,尺寸为3,5 x 2(英寸)(标签打印)。

这是我使用现有代码获得的打印输出;

https://prnt.sc/h1ecb0

https://prnt.sc/h1edex

1 个答案:

答案 0 :(得分:1)

您正在绘制的图像(batchCode)宽80像素,高700像素。当您在其上书写文字时,您将书写的左上角设置为80,700 - 正好在图片的右下角。基本上,你在图片之外写下你的文字。

更新

我创建了一个小例子以使其可重现,下面是基本WinForms应用程序的表单类:

public partial class Form1 : Form
{
    private PictureBox pictureBox2;

    public Form1()
    {
        InitializeComponent();

        pictureBox2 = new PictureBox();
        pictureBox2.Size = ClientSize;
        pictureBox2.SizeMode = PictureBoxSizeMode.AutoSize;
        this.Click += Form1_Click;
        pictureBox2.Click += Form1_Click;

        Controls.Add(pictureBox2);
    }

    private void Form1_Click(object sender, EventArgs e)
    {
        var batch = "hello there!";

        Bitmap batchCode = new Bitmap(1000, 1000);
        var batch1 = new RectangleF(150, 150, 850, 850);
        using (Graphics g = Graphics.FromImage(batchCode))
        {
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.DrawString(batch, new Font("Arial", 40), Brushes.Black, batch1);
        }
        pictureBox2.Image = batchCode;
    }
}