簡體   English   中英

如何在 C# 中打印 html

[英]How to print html in C#

我想在 C# 中使用 PrintDocument 打印文件。 該文件是簡單的 HTML(我需要它,因為我需要文件中的文本位於頁面內的特定位置。)

我的問題是,如何打印文件,使其不會打印 HTML 本身(標簽等),而是打印在 Web 瀏覽器中顯示的 HTML?

使用Web 瀏覽器控件並在其上調用打印方法,如下所示:

private void PrintHelpPage()
{
    // Create a WebBrowser instance. 
    WebBrowser webBrowserForPrinting = new WebBrowser();

    // Add an event handler that prints the document after it loads.
    webBrowserForPrinting.DocumentCompleted +=
        new WebBrowserDocumentCompletedEventHandler(PrintDocument);

    // Set the Url property to load the document.
    webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");
}

private void PrintDocument(object sender,
    WebBrowserDocumentCompletedEventArgs e)
{
    // Print the document now that it is fully loaded.
    ((WebBrowser)sender).Print();

    // Dispose the WebBrowser now that the task is complete. 
    ((WebBrowser)sender).Dispose();
}

關於這樣做的 MSDN 文章

使用此方法成功打印 HTML 使用,因為存在會導致多次觸發DocumentCompleted事件的錯誤。 我有一個簡單的解決方案 -

private class yourClassName
{
        WebBrowser webBrowserForPrinting;
        public void YourForm_Load()
        {
             webBrowserForPrinting = new webBrowserForPrinting();
             // Set the Url property to load the document.
             webBrowserForPrinting.Url = new Uri("Your HTML File Directory");
             webBrowserForPrinting.DocumentCompleted += WebBrowserForPrinting_DocumentCompleted;
        }

        int i = 0;
        private void WebBrowserForPrinting_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            i++;
            if (i == 1)
            {
                ((WebBrowser)sender).ShowPrintPreviewDialog();
            }

            else
            {
                ((WebBrowser)sender).Dispose();
            }
        }
}

此方法將向您顯示printing dialog以及預覽。 如果您不想預覽,請改用這個 -

private class yourClassName
{
        WebBrowser webBrowserForPrinting;
        public void YourForm_Load()
        {
             webBrowserForPrinting = new webBrowserForPrinting();
             // Set the Url property to load the document.
             webBrowserForPrinting.Url = new Uri("Your HTML File Directory");
             webBrowserForPrinting.DocumentCompleted += WebBrowserForPrinting_DocumentCompleted;
        }

        int i = 0;
        private void WebBrowserForPrinting_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            i++;
            if (i == 1)
            {
                ((WebBrowser)sender).ShowPrintDialog();
            }

            else
            {
                ((WebBrowser)sender).Dispose();
            }
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM