Partilhar via


Imprimir a partir de aplicações WebView2

Existem várias formas diferentes de imprimir uma página Web no WebView2, que lhe proporcionam vários níveis de facilidade de implementação e personalização.

Método Descrição
ShowPrintUI Abre a caixa de diálogo Pré-visualização de Impressão do WebView2 ou a caixa de diálogo Imprimir do sistema operativo. Fácil de implementar, suporte mínimo para personalização.
Print Imprime automaticamente o documento de nível superior atual no WebView2 através de definições de impressão especificadas programaticamente opcionais numa impressora. Pode utilizá-lo para criar a sua própria caixa de diálogo de Pré-visualização ou experiência de impressão.
PrintToPdf Imprime automaticamente o documento de nível superior atual no WebView2 para um ficheiro PDF. Pode utilizá-lo para criar o seu próprio código para imprimir o ficheiro PDF.
PrintToPdfStream Imprime automaticamente o documento de nível superior atual no WebView2 para um fluxo de PDF. Pode utilizá-lo para criar o seu próprio código para imprimir o PDF.

O método ShowPrintUI para abrir uma caixa de diálogo Imprimir

O ShowPrintUI método abre a caixa de diálogo Pré-visualização de Impressão webView2 ou a caixa de diálogo Imprimir do sistema operativo para o documento de nível superior atual no controlo WebView2. Ao utilizar esta abordagem, pode fornecer facilmente uma experiência de impressão familiar aos utilizadores.

Exemplo: o método ShowPrintUI para abrir uma caixa de diálogo Imprimir

Este exemplo mostra ao utilizador uma caixa de diálogo Imprimir .

  • Se printDialog for CoreWebView2PrintDialogKind.Browser, abre a caixa de diálogo Pré-visualizar do browser.
  • Se printDialog for CoreWebView2PrintDialogKind.System, abre uma caixa de diálogo Imprimir do sistema.
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);
  }
}

O método Imprimir para personalizar a impressão

O Print método imprime silenciosamente o documento de nível superior atual no controlo WebView2 ao utilizar definições de impressão opcionais especificadas programaticamente. Se quiser criar a sua própria caixa de diálogo Pré-visualizar ou criar a sua própria experiência de impressão, pode utilizar este método. Esta API consiste num método assíncrono Print e num PrintSettings objeto.

Exemplo 1: o método Imprimir sem uma caixa de diálogo, utilizando as predefinições de impressão

Este exemplo imprime a página Web atual na impressora predefinida, utilizando as predefinições de impressão, sem abrir uma caixa de diálogo Imprimir .

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

Exemplo 2: o método Imprimir para imprimir numa impressora especificada com as definições de impressão personalizadas

Este exemplo imprime a página Web atual numa impressora específica com as definições especificadas.

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

O método PrintToPdf para imprimir num ficheiro PDF com definições de impressão personalizadas

Imprime automaticamente o documento de nível superior atual no controlo WebView2 para um ficheiro PDF. Para controlar completamente a forma como a impressão é executada, pode imprimir num PDF e, em seguida, criar o seu próprio código para imprimir o PDF.

Esta API consiste num método assíncrono PrintToPdf e num PrintSettings objeto. O PrintToPdf método aceita um caminho no qual o ficheiro PDF será guardado.

Exemplo: o método PrintToPdf para imprimir num ficheiro PDF com definições de impressão personalizadas

Este exemplo imprime a página Web atual num ficheiro PDF com o caminho e as definições predefinidos.

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

O método PrintToPdfStream para imprimir num fluxo de PDF com definições de impressão personalizadas

Imprime automaticamente o documento de nível superior atual no controlo WebView2 para um fluxo de PDF. Para controlar completamente a forma como a impressão é executada, pode imprimir num PDF e, em seguida, criar o seu próprio código para imprimir o PDF. Esta API consiste num método assíncrono PrintToPdfStream e num PrintSettings objeto.

Exemplo: o método PrintToPdfStream para imprimir num fluxo de PDF com definições de impressão personalizadas

Este exemplo imprime os dados pdf da página Web atual num fluxo.

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

Confira também