windowspdfrustwebview2tauri

Getting ICoreWebView2_7 in Tauri to Print a PDF


I'm trying to silently create a PDF from HTML in a Tauri application. As far as I could find this is currently not supported in Tauri, so I need to directly communicate with platform specific interfaces.

I found that for windows I need to get the ICoreWebView2_7 of a window since that has a PrintToPdf method. How do I get that? (Or is there some other better way to solve this problem?)

I managed to get the ICoreWebView2 from webview2_com_sys like this.

let _ = main_window.with_webview(|webview| {
    #[cfg(windows)] 
    unsafe {
        let corewebview = webview.controller().CoreWebView2().expect("");
    }
}

But the printToPDF method is on ICoreWebView2_7. So how do i get ICoreWebView2_7 from ICoreWebView2?


Solution

  • This is still fairly complex and will require you to specify these two dependencies (which should already be implicitely in your project because they are used by tauri itself). I used the matching versions for Tauri 1.6.1 which are fairly old at this point:

    webview2-com = "0.19.1"
    windows = "0.39.0"
    

    then you can just cast (in this case to ICoreWebView2_10):

    #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
    
    use tauri::Manager;
    use webview2_com::{Microsoft::Web::WebView2::Win32::*, *};
    use windows::core::Interface;
    
    fn main() {
        tauri::Builder::default()
            .setup(|app| {
                let main_window = app.get_window("main").unwrap();
                main_window
                    .with_webview(|webview| {
                        #[cfg(windows)]
                        unsafe {
                            let Ok(webview) = webview
                                .controller()
                                .CoreWebView2()
                                .unwrap()
                                .cast::<ICoreWebView2_10>() // This is where the magic happens.
                            else {
                                panic!("Failed to cast PlatformWebview.");
                            };
    
                            //webview.PrintToPdf().expect("Failed to print to pdf.");
                        }
                    })
                    .expect("Failed to get webview.");
                Ok(())
            })
            .run(tauri::generate_context!())
            .expect("error while running tauri application");
    }