1

I have trouble with the printing function of the WebBrowser control.

First i load my page and it is rendered correct. Then i set the header/footer/margins and the right printer: webbrowser printing; How do I programatically change printer settings with the WebBrowser control?

That works so far. Then i use myBrowser.Print();

But my website does not print right. Only the upper left corner is printed, a few centimeters and then there are scrollbars.

I printed my website with the IE9 and everything was alright. Also tried different browsermodes and documentmodes. No problem. And i thought the control and the IE are technically the same...

Are there any parameters i have forgotten?

The website i want to print is old and has no doctype. But since the control displays it correct, I expect it to print correct, too.

Edit:

Found out that it has to do with javascript on the website, which does not run for printing. Is there a way to get the HTML from the manipulated DOM?

Community
  • 1
  • 1
Hannes
  • 76
  • 9
  • Have you considered using a HTML to PDF tool and then printing the pdf? They are marginally less twitchy than the browser control in Windows Forms. Also, welcome to Stack Overflow :) – linkerro Jul 04 '12 at 07:42
  • That is what i am developing... The problem: our website is generated with xsl/xslt and only the IE renders this right(We are working in that...). So we have to use this browser control. How do I close this question now? – Hannes Jul 04 '12 at 15:13
  • If you fixed it you can put an answer yourself and mark that as the accepted fix. If not, just delete it. – linkerro Jul 04 '12 at 15:50

1 Answers1

2

For the print function no external documents are processed. All documents for a website have to be merged into one printable site. To get the other documents you have to cast the myBrowser.Document.DomDocument to an IHTMLDocument2. From that IHTMLDocument2 you can extract the CSS or JS to put it into the html.

For Example:

    void myBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        myBrowser.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(myBrowser_DocumentCompleted);
        myBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(myBrowser_DocumentPrintable);
        String mySource = myBrowser.DocumentText;

        // Get the CSS
        IHTMLDocument2 doc = (myBrowser.Document.DomDocument) as IHTMLDocument2;
        myCSS = doc.styleSheets.item(0).cssText;
        mySource = mySource.Replace("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/style.css\">", "<style type=\"text/css\">"+myCSS+"</style>");

        // Reload
        myBrowser.DocumentText = mySource;
    }

    void myBrowser_DocumentPrintable(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        myBrowser.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(myBrowser_DocumentPrintable);
        myBrowser.Print();
    }
Hannes
  • 76
  • 9