如何在C#中打印到网络打印机

时间:2016-01-26 10:32:47

标签: c# asp.net networking printing

我正在尝试在C#中将一组字符串打印到网络打印机。

我知道打印机的 IP MAC地址(未安装到我的电脑上)

问题是我无法检测到这台打印机。相反,我得到了4台本地打印机的集合,这些打印机安装在我的电脑上。

注意:我的电脑上还安装了2台网络打印机,但我也无法检测到它们。

这是我的代码:

public string PageCreate( string printerName, string jsonString ) {
    string result = "1";
    if ( jsonString != null && jsonString.Length > 0 ) {
        JObject jsonObj = JObject.Parse( jsonString );
        string userName = jsonObj["userName"].ToString();
        string userDept = jsonObj["userDept"].ToString();
        string userPhone = jsonObj["userPhone"].ToString();
        string date = jsonObj["date"].ToString();
        var items = jsonObj["items"];
        string total = jsonObj["total"].ToString();
        string comments = jsonObj["comments"].ToString();

        if ( items != null ) {                    
            try {
                StringBuilder sb = new StringBuilder();

                // Some string added to sb

                // Here I get 4 local printers in 'printers' collection
                string query = "SELECT * from Win32_Printer";
                ManagementObjectSearcher searcher = new ManagementObjectSearcher( query );
                ManagementObjectCollection printers = searcher.Get();

                foreach ( ManagementObject printer in printers ) {
                    if ( !String.IsNullOrEmpty( printer.Properties["PortName"].Value.ToString() ) ) {
                        PropertyDataCollection props = printer.Properties;
                        string port = printer.Properties["PortName"].Value.ToString();                                
                    }
                }

                stringToPrint = new StringReader( sb.ToString() );
                printFont = new Font( "Arial", 10 );

                PrintDocument doc = new PrintDocument();

                //printerName = XX.X.X.XXX (IP address)
                doc.PrinterSettings.PrinterName = printerName;
                doc.DocumentName = "ESS_Order_" + userName + "_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm");
                doc.PrintPage += new PrintPageEventHandler( this.PagePrint );
                if ( doc.PrinterSettings.IsValid ) {
                    doc.Print();
                }
            }
            catch {
                result = "0";
            }
            finally {
                stringToPrint.Close();
            }
        }
    }
    return result;
}

注意#2:我不想弹出打印机对话框

0 个答案:

没有答案