從 WebView2 應用程式列印

在 WebView2 中有多種列印網頁的方式,提供不同程度的實作與自訂便利性。

方法 描述
ShowPrintUI 開啟 WebView2 列印預覽 對話框或作業系統的 列印 對話框。 容易實作,客製化支援極少。
Print 在 WebView2 中靜默列印目前的頂層文件,使用可選的程式化列印設定到印表機。 你可以用它來建立自己的列印預覽對話框或列印體驗。
PrintToPdf 靜默地將 WebView2 中目前的頂層文件列印成 PDF 檔案。 你可以用這個來建立自己的程式碼來列印 PDF 檔案。
PrintToPdfStream 靜默地將 WebView2 中目前的頂層文件列印成 PDF 串流。 你可以用這個來建立自己的程式碼來列印 PDF。

ShowPrintUI 方法用來開啟列印對話框

此 ShowPrintUI 方法會開啟 WebView2 列印 預覽 對話框或作業系統的 列印 對話框,以顯示 WebView2 控制項中目前頂層文件。 透過這種方法,你可以輕鬆為使用者提供熟悉的列印體驗。

範例:ShowPrintUI 方法用來開啟列印對話框

此範例顯示使用者一個 列印 對話框。

  • 如果 printDialog 是 CoreWebView2PrintDialogKind.Browser,則會開啟瀏覽器的列印預覽對話框。
  • 若 printDialog , CoreWebView2PrintDialogKind.System則會開啟系統列印對話框。
void ShowPrintUI(object target, ExecutedRoutedEventArgs e)
{
  string printDialog = e.Parameter.ToString();
  if (printDialog == "Browser")
  {
    // Opens the browser's Print Preview dialog.
    webView.CoreWebView2.ShowPrintUI();
  }
  else
  {
    // Opens a system's Print dialog.
    webView.CoreWebView2.ShowPrintUI(CoreWebView2PrintDialogKind.System);
  }
}

列印方法用於自訂列印

此 Print 方法透過可選的程式化列印設定,靜默地在 WebView2 控制項中列印目前的頂層文件。 如果你想建立自己的列印預覽對話框,或打造自己的列印體驗,可以使用這個方法。 此 API 由一個非同步 Print 方法與一個 PrintSettings 物件組成。

範例 1:使用預設列印設定的列印方法,無對話框

此範例是使用預設列印設定,將目前網頁列印到預設印表機,且未開啟 列印 對話框。

async void PrintToDefaultPrinter ()
{
  string title = webView.CoreWebView2.DocumentTitle;
  try
  {
    // Prints the current webpage, using the default printer and page settings.
    // Passing null for PrintSettings causes the default print settings to be used.
    CoreWebView2PrintStatus printStatus = await webView.CoreWebView2.PrintAsync(null);

    if (printStatus == CoreWebView2PrintStatus.Succeeded)
    {
      MessageBox.Show(this, "Printing " + title + " document to printer succeeded", "Print to default printer");
    }
    else if (printStatus == CoreWebView2PrintStatus.PrinterUnavailable)
    {
      MessageBox.Show(this, "Printer is not available, offline or error state", "Print to default printer");
    }
    else
    {
      MessageBox.Show(this, "Printing " + title + " document to printer is failed", "Print to default printer");
    }
  }
  catch (Exception)
  {
    MessageBox.Show(this, "Printing " + title + " document already in progress", "Print to default printer");
  }
}

範例 2:使用自訂列印設定列印到指定印表機的列印方法

此範例將當前網頁列印到特定印表機,並使用指定的設定。

async void PrintToPrinter()
{
  string printerName = GetPrinterName();
  CoreWebView2PrintSettings printSettings = GetSelectedPrinterPrintSettings(printerName);
  string title = webView.CoreWebView2.DocumentTitle;
  try
  {
    CoreWebView2PrintStatus printStatus = await webView.CoreWebView2.PrintAsync(printSettings);

    if (printStatus == CoreWebView2PrintStatus.Succeeded)
    {
      MessageBox.Show(this, "Printing " + title + " document to printer succeeded", "Print to printer");
    }
    else if (printStatus == CoreWebView2PrintStatus.PrinterUnavailable)
    {
      MessageBox.Show(this, "Selected printer is not found, not available, offline or error state", "Print to printer");
    }
    else
    {
      MessageBox.Show(this, "Printing " + title + " document to printer is failed", "Print");
    }
  }
  catch(ArgumentException)
  {
    MessageBox.Show(this, "Invalid settings provided for the specified printer", "Print");
  }
  catch (Exception)
  {
    MessageBox.Show(this, "Printing " + title + " document already in progress", "Print");
  }
}

