C# 操作打印机


获取当前设置能使用的打印机:

1 foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
2             {
3                 prints.Add(sPrint);
4             }
获取所有的打印机

获取打印机下的纸盒:

1  PrinterSettings ps = new PrinterSettings();
2             ps.PrinterName = printName;
3             for (int i = 0; i < ps.PaperSources.Count; i++)
4             {
5                 sources.Add(ps.PaperSources[i].SourceName);
6             }
获取打印机下的纸盒

打印图片方法:

 1 private static void PicturePrintDocument_PrintPage(object sender, PrintPageEventArgs e)
 2         {
 3             FileStream fs = File.OpenRead(filePath);
 4             int filelength = 0;
 5             filelength = (int)fs.Length; //获得文件长度 
 6             Byte[] image = new Byte[filelength]; //建立一个字节数组 
 7             fs.Read(image, 0, filelength); //按字节流读取 
 8             Image result = Image.FromStream(fs);
 9             fs.Close();
10             e.Graphics.DrawImage(result, 0, 0);  //img大小
11             //e.Graphics.DrawString(TicCode, DrawFont, brush, 600, 600); //绘制字符串
12             e.HasMorePages = false;
13         }
打印图片

注册打印方法:

1 using (PrintDocument pd = new PrintDocument()) {
2                     pd.PrintPage += PicturePrintDocument_PrintPage; //注册打印事件
3                     pd.PrinterSettings.PrinterName = printName;        //打印机选择
4                     pd.Print();
5                     pd.Dispose();
6                 }
注册打印方法

 自己封装的工具类:

using luzhoulaojiao.utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI.WebControls;

namespace WebApplication2.utils
{
    public class PrintUtil
    {
        // 打印类型2
        private static int print2StartX = Convert.ToInt32(ConfigurationManager.AppSettings["print2StartX"]);
        private static int print2StartY = Convert.ToInt32(ConfigurationManager.AppSettings["print2StartY"]);
        private static int print2Width = Convert.ToInt32(ConfigurationManager.AppSettings["print2Width"]);
        private static int print2Hight = Convert.ToInt32(ConfigurationManager.AppSettings["print2Hight"]);
        private static int print2Top = Convert.ToInt32(ConfigurationManager.AppSettings["print2Top"]);
        // 打印类型4
        private static int print4StartX = Convert.ToInt32(ConfigurationManager.AppSettings["print4StartX"]);
        private static int print4StartY = Convert.ToInt32(ConfigurationManager.AppSettings["print4StartY"]);
        private static int print4Width = Convert.ToInt32(ConfigurationManager.AppSettings["print4Width"]);
        private static int print4Hight = Convert.ToInt32(ConfigurationManager.AppSettings["print4Hight"]);
        private static int print4Left = Convert.ToInt32(ConfigurationManager.AppSettings["print4Left"]);
        private static int print4Top = Convert.ToInt32(ConfigurationManager.AppSettings["print4Top"]);
        // a4纸配置
        private static int a4Width = Convert.ToInt32(ConfigurationManager.AppSettings["a4Width"]);
        private static int a4Height = Convert.ToInt32(ConfigurationManager.AppSettings["a4Height"]);

