PrintFrom.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Microsoft.Web.WebView2.Core;
  2. using Microsoft.Web.WebView2.WinForms;
  3. using System;
  4. using System.IO;
  5. using System.Windows.Forms;
  6. namespace PrintHtml
  7. {
  8. public partial class PrinFrom : Form
  9. {
  10. string html = @"D:\index.html";
  11. public PrinFrom(string inParams)
  12. {
  13. InitializeComponent();
  14. AwaitCoreWebView2Async(webView21); //设置浏览器参数
  15. //webView21.Source = new Uri("https://www.baidu.com/"); //加载html
  16. //webView21.Dock = DockStyle.Fill;
  17. //this.webView21.CoreWebView2.NavigateToString(html);
  18. webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted;
  19. Initialize();
  20. //var printSettings = this.webView21.CoreWebView2.Environment.CreatePrintSettings();
  21. /*
  22. webView.CoreWebView2.NavigationCompleted += async (sender, e) =>
  23. {
  24. printSettings.ShouldPrintHeaderAndFooter = false;
  25. printSettings.MarginLeft = 0;
  26. printSettings.MarginTop = 0;
  27. printSettings.MarginRight = 0;
  28. printSettings.MarginBottom = 0;
  29. //webView.CoreWebView2.ShowPrintUI();
  30. //await webView.CoreWebView2.PrintAsync(printSettings);
  31. //window.print();
  32. //form.Close();
  33. };
  34. */
  35. }
  36. private void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
  37. {
  38. webView21.CoreWebView2.Navigate("https://www.baidu.com/");
  39. }
  40. /// <summary>
  41. /// WebView2初始化
  42. /// </summary>
  43. async void Initialize()
  44. {
  45. var result = await CoreWebView2Environment.CreateAsync(null, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache"), null);
  46. await webView21.EnsureCoreWebView2Async(result);
  47. }
  48. private void WebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
  49. {
  50. }
  51. private void Form1_Load(object sender, EventArgs e)
  52. {
  53. }
  54. private async void AwaitCoreWebView2Async(WebView2 WebView21)
  55. {
  56. //string userDataFolder = null; //"你的缓存文件夹路径";
  57. //CoreWebView2EnvironmentOptions options = new CoreWebView2EnvironmentOptions($"--lang=zh-CN");
  58. //var environment = await CoreWebView2Environment.CreateAsync(null, userDataFolder, options);
  59. // Create a WebView with the specified environment.
  60. //await WebView21.EnsureCoreWebView2Async(environment);
  61. }
  62. }
  63. }