C#實現呼叫印表機(列印字串、列印繪圖、列印圖片)

C#實現呼叫印表機(列印字串、列印繪圖、列印圖片)

C#實現呼叫印表機(列印字串、列印繪圖、列印圖片)


資料來源: https://www.796t.com/content/1543859288.html


code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Printer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private Font printFont;
        private Font titleFont;
        private StringReader streamToPrint;
        private int leftMargin = 0;

         /// <summary>
        /// 設定PrintDocument 的相關屬性 呼叫印表機方法
        /// </summary>
        /// <param name="str">要列印的字串</param>
        public void print(string str)
        {
            try
            {
                //列印文字
                streamToPrint = new StringReader(str);
                printFont = new Font("宋體", 10);
                titleFont = new Font("宋體", 15);
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                //呼叫的印表機名
                pd.PrinterSettings.PrinterName = "Hewlett-Packard HP LaserJet Pro MFP M126a";
                pd.DocumentName = pd.PrinterSettings.MaximumCopies.ToString(); 
                pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.pd_PrintPage);
               // pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.MyPrintDocument_PrintPage);
                pd.PrintController = new System.Drawing.Printing.StandardPrintController(); 
                pd.Print();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        /// <summary>
        /// 列印格式(字串)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = this.leftMargin;
            float topMargin = 0;
            String line = null;
            linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
            while (count < linesPerPage &&
            ((line = streamToPrint.ReadLine()) != null))
            {
                if (count == 0)
                {
                    yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                    ev.Graphics.DrawString(line, titleFont, Brushes.Black, leftMargin + 10, yPos, new StringFormat());
                }
                else
                {
                    yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                    ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                }
                count++;
            }
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;

        }


        private void button1_Click(object sender, EventArgs e)
        {
            //列印報表解決方案一:

            string ss = "選單";
            //呼叫本地印表機成功:注意的問題的是印表機的名字和印表機的驅動安裝
            print("主題\n------------\n被冷冷地:"+ss+"\n-------------\n說到了");


            //獲取本地印表機的名字
            GetPrintName();
        }

        /// <summary>
        /// 獲取印表機的名字
        /// </summary>
        private void GetPrintName()
        {
            //獲取本地印表機的名字
            PrintDocument print = new PrintDocument();
            string sDefault = print.PrinterSettings.PrinterName;//預設印表機名

            label1.Text = sDefault;
            
            foreach (string sPrint in PrinterSettings.InstalledPrinters)//獲取所有印表機名稱
            {
                listBox1.Items.Add(sPrint);
                textBox1.Text += sPrint + "\n";
                if (sPrint == sDefault)
                    listBox1.SelectedIndex = listBox1.Items.IndexOf(sPrint);

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO:  這行程式碼將資料載入到表“weijiaweiDataSet.xinxibiao”中。您可以根據需要移動或刪除它。
           // this.xinxibiaoTableAdapter.Fill(this.weijiaweiDataSet.xinxibiao);

            this.reportViewer1.RefreshReport();
            this.reportViewer1.RefreshReport();
        }

        private void button2_Click(object sender, EventArgs e)
        {


            print2();

        }

        /// <summary>
        /// 設定PrintDocument 的相關屬性
        /// </summary>
        /// <param name="str">要列印的字串</param>
        public void print2()
        {
            try
            {
               // streamToPrint = new StringReader(str);
                printFont = new Font("宋體", 10);
                titleFont = new Font("宋體", 15);
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                pd.PrinterSettings.PrinterName = "Hewlett-Packard HP LaserJet Pro MFP M126a";
                pd.DocumentName = pd.PrinterSettings.MaximumCopies.ToString();
                //pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.pd_PrintPage);
                pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.MyPrintDocument_PrintPage);
                pd.PrintController = new System.Drawing.Printing.StandardPrintController();
                pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        /// <summary>
        /// 列印的格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MyPrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            /*如果需要改變自己 可以在new Font(new FontFamily("黑體"),11)中的“黑體”改成自己要的字型就行了,黑體 後面的數字代表字型的大小
             System.Drawing.Brushes.Blue , 170, 10 中的 System.Drawing.Brushes.Blue 為顏色,後面的為輸出的位置 */
            e.Graphics.DrawString("新鄉市三月軟體公司入庫單", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 170, 10);
            e.Graphics.DrawString("供貨商:河南科技學院", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Blue, 10, 12);
            //資訊的名稱
            e.Graphics.DrawLine(Pens.Black, 8, 30, 480, 30);
            e.Graphics.DrawString("入庫單編號", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 9, 35);
            e.Graphics.DrawString("商品名稱", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 160, 35);
            e.Graphics.DrawString("數量", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 260, 35);
            e.Graphics.DrawString("單價", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 330, 35);
            e.Graphics.DrawString("總金額", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 400, 35);
            e.Graphics.DrawLine(Pens.Black, 8, 50, 480, 50);
            //產品資訊
            e.Graphics.DrawString("R2011-01-2016:06:35", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 9, 55);
            e.Graphics.DrawString("聯想A460", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 160, 55);
            e.Graphics.DrawString("100", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 260, 55);
            e.Graphics.DrawString("200.00", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 330, 55);
            e.Graphics.DrawString("20000.00", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 400, 55);


            e.Graphics.DrawLine(Pens.Black, 8, 200, 480, 200);
            e.Graphics.DrawString("地址:新鄉市河南科技學院資訊工程學院", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 9, 210);
            e.Graphics.DrawString("經辦人:任忌", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 220, 210);
            e.Graphics.DrawString("服務熱線:15083128577", new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 320, 210);
            e.Graphics.DrawString("入庫時間:" + DateTime.Now.ToString(), new Font(new FontFamily("黑體"), 8), System.Drawing.Brushes.Black, 9, 230);
        }


        private void button3_Click(object sender, EventArgs e)
        {
            // printDocument1 為 列印控制元件
            //設定列印用的紙張 當設定為Custom的時候,可以自定義紙張的大小,還可以選擇A4,A5等常用紙型
            
            //先註釋和不註釋來看取列印的內容   格式一測試失敗

            //格式一:
           // this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custom", 500, 300);
            //this.printDocument1.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

            //格式二:
          //  this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custom", 500, 300);
          //  this.printDocument1.PrintPage += new PrintPageEventHandler(this.MyPrintDocument_PrintPage);

            //格式:選單
           // this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custom", 300,500);
           // this.printDocument1.PrintPage += new PrintPageEventHandler(this.Menu);

            //列印圖片
            this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custom", 300, 500);
            this.printDocument1.PrintPage += new PrintPageEventHandler(this.Image);


            //將寫好的格式給列印預覽控制元件以便預覽
            printPreviewDialog1.Document = printDocument1;

            //顯示列印預覽
            DialogResult result = printPreviewDialog1.ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            print3();

        }


        /// <summary>
        /// 設定PrintDocument 的相關屬性
        /// </summary>
        /// <param name="str"></param>
        public void print3()
        {
            try
            {
                /*
                // streamToPrint = new StringReader(str);
                printFont = new Font("宋體", 10);
                titleFont = new Font("宋體", 15);
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                pd.PrinterSettings.PrinterName = "Hewlett-Packard HP LaserJet Pro MFP M126a";
                pd.DocumentName = pd.PrinterSettings.MaximumCopies.ToString();
                //pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.pd_PrintPage);
                pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.Menu);
                pd.PrintController = new System.Drawing.Printing.StandardPrintController();
                pd.Print();
                 
                 */

        

                //新建列印物件
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                //印表機名字
                pd.PrinterSettings.PrinterName = "Hewlett-Packard HP LaserJet Pro MFP M126a";
                //列印文件顯示的名字
                pd.DocumentName = "訂單";
                //
                //pd.PrinterSettings.MaximumCopies.ToString();

                //列印的格式
                pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.Menu);

                //
                pd.PrintController = new System.Drawing.Printing.StandardPrintController();

                //開始列印
                pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        //繪圖需要使用的陣列 後期可以套用變數list
        public string[] menu = { "菜一", "菜二","中級選單" };

        /// <summary>
        /// 列印的格式:選單
        /// </summary>
        /// <param name="sender">自定義報表(原理是繪圖)</param>
        /// <param name="e"></param>
        private void Menu(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {

              //繪製(輸出,文字格式(字型,大小),顏色,位置起始位置x,y軸座標)                 
            e.Graphics.DrawString("店名", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 138, 10);
           
            //列印兩個點的座標(顏色,座標1,座標2)
            e.Graphics.DrawLine(Pens.Black, 8, 30, 292, 30);


            e.Graphics.DrawString("訂單號:()", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 10, 35);

            e.Graphics.DrawString("編號", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 10, 55);
            e.Graphics.DrawString("菜名", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 75, 55);
            e.Graphics.DrawString("單價", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 150, 55);
            e.Graphics.DrawString("數量", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 200, 55);

            int i = 0;
            //迴圈輸出變數
            foreach (string element in menu)
            {
             
                i=i+20;
                e.Graphics.DrawString(element, new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 75, 80+i);

            }


            e.Graphics.DrawLine(Pens.Black, 8, 200, 292, 200);

         }


        private void button5_Click(object sender, EventArgs e)
        {
            print4();
        }

        public void print4()
        {
            try
            {

                //新建列印物件
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                //印表機名字
                pd.PrinterSettings.PrinterName = "Hewlett-Packard HP LaserJet Pro MFP M126a";
                //列印文件顯示的名字
                pd.DocumentName = "訂單";
                //
                //pd.PrinterSettings.MaximumCopies.ToString();

                //列印的格式
                pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.Image);

                //
                pd.PrintController = new System.Drawing.Printing.StandardPrintController();

                //開始列印
                pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        /// <summary>
        /// 列印的格式:圖片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            //直接呼叫圖片物件繪製
            e.Graphics.DrawImage(pictureBox1.Image, 20, 20);

        }

        private void button6_Click(object sender, EventArgs e)
        {
            printDocument1.PrintController.OnEndPrint(printDocument1, new System.Drawing.Printing.PrintEventArgs());
        }

    }
}

2 thoughts on “C#實現呼叫印表機(列印字串、列印繪圖、列印圖片)

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *