Search code examples
.netwpfwebbrowser-controlchromium-embeddedwebview2

Print functionality in WebView2 control


Thanks in Advance !

In my application, I have embedded a WebView2 control inside a WPF usercontrol.

Is there anyway or a workaround that can help me to take a print of the WebView2 control ?

I identified that the current WebView2 pre-release SDK provided by Microsoft does'nt have any thing specific to print functionality.


Solution

  • (Update 2023-06-02: Linking to WebView2 printing doc based on this answer. Also many APIs are no longer experimental)

    (Update 2022-11-30: Since I last replied here, we've added additional print methods I describe below)

    There are a few different ways to print which give you varying levels of ease of use and control:

    • CoreWebView2.ShowPrintUI: Show the WebView2 print preview dialog or OS print dialog for the current top-level document in the WebView2. With this mechanism you easily get a printing experience the user will be familiar with. The end user chooses print settings via the print dialogs. (This method is stable and in and available in the release SDK since v1.0.1518.46).
    webview2.CoreWebView2.ShowPrintUI();
    
    • CoreWebView2.PrintAsync: Silently print the current top-level document in the WebView2 using optional programmatically specified print settings. If you want to build your own print preview dialog or otherwise build your own print experience you can use this method. (This method is stable and available in the release SDK since v1.0.1518.46).
    // null for default print settings.
    await webview2.CoreWebView.PrintAsync(null);
    
    • CoreWebView2.PrintToPdfAsync/PrintToPdfStreamAsync: Silently print the current top-level document in the WebView2 to a PDF file or 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. (The stream version of this method is stable and available in the release SDK since v1.0.1518.46).
    // null for default print settings.
    var stream = await webview.CoreWebView2.PrintToPdfStreamAsync(null);
    
    • Script injection: If you must support a WebView2 Runtime older than the above APIs, as a workaround for HTML documents you can inject script that calls the DOM print method. This has the limitations that it only works for HTML documents (not PDF for example) and only when script is enabled in the document. For example if in the following the webview2 is the WPF WebView2 class:
    await webview2.CoreWebView2.ExecuteScriptAsync("window.print();");
    

    See the WebView2 printing doc for more details.

    See also the old Print feature request GitHub thread.