// Gets the printer name by displaying the list of installed printers to the user and
// returns the name of the user's selected printer.
string GetPrinterName()
{
  // Use GetPrintQueues() of LocalPrintServer from System.Printing to get the list of locally installed printers.
  // Display the list of printers to the user and get the desired printer to use.
  // Return the name of the selected printer.
}

// Gets the print settings for the selected printer.
// You can also get the capabilities from the native printer API, and display them
// to the user to get the print settings for the current webpage and for the selected printer.
CoreWebView2PrintSettings GetSelectedPrinterPrintSettings(string printerName)
{
  CoreWebView2PrintSettings printSettings = null;
  printSettings = WebViewEnvironment.CreatePrintSettings();
  printSettings.ShouldPrintBackgrounds = true;
  printSettings.ShouldPrintHeaderAndFooter = true;

  return printSettings;

  // or
  // Get PrintQueue for the selected printer and use GetPrintCapabilities() of PrintQueue from System.Printing
  // to get the capabilities of the selected printer.
  // Display the printer capabilities to the user along with the page settings.
  // Return the user selected settings.
}

PrintToPdf 列印成 PDF 檔案的方法,使用自訂列印設定

靜默地將 WebView2 控制項中的頂層文件列印成 PDF 檔案。 為了完全控制列印方式,你可以先列印成 PDF,然後自己寫程式碼來列印 PDF。

此 API 由一個非同步 PrintToPdf 方法與一個 PrintSettings 物件組成。 此 PrintToPdf 方法接受 PDF 檔案將儲存的路徑。

範例:使用自訂列印設定列印成 PDF 檔案的 PrintToPdf 方法

此範例將目前網頁列印成 PDF 檔案,使用預設路徑與設定。

async void PrintToPdfCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
    if (_isPrintToPdfInProgress)
    {
        MessageBox.Show(this, "Print to PDF in progress", "Print To PDF");
        return;
    }
    CoreWebView2PrintSettings printSettings = null;
    string orientationString = e.Parameter.ToString();
    if (orientationString == "Landscape")
    {
        printSettings = WebViewEnvironment.CreatePrintSettings();
        printSettings.Orientation =
            CoreWebView2PrintOrientation.Landscape;
    }

    Microsoft.Win32.SaveFileDialog saveFileDialog =
        new Microsoft.Win32.SaveFileDialog();
    saveFileDialog.InitialDirectory = "C:\\";
    saveFileDialog.Filter = "PDF Files|*.pdf";
    Nullable<bool> result = saveFileDialog.ShowDialog();
    if (result == true) {
        _isPrintToPdfInProgress = true;
        bool isSuccessful = await webView.CoreWebView2.PrintToPdfAsync(
            saveFileDialog.FileName, printSettings);
        _isPrintToPdfInProgress = false;
        string message = (isSuccessful) ?
            "Print to PDF succeeded" : "Print to PDF failed";
        MessageBox.Show(this, message, "Print To PDF Completed");
    }
}

PrintToPdfStream 方法,使用自訂列印設定列印成 PDF 串流

靜默地將 WebView2 控制項中的頂層文件列印成 PDF 串流。 為了完全控制列印方式,你可以先列印成 PDF,然後自己寫程式碼來列印 PDF。 此 API 由一個非同步 PrintToPdfStream 方法與一個 PrintSettings 物件組成。

範例:使用自訂列印設定,將 PrintToPdfStream 列印成 PDF 串流

此範例將當前網頁的 PDF 資料列印成串流。

async void PrintToPdfStream()
{
  try
  {
    string title = webView.CoreWebView2.DocumentTitle;

    // Passing null for PrintSettings causes the default print settings to be used.
    System.IO.Stream stream = await webView.CoreWebView2.PrintToPdfStreamAsync(null);
    DisplayPdfDataInPrintDialog(stream);

    MessageBox.Show(this, "Printing " + title + " document to PDF Stream " +
                ((stream != null) ? "succeeded" : "failed"), "Print To PDF Stream");
  }
  catch(Exception exception)
  {
    MessageBox.Show(this, "Printing to PDF Stream failed: " + exception.Message, "Print to PDF Stream");
  }
}

// Function to display current webpage PDF data in a custom Print Preview dialog.
void DisplayPdfDataInPrintDialog(Stream pdfData)
{
  // You can display the printable PDF data to the user in a custom Print Preview dialog.
}

另請參閱