I want to Print my HTML document directly to a specific network printer without printer dialog window when the end user click on PRINT button. I do search and follow this but this opens a dialog window to save the document as pdf.
Based On The Comments:
public static class PrinterClass
{
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Printer);
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//List<string> st = new List<string>();
//foreach (string strPrinter in PrinterSettings.InstalledPrinters)
//{
// if (strPrinter.Contains("My Printer"))
// {
// PrinterClass.SetDefaultPrinter(strPrinter);
// }
// st.Add(strPrinter);
//}
SetDefaultPrinter("Send To OneNote 2016");
}
WebBrowser webBrowser = new WebBrowser();
void Print(string str)
{
webBrowser.DocumentText = str;
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
}
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
IHTMLDocument2 d2;
d2 = (IHTMLDocument2)((WebBrowser)sender).Document.DomDocument;
d2.execCommand("Print", false, null);
}
private void btn_print_Click(object sender, EventArgs e)
{
Print("<html><body>..some html code..</body></html>");
}
public static bool SetDefaultPrinter(string defaultPrinter)
{
using (ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer"))
{
using (ManagementObjectCollection objectCollection = objectSearcher.Get())
{
foreach (ManagementObject mo in objectCollection)
{
if (string.Compare(mo["Name"].ToString(), defaultPrinter, true) == 0)
{
mo.InvokeMethod("SetDefaultPrinter", null, null);
return true;
}
}
}
}
return false;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…