        private static String filePath = "";
        /**
         * 打印类型2打印方法
         *
         * **/
        public static void PrintDo2(List images, String printName, String printSourceName)
        {
            Bitmap img = new Bitmap(a4Width, a4Height);
            Graphics g;//创建Graphics
            g = Graphics.FromImage(img);
            for (int i = 0; i < images.Count(); i++)
            {
                #region 文件位置处理
                if (i == 0)
                {
                    // 第一张图片
                    g.DrawImage(images[i], print2StartX, print2StartY, print2Width, print2Hight);
                }
                else if (i == 1)
                {
                    // 第二张图片
                    g.DrawImage(images[i], print2StartX, print2StartY + print2Hight + print2Top, print2Width, print2Hight);
                }
                #endregion
            }
            String uuid = Guid.NewGuid().ToString("N");
            string path = HttpContext.Current.Server.MapPath("~/files/" + uuid + ".jpg");
            #region 打印处理
            try
            {
                using (PrintDocument pd = new PrintDocument())
                {
                    img.Save(path);
                    filePath = path;
                    PrinterSettings ps = new PrinterSettings();
                    ps.PrinterName = printName;
                    for (int i = 0; i < ps.PaperSources.Count; i++)
                    {
                        if (ps.PaperSources[i].SourceName == printSourceName) {
                            pd.DefaultPageSettings.PaperSource = ps.PaperSources[i];// 选择纸盒
                        }
                    }
                    pd.PrintPage += PicturePrintDocument_PrintPage; //注册打印事件
                    pd.PrinterSettings.PrinterName = printName;        //打印机选择
                   
                    pd.Print();
                    pd.Dispose();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // 打印完删除文件
                File.Delete(filePath);
                filePath = "";
            }
            #endregion

        }



        /**
        * 打印类型4打印方法
        *
        * **/
        public static void PrintDo4(List images, String printName, String printSourceName)
        {
           
            Bitmap img = new Bitmap(a4Width, a4Height);
            Graphics g = Graphics.FromImage(img);
            g = Graphics.FromImage(img);
            g.Clear(Color.White);
            for (int i = 0; i < images.Count(); i++)
            {
                Bitmap map = new Bitmap(images[i]);
                map.RotateFlip(RotateFlipType.Rotate270FlipXY);
                System.Drawing.Image turnImage = map;
                if (i == 0)
                {
                    // 第一张图片
                    g.DrawImage(turnImage, print4StartX, print4StartY, print4Width, print4Hight);
                }
                else if (i == 1)
                {
                    // 第二张图片
                    g.DrawImage(turnImage, print4StartX + print4Width + print4Left, print4StartY, print4Width, print4Hight);
                }
                else if (i == 2)
                {
                    // 第三张图片
                    g.DrawImage(turnImage, print4StartX, print4StartY + print4Hight + print4Top, print4Width, print4Hight);
                }
                else if (i == 3)
                {
                    // 第四张图片
                    g.DrawImage(turnImage, print4StartX + print4Width + print4Left, print4StartY + print4Hight + print4Top, print4Width, print4Hight);
                }
            }
            String uuid = Guid.NewGuid().ToString("N"); ;
            string path = HttpContext.Current.Server.MapPath("~/files/" + uuid + ".jpg");
            #region 打印处理
            try
            {
                using (PrintDocument pd = new PrintDocument()) {
                    img.Save(path);
                    filePath = path;
                    PrinterSettings ps = new PrinterSettings();
                    ps.PrinterName = printName;
                    for (int i = 0; i < ps.PaperSources.Count; i++)
                    {
                        if (ps.PaperSources[i].SourceName == printSourceName)
                        {
                            pd.DefaultPageSettings.PaperSource = ps.PaperSources[i];//选择纸盒
                        }
                    }
                    pd.PrintPage += PicturePrintDocument_PrintPage; //注册打印事件
                    pd.PrinterSettings.PrinterName = printName;        //打印机选择
                    pd.Print();
                    pd.Dispose();
                }
                
            }
            catch (Exception)
            {
                throw;
            }
            finally {
                // 打印完删除文件
                File.Delete(filePath);
                filePath = "";
            }
            #endregion
        }

        [DllImport("gdi32.dll")]
        private static extern int GetDeviceCaps(IntPtr hdc, int Index);

        public static double MillimetersToPixelsWidth(double length) //length是毫米,1厘米=10毫米l
        {
            System.Windows.Forms.Panel p = new System.Windows.Forms.Panel();
            Graphics g = Graphics.FromHwnd(p.Handle);
            IntPtr hdc = g.GetHdc();
            int width = GetDeviceCaps(hdc, 4);     // HORZRES 
            int pixels = GetDeviceCaps(hdc, 8);     // BITSPIXEL
            g.ReleaseHdc(hdc);
            return (((double)pixels / (double)width) * (double)length);
        }

        public static void printOne(int size, System.Drawing.Image image,String printName,String printSourceName)
        {

            String uuid = Guid.NewGuid().ToString("N"); ;
            string path = HttpContext.Current.Server.MapPath("~/files/" + uuid + ".jpg");
            if (size == 7)
            {
                int width = Convert.ToInt32(MillimetersToPixelsWidth(120));
                int height = Convert.ToInt32(MillimetersToPixelsWidth(171));
                Bitmap map = new Bitmap(image);
                map.RotateFlip(RotateFlipType.Rotate270FlipXY);
                System.Drawing.Image turnImage = map;
                Bitmap img = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(img);
                g = Graphics.FromImage(img);
                g.Clear(Color.Red);
                int xx = (img.Width - width) / 2;
                int yy = (img.Height - height) / 2;
                g.DrawImage(turnImage, 0, 0, width, height);
                img.Save(path);
                filePath = path;
            }
            else if (size == 8)
            {
                int width = Convert.ToInt32(MillimetersToPixelsWidth(120));
                int height = Convert.ToInt32(MillimetersToPixelsWidth(196.2));
                Bitmap map = new Bitmap(image);
                map.RotateFlip(RotateFlipType.Rotate270FlipXY);
                System.Drawing.Image turnImage = map;
                Bitmap img = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(img);
                g = Graphics.FromImage(img);
                g.Clear(Color.White);
                int xx = (img.Width - width) / 2;
                int yy = (img.Height - height) / 2;
                g.DrawImage(turnImage, 0, 0, width, height);
                img.Save(path);
                filePath = path;
            }
            else if (size == 10)
            {
                int width = Convert.ToInt32(MillimetersToPixelsWidth(196.2));
                int height = Convert.ToInt32(MillimetersToPixelsWidth(247));
                Bitmap map = new Bitmap(image);
                map.RotateFlip(RotateFlipType.Rotate270FlipXY);
                System.Drawing.Image turnImage = map;
                Bitmap img = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(img);
                g = Graphics.FromImage(img);
                g.Clear(Color.White);
                int xx = (img.Width - width) / 2;
                int yy = (img.Height - height) / 2;
                g.DrawImage(turnImage, 0, 0, width, height);
                img.Save(path);
                filePath = path;
            }
            
            #region 打印处理
            try
            {
                using (PrintDocument pd = new PrintDocument())
                {
                    PrinterSettings ps = new PrinterSettings();
                    ps.PrinterName = printName;
                    for (int i = 0; i < ps.PaperSources.Count; i++)
                    {
                        if (ps.PaperSources[i].SourceName == printSourceName)
                        {
                            pd.DefaultPageSettings.PaperSource = ps.PaperSources[i];//选择纸盒
                        }
                    }
                    pd.PrintPage += PicturePrintDocument_PrintPage; //注册打印事件
                    pd.PrinterSettings.PrinterName = printName;        //打印机选择
                    pd.Print();
                    pd.Dispose();
                }

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // 打印完删除文件
                File.Delete(filePath);
                filePath = "";
            }
            #endregion
        }

        private static void PicturePrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            FileStream fs = File.OpenRead(filePath);
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组 
            fs.Read(image, 0, filelength); //按字节流读取 
            System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            e.Graphics.DrawImage(result, 0, 0);  //img大小
            //e.Graphics.DrawString(TicCode, DrawFont, brush, 600, 600); //绘制字符串
            e.HasMorePages = false;
        }

