using Microsoft.Web.WebView2.Core; using System.IO; using System.Windows.Threading;
namespaceDemo;
internalclassProgram { staticreadonly IntPtr HWND_MESSAGE = new IntPtr(-3);
staticvoidMain(string[] args) { var htmlContent = @" <!doctype html> <html> <head> <title>This is the title!</title> </head> <body> <p>Hello World</p> </body> </html> "; // create a new thread var uiThread = new Thread((htmlContent) => { Dispatcher.CurrentDispatcher.Invoke(async (string htmlContent) => { // setup webview runtime var runtimePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WebView2"); var environment = await CoreWebView2Environment.CreateAsync(runtimePath, null, null);
// create controller var browserController = await environment.CreateCoreWebView2ControllerAsync(HWND_MESSAGE);
// create view var view = browserController.CoreWebView2;
// load html content, could also use other methods to fetch request // html content is limited to 2 MB view.NavigateToString(htmlContent);
// get html content body var response = await view.ExecuteScriptAsync("document.body.outerHTML");
// print html content to pdf files, the file path should be full path, cannot use relative path await view.PrintToPdfAsync(@"D:\UseWebView2InConsoleApp\Demo\bin\Debug\net8.0-windows\hello.pdf");