Search code examples
htmldelphiprintingmicrosoft-edgetedgebrowser

Controlling headers and footers when printing using TEdgeBrowser component


The TWebBrowser component has been replaced by the TEdgeBrowser. My goal is to customize the text in the header and footer sections of a printed HTML page when the user prints using the TEdgeBrowser component.

I was able to accomplish this when using the TWebBrowser component by writing code to temporarily set the Internet Explorer registry keys at the time of printing ("SOFTWARE\Microsoft\Internet Explorer\PageSetup": 'header' and 'footer' keys). However, these same keys don't seem to exist for the Edge browser. The closest I found was the 'PrintHeaderFooter' key, which enables/disables the headers and footers.

Is there a way to modify the header and footer content in my Delphi application when printing using the new TEdgeBrowser component?


Solution

  • When printing yourself using the Print method of the WebView2 control, you can specify your own strings to use instead of document title and document uri in the header and footer:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      PrintSettings: ICoreWebView2PrintSettings;
    begin
      (EdgeBrowser1.EnvironmentInterface as ICoreWebView2Environment6).CreatePrintSettings(PrintSettings);
    
      PrintSettings.Set_ShouldPrintHeaderAndFooter(true.ToInteger);
      PrintSettings.Set_HeaderTitle('New Header text');
      PrintSettings.Set_FooterUri('New Footer text');
    
      (EdgeBrowser1.DefaultInterface as ICoreWebView2_16).Print(PrintSettings, nil);
    end;
    

    You can also control more stuff via PrintSettings like selecting the printer to use by name, choosing paper size and page orientation, etc.


    In order to get access to the types ICoreWebView2PrintSettings, ICoreWebView2Environment6 and ICoreWebView2_16 follow the steps in Marcodor's answer at WebView2 (TEdgeBrowser) updated Delphi interface (e.g. ICoreWebView2Controller2).