从 WebView2 应用打印

从 WebView2 应用打印

本文内容

  1. 用于打开“打印”对话框的 ShowPrintUI 方法
  2. 用于自定义打印的 Print 方法
  3. 使用自定义打印设置打印到 PDF 文件的 PrintToPdf 方法
  4. 使用自定义打印设置打印到 PDF 流的 PrintToPdfStream 方法
  5. 另请参阅

有几种不同的方法可以在 WebView2 中打印网页,这为你提供了各种级别的实现和自定义便利。

方法说明
ShowPrintUI 打开“WebView2 打印预览 ”对话框或操作系统的“ 打印 ”对话框。 易于实现,对自定义的支持最少。
Print 使用可选的以编程方式指定的打印设置将 WebView2 中的当前顶级文档打印到打印机。 可以使用此功能生成自己的“打印预览”对话框或打印体验。
PrintToPdf 以无提示方式将 WebView2 中的当前顶级文档打印为 PDF 文件。 可以使用它生成自己的代码来打印 PDF 文件。
PrintToPdfStream 以无提示方式将 WebView2 中的当前顶级文档打印到 PDF 流。 可以使用它来生成自己的代码来打印 PDF。

用于打开“打印”对话框的 ShowPrintUI 方法

方法 ShowPrintUI 打开 WebView2 控件中当前顶级文档的“WebView2 打印预览 ”对话框或操作系统的“ 打印 ”对话框。 使用此方法,可以轻松为用户提供熟悉的打印体验。

示例:用于打开“打印”对话框的 ShowPrintUI 方法

此示例向用户显示 “打印 ”对话框。

  • 如果 printDialog 为 CoreWebView2PrintDialogKind.Browser,则打开浏览器的“打印预览”对话框。
  • 如果 printDialog 为 CoreWebView2PrintDialogKind.System,则打开系统“打印”对话框。
C#
void ShowPrintUI(CoreWebView2PrintDialogKind printDialogKind)
{
  WebView2.CoreWebView2.ShowPrintUI(printDialogKind);
}

用于自定义打印的 Print 方法

方法 Print 使用可选的、以编程方式指定的打印设置,以静默方式打印 WebView2 控件中的当前顶级文档。 如果要生成自己的“打印预览”对话框或构建自己的打印体验,可以使用此方法。 此 API 由异步 Print 方法和 PrintSettings 对象组成。

示例 1:使用默认打印设置的不带对话框的 Print 方法

本示例使用默认打印设置将当前网页打印到默认打印机,而无需打开 “打印 ”对话框。

