using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.WinForms; using System; using System.IO; using System.Windows.Forms; namespace PrintHtml { public partial class PrinFrom : Form { string html = @"D:\index.html"; public PrinFrom(string inParams) { InitializeComponent(); AwaitCoreWebView2Async(webView21); //设置浏览器参数 //webView21.Source = new Uri("https://www.baidu.com/"); //加载html //webView21.Dock = DockStyle.Fill; //this.webView21.CoreWebView2.NavigateToString(html); webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted; Initialize(); //var printSettings = this.webView21.CoreWebView2.Environment.CreatePrintSettings(); /* webView.CoreWebView2.NavigationCompleted += async (sender, e) => { printSettings.ShouldPrintHeaderAndFooter = false; printSettings.MarginLeft = 0; printSettings.MarginTop = 0; printSettings.MarginRight = 0; printSettings.MarginBottom = 0; //webView.CoreWebView2.ShowPrintUI(); //await webView.CoreWebView2.PrintAsync(printSettings); //window.print(); //form.Close(); }; */ } private void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e) { webView21.CoreWebView2.Navigate("https://www.baidu.com/"); } /// /// WebView2初始化 /// async void Initialize() { var result = await CoreWebView2Environment.CreateAsync(null, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache"), null); await webView21.EnsureCoreWebView2Async(result); } private void WebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } private async void AwaitCoreWebView2Async(WebView2 WebView21) { //string userDataFolder = null; //"你的缓存文件夹路径"; //CoreWebView2EnvironmentOptions options = new CoreWebView2EnvironmentOptions($"--lang=zh-CN"); //var environment = await CoreWebView2Environment.CreateAsync(null, userDataFolder, options); // Create a WebView with the specified environment. //await WebView21.EnsureCoreWebView2Async(environment); } } }