Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically change printer settings with the WebBrowser control?

I finally figured out how to print transformed XML without prompting the user or showing an IE window, but now I need to specify a number of copies and possibly other printer settings.

Is there a way to programmatically change printer settings on a WebBrowser control?

The code in question:

private static void PrintReport(string reportFilename)
{
    WebBrowser browser = new WebBrowser();

    browser.DocumentCompleted += browser_DocumentCompleted;

    browser.Navigate(reportFilename);
}

private static void browser_DocumentCompleted
    (object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser browser = sender as WebBrowser;

    if (null == browser)
    {
        return;
    }

    browser.Print();

    browser.Dispose();
}
like image 531
Chris Doggett Avatar asked Apr 03 '09 15:04

Chris Doggett


2 Answers

The only method I've had success with is modifying the registry on the fly (and changing them back to not affect anything else).

You can find the settings you need at "Software\Microsoft\Internet Explorer\PageSetup" under CurrentUser.

To change the printer, you can use this:

using System.Management

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;
}


As for the number of copies, you can always put the WebBrowser.Print in a while loop.

like image 118
Austin Salonen Avatar answered Oct 11 '22 05:10

Austin Salonen


            string strKey = "Software\\Microsoft\\Internet Explorer\\PageSetup";
        bool bolWritable = true;

        RegistryKey oKey = Registry.CurrentUser.OpenSubKey(strKey, bolWritable);
        Console.Write(strKey);

        if (stringToPrint.Contains("Nalog%20za%20sluzbeno%20putovanje_files"))
        {
            oKey.SetValue("margin_bottom", 15);
            oKey.SetValue("margin_top", 0.19);
        }
        else
        {
            //Return onld walue
            oKey.SetValue("margin_bottom", 0.75);
            oKey.SetValue("margin_top", 0.75);
        }
like image 31
Nino Mirza Mušić Avatar answered Oct 11 '22 05:10

Nino Mirza Mušić