简体   繁体   English

在C#中打印格式化的HTML页面

[英]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). 我正在寻找一种在c#(主要是wpf)中以横向模式打印格式化的html文件的方法。 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. 我尝试使用Microsoft的html到xaml转换器,它破坏了格式化。 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. 您可以在C#中访问WebBrowser类的Print()方法来执行此操作。 The cool thing is that you don't need to actually display the WebBrowser anywhere in your application. 很酷的是,您不需要在应用程序的任何位置实际显示WebBrowser。 Just simply feed the content to the WebBrowser Control like so: 只需简单地将内容提供给WebBrowser控件,如下所示:

webBrowser1.DocumentContent = openfiledialog.FileName;

And then just call the webBrowser1.Print(); 然后只需调用webBrowser1.Print(); method. 方法。 Here's an MSDN reference: 这是一个MSDN参考:

http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.print.aspx 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. 多年来,我们使用.net WebBrowser控件,如其他答案所述,但最近控制变得越来越不稳定。 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. 即使重建我们用于在仓库中打印我们的拣货单以运行Windows 10的机器,我们仍然会遇到问题,直到我们重新启动计算机才会打印页面。 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. 相同的代码在4年多的时间里为我们提供了良好的服务,但现在看来微软的最新更新使得这种控制比过去更加错误。

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. 另一个主要问题是没有简单的方法可以打印到除Internet Explorer的默认设置之外的打印机,因此如果您希望打印到不同的打印机,那么您很可能对该控件不满意。

Many years ago we wrote a version of our printing code for packing slips using C++ and the QtWebKit library. 很多年前,我们使用C ++和QtWebKit库编写了一个打印代码的打印代码。 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. 因此,为了解决这些问题,我挖出了打印网页文件的旧C ++应用程序,并将其转换为此项目以通过命令行进行打印,并使其能够打印到不同的打印机。

You can get the source code for it here: 你可以在这里获得它的源代码:

https://github.com/kendallb/PrintHtml https://github.com/kendallb/PrintHtml

and you can download a 32-bit binary pre-compiled for Windows using MinGW from here: 您可以从这里使用MinGW下载为Windows预编译的32位二进制文​​件:

https://github.com/kendallb/PrintHtml/blob/master/deploy/PrintHtml-window-x86.zip?raw=true 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. 代码是完全可移植的,因此如果需要,您可以轻松地将其编译为在macOS或Linux上运行。

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. 显然,要从.net应用程序中使用它,您需要在命令行上生成它,但这很容易做到。 Assuming the PrintHtml.exe program is in the bin directory for your application or web site, you can run it from .net like so: 假设PrintHtml.exe程序位于应用程序或网站的bin目录中,您可以从.net运行它,如下所示:

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. 在我看来,你想要的最好的方法就是首先选择HTML渲染引擎并寻找它以获得打印支持。 There is no "standard" way to print an HTML document regardless of language, OS, or framework. 无论语言,操作系统或框架如何,都没有“标准”方式来打印HTML文档。

Maybe something like: 也许是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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