C#
async void PrintToDefaultPrinter(object sender, RoutedEventArgs e)
{
  string title = WebView2.CoreWebView2.DocumentTitle;
  MessageDialog dialog = new MessageDialog("", "Print");

  try
  {
    // Prints the current webpage by using the default printer and page settings.
    // Passing null for PrintSettings causes the default print settings to be used.
    CoreWebView2PrintStatus printStatus = await WebView2.CoreWebView2.PrintAsync(null);

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

示例 2:使用自定义打印设置打印到指定打印机的 Print 方法

本示例使用指定的设置将当前网页打印到特定打印机。

C#
async void PrintToPrinter(object sender, RoutedEventArgs e)
{
  string printerName = GetPrinterName();
  CoreWebView2PrintSettings printSettings = GetSelectedPrinterPrintSettings(printerName);
  string title = WebView2.CoreWebView2.DocumentTitle;
  MessageDialog dialog = new MessageDialog("", "Print");

  try
  {
    CoreWebView2PrintStatus printStatus =
                          await WebView2.CoreWebView2.PrintAsync(printSettings);

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

// Gets the printer name by displaying the list of installed printers to the user, 
// and returns the user-selected printer.
string GetPrinterName()
{
  // Use DeviceInformation.FindAllAsync to get the list of local printers with AQS as:
  // System.Devices.HardwareIds:~~"PRINTENUM\LocalPrintQueue"
  // Display the list of printers to the user, and get the desired printer to use.
  // Return the name of the user's selected printer.
}

// Gets print settings for the selected printer.
// You can also get the capabilities from the printer APIs, 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 = WebView2.CoreWebView2.Environment.CreatePrintSettings();
  printSettings.ShouldPrintBackgrounds = true;
  printSettings.ShouldPrintHeaderAndFooter = true;

  return printSettings;

  // or
  // Get the print ticket and use PrintTicketCapabilities from
  // Windows.Graphics.Printing.PrintTicket 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.
}

使用自定义打印设置打印到 PDF 文件的 PrintToPdf 方法

以无提示方式将 WebView2 控件中的当前顶级文档打印到 PDF 文件。 若要完全控制打印的执行方式,可以打印到 PDF,然后生成自己的代码来打印 PDF。

此 API 由异步 PrintToPdf 方法和 PrintSettings 对象组成。 方法 PrintToPdf 接受 PDF 文件将保存到的路径。

示例:使用自定义打印设置打印到 PDF 文件的 PrintToPdf 方法

本示例使用默认路径和设置将当前网页打印为 PDF 文件。

C#
async void PrintToPdf(bool enableLandscape)
{
  MessageDialog dialog = new MessageDialog("", "Print To PDF");
  if (_isPrintToPdfInProgress)
  {
    dialog = new MessageDialog("Print to PDF in progress", "Print To PDF");
    return;
  }
  CoreWebView2PrintSettings printSettings = null;
  if (enableLandscape)
  {
    printSettings = WebView2.CoreWebView2.Environment.CreatePrintSettings();
    printSettings.Orientation = CoreWebView2PrintOrientation.Landscape;
  }

  var savePicker = new Windows.Storage.Pickers.FileSavePicker();
  savePicker.FileTypeChoices.Add("PDF Files", new List<string>() { ".pdf" });
  savePicker.SuggestedFileName = "WebView2_PrintedPdf";

  StorageFile file = await savePicker.PickSaveFileAsync();
  if (file != null)
  {
    _isPrintToPdfInProgress = true;
    bool isSuccessful = await WebView2.CoreWebView2.PrintToPdfAsync(file.Path, printSettings);
    _isPrintToPdfInProgress = false;
    string message = (isSuccessful) ? "Print to PDF succeeded" : "Print to PDF failed";
    dialog = new MessageDialog(message, "Print To PDF");
  }

  await dialog.ShowAsync();
}

使用自定义打印设置打印到 PDF 流的 PrintToPdfStream 方法

以无提示方式将 WebView2 控件中的当前顶级文档打印到 PDF 流。 若要完全控制打印的执行方式,可以打印到 PDF,然后生成自己的代码来打印 PDF。 此 API 由异步 PrintToPdfStream 方法和 PrintSettings 对象组成。

示例:使用自定义打印设置打印到 PDF 流的 PrintToPdfStream 方法

本示例将当前网页的 PDF 数据打印到流中。

C#
async void PrintToPdfStream(object sender, RoutedEventArgs e)
{
  MessageDialog dialog = new MessageDialog("", "Print to PDF Stream");
  try
  {
    string title = WebView2.CoreWebView2.DocumentTitle;

    // Passing null for PrintSettings causes the default print settings to be used.
    Windows.Storage.Streams.IRandomAccessStream stream =
                        await WebView2.CoreWebView2.PrintToPdfStreamAsync(null);
    DisplayPdfDataInPrintDialog(stream);
    dialog = new MessageDialog("Printing" + title + " document to PDF Stream "
                           + ((stream != null) ? "succeeded" : "failed"), "Print To PDF Stream");
  }
  catch (Exception exception)
  {
    dialog = new MessageDialog("Printing to PDF Stream failed: " + exception.Message,
              "Print to PDF Stream");
  }
  await dialog.ShowAsync();
}

// Function to display the current page PDF data in a custom Print Preview dialog.
void DisplayPdfDataInPrintDialog(Windows.Storage.Streams.IRandomAccessStream pdfData)
{
  // You can display the printable PDF data to the user in a custom Print Preview dialog.
}

另请参阅

posted on 2025-04-01 15:14  漫思  阅读(86)  评论(0)    收藏  举报

导航