Search code examples
javascriptdelphitedgebrowser

TEdgeBrowser modal print dialog?


TEdgeBrowser has replaced the TWebBrowser. Is there a way to do a modal dialog print using TEdgeBrowser? I've tried running Javascript to show the Edge Browser print dialog using this code:

EdgeBrowser.ExecuteScript('window.print();');

The browser flashes for a second, but there is no print dialog shown. The TEdgeBrower is also very small in my application, so I'd like to have a modal print dialog if possible.

If I use the key combination CTRL+SHIFT+P, the print dialog is shown... but is only shown within the small TEdgeBrowser window.


Solution

  • Functionality to control printing in the Edge WebView control was only added within the last months (You need at least version 109.0.1518.46 of Edge and of the Microsoft Edge Runtime installed), so the standard TEdgeBrowser component in Delphi does not know it yet.

    There is a new method ShowPrintUI() that you can use to specifically open an operating system version of the print dialog that is modal and is shown outside the bounds of the actual browser control.

    You can use the new method from Delphi TEdgeBrowser by following the steps in Marcodor's answer at WebView2 (TEdgeBrowser) updated Delphi interface (e.g. ICoreWebView2Controller2).

    Using the current WebView2 package from Microsoft, the resultung file WebView2_TLB.pas will contain an ICoreWebView2_16 interface definition which contains among other things the definition for the ShowPrintUI() method.

    You can then include the WebView2_TLB.pas unit into your project and show the system print dialog with this code:

    var
      WebView: ICoreWebView2_16;
    begin
      // Test if browser supports ICoreWebView2_16 interface
      if EdgeBrowser1.DefaultInterface.QueryInterface(ICoreWebView2_16, WebView) = S_OK then
      begin
        // If yes, show system print dialog
        WebView.ShowPrintUI(COREWEBVIEW2_PRINT_DIALOG_KIND_SYSTEM);
      end
      else
      begin
        // Not yet supported, possible fallback?
      end;
    end;
    

    The ICoreWebView2_16 interface also contains methods for printing the browser content directly to a PDF or to a pre-selected printer without showing a dialog to the user.