Bewerken

Delen via


Printing from WebView2 apps

There are several different ways to print a webpage in WebView2, which give you various levels of ease of implementation and customizing.

Method Description
ShowPrintUI Opens the WebView2 Print Preview dialog or the operating system's Print dialog. Easy to implement, minimal support for customizing.
Print Silently prints the current top-level document in the WebView2 using optional programmatically specified print settings to a printer. You can use this to build your own Print Preview dialog or print experience.
PrintToPdf Silently prints the current top-level document in the WebView2 to a PDF file. You can use this to build your own code to print the PDF file.
PrintToPdfStream Silently prints the current top-level document in the WebView2 to a PDF stream. You can use this to build your own code to print the PDF.

The ShowPrintUI method to open a Print dialog

The ShowPrintUI method opens the WebView2 Print Preview dialog or the operating system's Print dialog, for the current top-level document in the WebView2 control. By using this approach, you can easily provide a familiar printing experience for users.

Example: The ShowPrintUI method to open a Print dialog

This example shows the user a Print dialog.

  • If printDialog is CoreWebView2PrintDialogKind.Browser, opens the browser's Print Preview dialog.
  • If printDialog is CoreWebView2PrintDialogKind.System, opens a system Print dialog.
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);
  }
}

The Print method to customize printing

The Print method silently prints the current top-level document in the WebView2 control by using optional, programmatically specified print settings. If you want to build your own Print Preview dialog, or build your own print experience, you can use this method. This API consists of an asynchronous Print method and a PrintSettings object.

Example 1: The Print method without a dialog, using default print settings

This example prints the current webpage to the default printer, using the default print settings, without opening a Print dialog.

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");
  }
}

Example 2: The Print method to print to a specified printer, using custom print settings

This example prints the current webpage to a specific printer, using the specified settings.

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.
}

The PrintToPdf method to print to a PDF file, using custom print settings

Silently prints the current top-level document in the WebView2 control to a PDF file. To completely control how printing is performed, you can print to a PDF and then build your own code to print the PDF.

This API consists of an asynchronous PrintToPdf method and a PrintSettings object. The PrintToPdf method accepts a path that the PDF file will be saved to.

Example: The PrintToPdf method to print to a PDF file, using custom print settings

This example prints the current webpage to a PDF file, using the default path and settings.

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");
    }
}

The PrintToPdfStream method to print to a PDF stream, using custom print settings

Silently prints the current top-level document in the WebView2 control to a PDF stream. To completely control how printing is performed, you can print to a PDF and then build your own code to print the PDF. This API consists of an asynchronous PrintToPdfStream method and a PrintSettings object.

Example: The PrintToPdfStream method to print to a PDF stream, using custom print settings

This example prints the PDF data of the current webpage to a stream.

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.
}

See also