Share via


Impression à partir d’applications WebView2

Il existe plusieurs façons d’imprimer une page web dans WebView2, ce qui vous offre différents niveaux de facilité d’implémentation et de personnalisation.

Méthode Description
ShowPrintUI Ouvre la boîte de dialogue Aperçu avant impression de WebView2 ou la boîte de dialogue Imprimer du système d’exploitation. Facile à implémenter, prise en charge minimale de la personnalisation.
Print Imprime en mode silencieux le document de niveau supérieur actuel dans WebView2 à l’aide des paramètres d’impression facultatifs spécifiés par programme sur une imprimante. Vous pouvez l’utiliser pour créer votre propre boîte de dialogue Aperçu avant impression ou votre propre expérience d’impression.
PrintToPdf Imprime en mode silencieux le document de niveau supérieur actuel dans WebView2 dans un fichier PDF. Vous pouvez l’utiliser pour créer votre propre code afin d’imprimer le fichier PDF.
PrintToPdfStream Imprime en mode silencieux le document de niveau supérieur actuel dans WebView2 dans un flux PDF. Vous pouvez l’utiliser pour créer votre propre code afin d’imprimer le fichier PDF.

Méthode ShowPrintUI pour ouvrir une boîte de dialogue Imprimer

La ShowPrintUI méthode ouvre la boîte de dialogue Aperçu avant impression WebView2 ou la boîte de dialogue Imprimer du système d’exploitation pour le document de niveau supérieur actuel dans le contrôle WebView2. En utilisant cette approche, vous pouvez facilement fournir une expérience d’impression familière aux utilisateurs.

Exemple : Méthode ShowPrintUI pour ouvrir une boîte de dialogue Imprimer

Cet exemple montre à l’utilisateur une boîte de dialogue Imprimer .

  • Si printDialog a la valeur CoreWebView2PrintDialogKind.Browser, ouvre la boîte de dialogue Aperçu avant impression du navigateur.
  • Si printDialog a la valeur CoreWebView2PrintDialogKind.System, ouvre une boîte de dialogue d’impression système.
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);
  }
}

Méthode Print pour personnaliser l’impression

La Print méthode imprime en mode silencieux le document de niveau supérieur actuel dans le contrôle WebView2 à l’aide des paramètres d’impression facultatifs spécifiés par programme. Si vous souhaitez créer votre propre boîte de dialogue Aperçu avant impression ou créer votre propre expérience d’impression, vous pouvez utiliser cette méthode. Cette API se compose d’une méthode asynchrone Print et d’un PrintSettings objet .

Exemple 1 : Méthode Print sans boîte de dialogue, à l’aide des paramètres d’impression par défaut

Cet exemple montre comment imprimer la page web active sur l’imprimante par défaut, à l’aide des paramètres d’impression par défaut, sans ouvrir de boîte de dialogue Imprimer .

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

Exemple 2 : Méthode Print pour imprimer sur une imprimante spécifiée, à l’aide de paramètres d’impression personnalisés

Cet exemple montre comment imprimer la page web active sur une imprimante spécifique à l’aide des paramètres spécifiés.

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

Méthode PrintToPdf pour imprimer dans un fichier PDF à l’aide de paramètres d’impression personnalisés

Imprime en mode silencieux le document de niveau supérieur actuel dans le contrôle WebView2 dans un fichier PDF. Pour contrôler complètement la façon dont l’impression est effectuée, vous pouvez imprimer dans un fichier PDF, puis créer votre propre code pour imprimer le FICHIER PDF.

Cette API se compose d’une méthode asynchrone PrintToPdf et d’un PrintSettings objet . La PrintToPdf méthode accepte un chemin d’accès dans lequel le fichier PDF sera enregistré.

Exemple : Méthode PrintToPdf pour imprimer dans un fichier PDF, à l’aide de paramètres d’impression personnalisés

Cet exemple montre comment imprimer la page web active dans un fichier PDF à l’aide du chemin d’accès et des paramètres par défaut.

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

Méthode PrintToPdfStream pour imprimer dans un flux PDF, à l’aide de paramètres d’impression personnalisés

Imprime en mode silencieux le document de niveau supérieur actuel dans le contrôle WebView2 dans un flux PDF. Pour contrôler complètement la façon dont l’impression est effectuée, vous pouvez imprimer dans un fichier PDF, puis créer votre propre code pour imprimer le FICHIER PDF. Cette API se compose d’une méthode asynchrone PrintToPdfStream et d’un PrintSettings objet .

Exemple : méthode PrintToPdfStream pour imprimer dans un flux PDF, à l’aide de paramètres d’impression personnalisés

Cet exemple montre comment imprimer les données PDF de la page web active dans un flux.

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

Voir aussi