WPF打印二维码和条形码

北慕城南 提交于 2020-08-11 18:08:57

使用ZXing.net生成二维码和一维码图片,再使用PrintDocument打印图片

具体代码:

private string GenerateBarCodeImage(string barCode, int width, int height, BarcodeFormat format)
        {
            BarcodeWriter writer = new BarcodeWriter { Format = format };
            QrCodeEncodingOptions options = new QrCodeEncodingOptions();
            //设置内容编码
            options.CharacterSet = "UTF-8";
            //设置二维码的宽度和高度
            options.Width = width;
            options.Height = height;
            //设置二维码的边距,单位不是固定像素
            options.Margin = 1;
            writer.Options = options;

            string fileName = _printImageDirectory + Guid.NewGuid().ToString();
            Bitmap map = writer.Write(barCode);

            map.Save(fileName, ImageFormat.Png);
            map.Dispose();
            return fileName;
        }
private void PrintImage(string imagePath)
        {
            if (File.Exists(imagePath))
            {
                PrintDocument pd = new PrintDocument();
                //pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
                pd.DefaultPageSettings.Landscape = true; //or false!
                pd.PrintPage += (sender, args) =>
                {
                    Image i = Image.FromFile(imagePath);
                    System.Drawing.Rectangle m = args.MarginBounds;

                    if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
                    {
                        m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
                    }
                    else
                    {
                        m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
                    }
                    args.Graphics.DrawImage(i, m);
                };
                var printPriview = new PrintPreviewDialog
                {
                    Document = pd,
                    WindowState = FormWindowState.Maximized
                };
                printPriview.ShowDialog();
            }
        }

使用的命名空间:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using ZXing;
using ZXing.QrCode;
using Image = System.Drawing.Image;
using System.Windows.Forms;

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!