简体   繁体   中英

Printing a formatted HTML page in C#

I am looking for a way to print a formatted html file in landscape mode in c# (primarily wpf). Print dialog would be nice in order to set the page setting to landscape. I tried using Microsoft's html to xaml converter and it destroyed the formatting. I find it quite amazing that there is no method or grabbing a file and sending directly to a printer.

Any ideas would be much appreciated.

 WebBrowser myWebBrowser = new WebBrowser();
        private void Form1_Load(object sender, EventArgs e)
        {
            myWebBrowser.DocumentCompleted += myWebBrowser_DocumentCompleted;
            myWebBrowser.DocumentText  =System .IO.File .ReadAllText ( @"C:\a.htm");
        }

        private void myWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            myWebBrowser.Print();
        }

You can access the Print() method of the WebBrowser Class, in C# to do this. The cool thing is that you don't need to actually display the WebBrowser anywhere in your application. Just simply feed the content to the WebBrowser Control like so:

webBrowser1.DocumentContent = openfiledialog.FileName;

And then just call the webBrowser1.Print(); method. Here's an MSDN reference:

http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.print.aspx

Hope this helps.

For many years we used the .net WebBrowser control as outlined in other answers, however more recently that control has become more and more unstable. Even rebuilding the machine we use to print our pick sheets in the warehouse to run Windows 10, we still have problems with pages simply never printing until we reboot the computer. The same code served us well for 4+ years but now it appears recent updates from Microsoft have made this control even more buggy than it was in the past.

The other major issue is that there is no easy way to print to a printer other than the default set for Internet Explorer, so if you wish to print to different printers, you are pretty much out of luck with that control.

Many years ago we wrote a version of our printing code for packing slips using C++ and the QtWebKit library. So to solve these problems I dug up the old C++ application that printed web pages files and turned it into this project to print via the command line, and enabled it to print to different printers.

You can get the source code for it here:

https://github.com/kendallb/PrintHtml

and you can download a 32-bit binary pre-compiled for Windows using MinGW from here:

https://github.com/kendallb/PrintHtml/blob/master/deploy/PrintHtml-window-x86.zip?raw=true

The code is fully portable so you could easily compile it to run on macOS or Linux if desired from the source code.

The command line is pretty easy to use and the usage is below:

Usage: PrintHtml [-test] [-p printer] [-l left] [-t top] [-r right] [-b bottom] <url> [url2]

-test         - Don't print, just show what would have printed.
-p printer    - Printer to print to. Use 'Default' for default printer.
-l left       - Optional left margin for page.
-t top        - Optional top margin for page.
-r right      - Optional right margin for page.
-b bottom     - Optional bottom margin for page.
url           - Defines the list of URLs to print, one after the other.

Obviously to use this from a .net application you will need to spawn it on the command line, but that is pretty easy to do. Assuming the PrintHtml.exe program is in the bin directory for your application or web site, you can run it from .net like so:

public bool PrintHtmlPages(
    string printer,
    List<string> urls)
{
    try {
        // Spawn the code to print the packing slips
        var info = new ProcessStartInfo();
        info.Arguments = $"-p \"{printer}\" \"{string.Join("\" \"", urls)}\"";
        var pathToExe = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        info.FileName = Path.Combine(pathToExe, "PrintHtml.exe");
        using (var p = Process.Start(info)) {
            // Wait until it is finished
            while (!p.HasExited) {
                Application.DoEvents();
                System.Threading.Thread.Sleep(10);
            }

            // Return the exit code
            return p.ExitCode == 0;
        }
    } catch {
        return false;
    }
}

Enjoy!

It sounds to me like the best way you'd want to go is to first pick the HTML rendering engine and look to it for print support. There is no "standard" way to print an HTML document regardless of language, OS, or framework.

Maybe something like:

webBrowser1.DocumentContent = YOUR_FILE_NAME;
mshtml.IHTMLDocument2 doc = webBrowser1.Document as mshtml.IHTMLDocument2;
doc.execCommand("Print", true, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM