WPF打印二维码和条形码

使用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;
原文地址:https://www.cnblogs.com/tangchun/p/12883312.html