        /**
         * 刷新配置
         * **/
        private static void RefreshConfig()
        {
            
            print2StartX = Convert.ToInt32(ConfigurationManager.AppSettings["print2StartX"]);
            print2StartY = Convert.ToInt32(ConfigurationManager.AppSettings["print2StartY"]);
            print2Width = Convert.ToInt32(ConfigurationManager.AppSettings["print2Width"]);
            print2Hight = Convert.ToInt32(ConfigurationManager.AppSettings["print2Hight"]);
            print2Top = Convert.ToInt32(ConfigurationManager.AppSettings["print2Top"]);
            print4StartX = Convert.ToInt32(ConfigurationManager.AppSettings["print4StartX"]);
            print4StartY = Convert.ToInt32(ConfigurationManager.AppSettings["print4StartY"]);
            print4Width = Convert.ToInt32(ConfigurationManager.AppSettings["print4Width"]);
            print4Hight = Convert.ToInt32(ConfigurationManager.AppSettings["print4Hight"]);
            print4Left = Convert.ToInt32(ConfigurationManager.AppSettings["print4Left"]);
            print4Top = Convert.ToInt32(ConfigurationManager.AppSettings["print4Top"]);
            a4Width = Convert.ToInt32(ConfigurationManager.AppSettings["a4Width"]);
            a4Height = Convert.ToInt32(ConfigurationManager.AppSettings["a4Height"]);
        }

