Csharp: print Card using HiTi CS310

简介: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace FeaTon.WaterImage
{
    /// <summary>
    /// 員工IC卡打印
    /// 塗聚文 20121225
    /// 
    /// </summary>
    public partial class IdCardForm : Form
    {
        /// <summary>
        /// 卡底圖
        /// </summary>
        string path = string.Empty;
        /// <summary>
        /// 卡相片
        /// </summary>
        string Photopath = string.Empty;
        /// <summary>
        /// 設置字體
        /// </summary>
        string setFont = "宋体";

        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]//应用API函数
        private static extern bool BitBlt(
        IntPtr hdcDest, // 目标设备的句柄 
        int nXDest, // 目标对象的左上角的X坐标 
        int nYDest, // 目标对象的左上角的X坐标 
        int nWidth, // 目标对象的矩形的宽度 
        int nHeight, // 目标对象的矩形的长度 
        IntPtr hdcSrc, // 源设备的句柄 
        int nXSrc, // 源对象的左上角的X坐标 
        int nYSrc, // 源对象的左上角的X坐标 
        System.Int32 dwRop // 光栅的操作值 
        );

        /// <summary>
        /// 
        /// </summary>
        public IdCardForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 查找安裝的打印機
        /// </summary>
        private void PopulateInstalledPrintersCombo()
        {
            System.Data.DataTable PrintersList = new System.Data.DataTable();
            PrintersList.Columns.Add("id", typeof(int));
            PrintersList.Columns.Add("InstalledPrinters", typeof(string));
            // Add list of installed printers found to the combo box.
            // The pkInstalledPrinters string will be used to provide the display string.
            String pkInstalledPrinters;
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                //comboInstalledPrinters.Items.Add(pkInstalledPrinters);
                PrintersList.Rows.Add(i, pkInstalledPrinters);

            }
            comboInstalledPrinters.DataSource = PrintersList;
            comboInstalledPrinters.DisplayMember = "InstalledPrinters";
            comboInstalledPrinters.ValueMember = "id";
            comboInstalledPrinters.AutoCompleteMode = AutoCompleteMode.Suggest;
            comboInstalledPrinters.AutoCompleteSource = AutoCompleteSource.ListItems;
            
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IdCardForm_Load(object sender, EventArgs e)
        {
            //尋找本地安裝打印機
            PopulateInstalledPrintersCombo();

            //
            //尋找本地安裝字體
            InstalledFontCollection fontCollection = new InstalledFontCollection();
            foreach (FontFamily fontFamily in fontCollection.Families)
            {
                this.comboBoxFont.Items.Add(fontFamily.Name);
                
            }

           this.comboBoxFont.SelectedIndex = 10;
            
                //Response.Redirect(newPath); 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboInstalledPrinters_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboInstalledPrinters.SelectedIndex != -1)
            {
                // The combo box's Text property returns the selected item's text, which is the printer name.
                printDocument1.PrinterSettings.PrinterName = comboInstalledPrinters.Text;
            }
        }
        /// <summary>
        ///  Define DrawImageAbort callback method.
        /// </summary>
        /// <param name="callBackData"></param>
        /// <returns></returns>
        private bool DrawImageCallback4(IntPtr callBackData)
        {

            // Test for call that passes callBackData parameter.
            if (callBackData == IntPtr.Zero)
            {

                // If no callBackData passed, abort DrawImage method.
                return true;
            }
            else
            {

                // If callBackData passed, continue DrawImage method.
                return false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {

            // Create callback method.
            Graphics.DrawImageAbort imageCallback
                = new Graphics.DrawImageAbort(DrawImageCallback4);
            IntPtr imageCallbackData = new IntPtr(1);

            pictureBox1.Width = Width;
            pictureBox1.Height = Height;
            System.Drawing.Image image = this.pictureBox1.Image;
            int x = Convert.ToInt32(e.MarginBounds.X - e.PageSettings.HardMarginX);
            x = Screen.PrimaryScreen.Bounds.Width;
            int y = Convert.ToInt32(e.MarginBounds.Y - e.PageSettings.HardMarginY);
            y = Screen.PrimaryScreen.Bounds.Height;

            System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(0, 0, Width, Height);
            
           System.Drawing.Image image1 = resizeImage(image,new  Size(Width, Height));
           // Create image attributes and set large gamma.
           ImageAttributes imageAttr = new ImageAttributes();
           imageAttr.SetGamma(4.0F);
           GraphicsUnit units = GraphicsUnit.Pixel;

           e.Graphics.DrawImage(image1, destRect, 0, 0, image1.Width, image1.Height, units);//, imageAttr, imageCallback, imageCallbackData
           //e.HasMorePages = false;
           //IntPtr dc1 = e.Graphics.GetHdc();
           //IntPtr dc2 = e.Graphics.GetHdc();
           //   BitBlt(dc2, 0, 0, panel4.ClientRectangle.Width, panel4.ClientRectangle.Height,dc1, 0, 0, 13369376);
           //BitBlt(dc1, 0, 0, image1.Width, 1024, dc1, 0, 0, 13369376);

        }
        /// <summary>
        /// 因為沒有引用HiTi打卡打印機的SDK,無法打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonPrint_Click(object sender, EventArgs e)
        {
            PaperSize pkCustomSize = new PaperSize("Custum", 775, 453); //員工IC卡格式
            this.printDocument1.DefaultPageSettings.PaperSize = pkCustomSize;
            //printPreviewDialog1.SetBounds(0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            pageSetupDialog1.PageSettings.Landscape = false; //true縱向   //false橫向
            int width = 775;  //216*97
            int height = 453;//(int)(101 * 100 / 25.4 + 1);
            foreach (PaperSize paperSize in printDocument1.PrinterSettings.PaperSizes)
            {
                if (paperSize.Height == width && paperSize.Height == height)//paperSize.PaperName == "Custum" &&
                {

                    printDocument1.DefaultPageSettings.PaperSize = paperSize;
                    break;
                }
            }
            if(printPreviewDialog1.ShowDialog()== DialogResult.Yes)
            {
                //System.Drawing.Printing.Duplex
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
                pd.Print();
                //printDocument1.Print();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="imgToResize"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        private static Image resizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (Image)b;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxFont_SelectedIndexChanged(object sender, EventArgs e)
        {
            setFont = this.comboBoxFont.Text;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonImage_Click(object sender, EventArgs e)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(Application.StartupPath + "\\temp\\");
            //加文字水印,注意,这里的代码和以下加图片水印的代码不能共存  
            path = dirInfo + "id4.jpg";
            string newpath = dirInfo + "id4001.jpg";
            System.Drawing.Image image = System.Drawing.Image.FromFile(path);
            Graphics g = Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            Font f = new Font(setFont, 18, FontStyle.Bold); //字體大小
            Font fno = new Font(setFont, 10, FontStyle.Bold);
            Font fclerk = new Font(setFont, 8, FontStyle.Bold);
            Brush b = new SolidBrush(Color.Black); //字體顏色                
            string addText = "塗聚文";
            //new RectangleF(0, 0, 500, 500), strFormat)  
            g.DrawString(addText, f, b, new RectangleF(130, 220, 550, 110), new StringFormat());//放的姓名位置
            g.DrawString("行政及人事管理人員", fclerk, b, new RectangleF(130, 410, 550, 110), new StringFormat());//放職稱的位置
            g.DrawString("行政及人力资源管理部", fno, b, new RectangleF(130, 470, 550, 110), new StringFormat());//放部門名稱的位置
            g.DrawString("L00094", fno, b, new RectangleF(130, 540, 550, 110), new StringFormat()); //放員工編號的位置
            
            image.Save(newpath);
            g.Dispose();
            image.Dispose();



            //加图片水印 System.Drawing.Image                  
            image = System.Drawing.Image.FromFile(newpath);

            int xPosOfWm;
            int yPosOfWm;
            int phWidth = image.Width;
            int phHeight = image.Height;
            Photopath = dirInfo + "2cun.jpg"; //2寸照片
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Photopath);
            int wmWidth = copyImage.Width;
            int wmHeight = copyImage.Height;
            Graphics g1 = Graphics.FromImage(image);

            xPosOfWm = phWidth - wmWidth - 80;
            yPosOfWm = 80;
            StringFormat strFormat = new StringFormat();

            g1.DrawImage(copyImage, new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            g1.Dispose();

            //保存加水印过后的图片,删除原始图片                  
            string newPath = string.Empty; //Server.MapPath(".") + "/UploadFile/" + fileName + "_new" + extension;   
            newPath = dirInfo + DateTime.Now.Ticks.ToString() + "_1011.jpg";
            image.Save(newPath);
            pictureBox1.Image = Image.FromFile(newPath);
            this.textBox1.Text = newPath;
            image.Dispose();
            if (File.Exists(newpath))
            {
                File.Delete(newpath);
            }               

        }
        /// <summary>
        /// 調用Windows圖片和傳真查看器
        /// HiTiCS3xx 卡片打印機,沒有調用其SDK只能這種方打印了。
        /// 塗聚文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //Process.Start("rundll32.exe", @"C:\Windows\System32\shimgvw.dll,ImageView_PrintTo /pt C:\0JQJ\Rose.tif");
            //Process.Start("rundll32.exe", @"C:\Windows\System32\shimgvw.dll,ImageView_PrintTo /pt C:\0JQJ\Rose.tif ADD-PRINTER17");
            //Process.Start("rundll32.exe", @"C:\Windows\System32\shimgvw.dll,ImageView_PrintTo /pt C:\0JQJ\Rose.tif ADDFILE00\ADD-PRINTER17");
            string Path = textBox1.Text;
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "rundll32.exe";
            startInfo.Arguments = @"D:\WINDOWS\System32\shimgvw.dll,ImageView_Fullscreen" + " " + Path;
            Process.Start(startInfo);
        }
        /// <summary>
        /// 員工卡圖片生成
        /// 由背景圖,貼上二寸照片,再加上個人信息而成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(Application.StartupPath + "\\temp\\");
            //加文字水印,注意,这里的代码和以下加图片水印的代码不能共存  
            path = dirInfo + "id4.jpg"; //底圖片     
            System.Drawing.Image image = System.Drawing.Image.FromFile(path);
            Graphics g = Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            Font f = new Font(setFont, 18, FontStyle.Bold); //字體大小
            Font fno = new Font(setFont, 10, FontStyle.Bold);
            Font fclerk = new Font(setFont, 8, FontStyle.Bold);
            Brush b = new SolidBrush(Color.Black); //字體顏色                
            string addText = "塗聚文";
            //new RectangleF(0, 0, 500, 500), strFormat)  
            g.DrawString(addText, f, b, new RectangleF(130, 220, 550, 110), new StringFormat());//放的姓名位置
            g.DrawString("行政及人事管理人員", fclerk, b, new RectangleF(130, 410, 550, 110), new StringFormat());//放職稱的位置
            g.DrawString("行政及人力资源管理部", fno, b, new RectangleF(130, 470, 550, 110), new StringFormat());//放部門名稱的位置
            g.DrawString("L00094", fno, b, new RectangleF(130, 540, 550, 110), new StringFormat()); //放員工編號的位置

            int xPosOfWm;
            int yPosOfWm;
            int phWidth = image.Width;
            int phHeight = image.Height;
            Photopath = dirInfo + "2cun.jpg"; //2寸照片
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Photopath);
            int wmWidth = copyImage.Width;
            int wmHeight = copyImage.Height;


            xPosOfWm = phWidth - wmWidth - 80;
            yPosOfWm = 80;
            StringFormat strFormat = new StringFormat();

            g.DrawImage(copyImage, new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            

            //保存加水印过后的图片,删除原始图片                  
            string newPath = string.Empty; //Server.MapPath(".") + "/UploadFile/" + fileName + "_new" + extension;   
            newPath = dirInfo + DateTime.Now.Ticks.ToString() + "_1011.jpg";
            image.Save(newPath);
            pictureBox1.Image = Image.FromFile(newPath);
            this.textBox1.Text = newPath;
            g.Dispose();
            image.Dispose();
            //if (File.Exists(newPath))
            //{
            //    File.Delete(newPath);
            //}               

        }
    }
}

目录
相关文章
打印文档即提示Print driver host for 32bit applications
主机win7 32位系统,打印一切正常,共享打印机后,客户机为win7 64位系统连接该共享打印机,连接成功,驱动安装正常,x64驱动,客户机打印测试页正常,但打印文档即提示Print driver host for 32bit applications。
7760 0
打印文档即提示Print driver host for 32bit applications
|
5月前
解决Vscode使用LeetCode报错Failed to test the solution. Please open the output channel for details.
本文提供了解决在VScode中使用LeetCode插件时遇到“Failed to test the solution. Please open the output channel for details.”错误的方法,主要是通过修改setting.json文件中的输出文件夹配置来解决。
469 1
|
8月前
|
IDE 开发工具 Android开发
Couldn‘t get post build model. Module:UpdateService_0804.main Variant: debugOpen logcat panel fo
Couldn‘t get post build model. Module:UpdateService_0804.main Variant: debugOpen logcat panel fo
110 0
TestRange.cs error CS0104: `Range' is an ambiguous reference between `System.Range' and Gtk.Range
TestRange.cs error CS0104: `Range' is an ambiguous reference between `System.Range' and Gtk.Range
188 0
SAP QM 执行事务代码QP01,系统报错 -Material type FOOD is not defined for task list type Q-
SAP QM 执行事务代码QP01,系统报错 -Material type FOOD is not defined for task list type Q-
SAP QM 执行事务代码QP01,系统报错 -Material type FOOD is not defined for task list type Q-
Cannot find source code based button in SE24
When you are logging on to customer system for incident handling, you want to switch to source code to perform some keyword search. However, you could not find button “Source code based builder” in toolbar, with following warning message: ———————————————— 版权声明:本文为CSDN博主「汪子熙」的原创文章,遵循CC 4.0 BY-SA版权协
Cannot find source code based button in SE24
vuepress build提示YAMLException: end of the stream or a document separator is expected at line 7, colu
vuepress build提示YAMLException: end of the stream or a document separator is expected at line 7, colu
878 0
|
数据库管理
Xamarin.Android 使用 SQLite 出现 Couldn't read row 0, col -1 from CursorWindow. 异常
异常:Java.Lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it. 出现该问题一般分为两种情况: 1.请求的字段不在表中,可能是大小写没写对。
6589 0