C# - How to Print a PictureBox [QRCode] in WinForm Application

生成二维码

  1. 通过 Nuget 安装 QRCoder
  2. 添加 PictureBox 控件时,将其 SizeMode 设置为 Zoom

二维码生成代码:

  1. private void BtnGenerate_Click(object sender, EventArgs e)
  2. {
  3. var qg = new QRCoder.QRCodeGenerator();
  4. var myData = qg.CreateQrCode(TxtCode.Text, QRCoder.QRCodeGenerator.ECCLevel.H);
  5. var code = new QRCoder.QRCode(myData);
  6. PicQRCode.Image = code.GetGraphic(50);
  7. }

打印图像

利用 .NET Framework 自带的 PrintDocument 调用打印机。

  1. private void PrintBarCode()
  2. {
  3. var pd = new PrintDialog();
  4. var doc = new PrintDocument();
  5. doc.PrintPage += Doc_PrintPage;
  6. pd.Document = doc;
  7. if (pd.ShowDialog() == DialogResult.OK)
  8. {
  9. doc.Print();
  10. }
  11. }
  12. private void Doc_PrintPage(object sender, PrintPageEventArgs e)
  13. {
  14. var bm = new Bitmap(PicQRCode.Width, PicQRCode.Height);
  15. PicQRCode.DrawToBitmap(bm, new Rectangle(0, 0, PicQRCode.Width, PicQRCode.Height));
  16. e.Graphics.DrawImage(bm, 0, 0);
  17. bm.Dispose();
  18. }