        /**
         * 获取配置
         * **/
        public static PrintCacheConfig GetCache()
        {
            PrintCacheConfig cacheConfig = new PrintCacheConfig();
            cacheConfig.print2StartX = Convert.ToInt32(ConfigurationManager.AppSettings["print2StartX"]);
            cacheConfig.print2StartY = Convert.ToInt32(ConfigurationManager.AppSettings["print2StartY"]);
            cacheConfig.print2Width = Convert.ToInt32(ConfigurationManager.AppSettings["print2Width"]);
            cacheConfig.print2Hight = Convert.ToInt32(ConfigurationManager.AppSettings["print2Hight"]);
            cacheConfig.print2Top = Convert.ToInt32(ConfigurationManager.AppSettings["print2Top"]);
            cacheConfig.print4StartX = Convert.ToInt32(ConfigurationManager.AppSettings["print4StartX"]);
            cacheConfig.print4StartY = Convert.ToInt32(ConfigurationManager.AppSettings["print4StartY"]);
            cacheConfig.print4Width = Convert.ToInt32(ConfigurationManager.AppSettings["print4Width"]);
            cacheConfig.print4Hight = Convert.ToInt32(ConfigurationManager.AppSettings["print4Hight"]);
            cacheConfig.print4Left = Convert.ToInt32(ConfigurationManager.AppSettings["print4Left"]);
            cacheConfig.print4Top = Convert.ToInt32(ConfigurationManager.AppSettings["print4Top"]);
            cacheConfig.a4Width = Convert.ToInt32(ConfigurationManager.AppSettings["a4Width"]);
            cacheConfig.a4Height = Convert.ToInt32(ConfigurationManager.AppSettings["a4Height"]);
            return cacheConfig;
        }


        /**
         * 写配置
         * **/
        public static void SaveCache(PrintCacheConfig config)
        { 
            Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            configuration.AppSettings.Settings.Remove("print2StartX");
            configuration.AppSettings.Settings.Add("print2StartX", config.print2StartX.ToString());
           
            configuration.AppSettings.Settings.Remove("print2StartY");
            configuration.AppSettings.Settings.Add("print2StartY", config.print2StartY.ToString());

            configuration.AppSettings.Settings.Remove("print2Width");
            configuration.AppSettings.Settings.Add("print2Width", config.print2Width.ToString());

            configuration.AppSettings.Settings.Remove("print2Hight");
            configuration.AppSettings.Settings.Add("print2Hight", config.print2Hight.ToString());

            configuration.AppSettings.Settings.Remove("print2Top");
            configuration.AppSettings.Settings.Add("print2Top", config.print2Top.ToString());

            configuration.AppSettings.Settings.Remove("print4StartX");
            configuration.AppSettings.Settings.Add("print4StartX", config.print4StartX.ToString());

            configuration.AppSettings.Settings.Remove("print4StartX");
            configuration.AppSettings.Settings.Add("print4StartX", config.print4StartX.ToString());

            configuration.AppSettings.Settings.Remove("print4StartY");
            configuration.AppSettings.Settings.Add("print4StartY", config.print4StartY.ToString());

            configuration.AppSettings.Settings.Remove("print4Width");
            configuration.AppSettings.Settings.Add("print4Width", config.print4Width.ToString());

            configuration.AppSettings.Settings.Remove("print4Hight");
            configuration.AppSettings.Settings.Add("print4Hight", config.print4Hight.ToString());

            configuration.AppSettings.Settings.Remove("print4Left");
            configuration.AppSettings.Settings.Add("print4Left", config.print4Left.ToString());

            configuration.AppSettings.Settings.Remove("print4Top");
            configuration.AppSettings.Settings.Add("print4Top", config.print4Top.ToString());

            configuration.AppSettings.Settings.Remove("a4Width");
            configuration.AppSettings.Settings.Add("a4Width", config.a4Width.ToString());

            configuration.AppSettings.Settings.Remove("a4Height");
            configuration.AppSettings.Settings.Add("a4Height", config.a4Height.ToString());

            configuration.Save();
            RefreshConfig();
        }

    }
}
工具类