Jak przeprowadzić migrację z WebView2 do IronPDF w języku C#
WebView2, kontrolka przeglądarki Edge/Chromium firmy Microsoft, którą można osadzać w aplikacjach, oferuje programistom możliwość wyświetlania treści internetowych w aplikacjach systemu Windows. Jednak gdy zespoły programistów próbują używaćWebView2do generowania plików PDF, napotykają poważne ograniczenia architektoniczne, które sprawiają, że nie nadaje się on do środowisk produkcyjnych.WebView2to kontrolka do osadzania przeglądarki przeznaczona dla aplikacji UI — nie jest to biblioteka do generowania plików PDF.
Niniejszy przewodnik zawiera kompletną ścieżkę migracji zWebView2do IronPDF, wraz z instrukcjami krok po kroku, porównaniami kodu i praktycznymi przykładami dla profesjonalnych programistów .NET, którzy potrzebują niezawodnego generowania plików PDF w swoich aplikacjach.
Ważne ostrzeżenie:WebView2NIE nadaje się do generowania plików PDF
Przed przeanalizowaniem ścieżki migracji zespoły programistów muszą zrozumieć, dlaczegoWebView2powoduje poważne problemy podczas tworzenia plików PDF:
| Problem | Wpływ | Waga |
|---|---|---|
| Wycieki pamięci | WebView2ma dobrze udokumentówane wycieki pamięci w długotrwałych procesach. Twój serwer ulegnie awarii. | KLUCZOWE |
| Tylko dla systemu Windows | Brak obsługi systemów Linux, macOS, Docker lub środowisk chmurowych | KLUCZOWE |
| Wymagany wątek dotyczący interfejsu użytkownika | Musi działać na wątku STA z pompą komunikatów. Nie może działać na serwerach internetowych ani w interfejsach API. | KLUCZOWE |
| Nieprzeznaczone do plików PDF | PrintToPdfAsync jest dodatkiem, a nie podstawową funkcją |
HIGH |
| Niestabilne w usługach | Awarie i zawieszanie się, typowe dla usług Windows i procesów działających w tle | HIGH |
| Złożony przepływ asynchroniczny | Zdarzenia nawigacyjne, wywołania zwrotne po zakończeniu, warunki wyścigu | HIGH |
| Zależność środowiska uruchomieniowego Edge | Wymaga zainstalowania środowiska uruchomieniowego EdgeWebView2na komputerze docelowym | MEDIUM |
| Brak trybu bezinterfejsowego | Zawsze tworzy elementy interfejsu użytkownika, nawet gdy są ukryte | MEDIUM |
| Wydajność | Powolny start, duże zużycie zasobów | MEDIUM |
| Brak profesjonalnego wsparcia | Microsoft nie obsługuje generowania plików PDF | MEDIUM |
Scenariusze awarii w praktyce
Te wzorce kodu powodują awarie produkcyjne:
// DANGER: This code WILL cause problems in production
//Problem1: Memory leak - creates newWebView2for each PDF
public async Task<byte[]> GeneratePdf(string html) // Called 1000x/day = server crash
{
using var webView = new WebView2(); // Memory not fully released!
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.NavigateToString(html);
// ... memory accumulates until OOM
}
//Problem2: UI thread requirement - crashes in ASP.NET
public IActionResult GenerateReport() // FAILS - no STA thread
{
var webView = new WebView2(); // InvalidOperationException
}
//Problem3: Windows Service instability
public class PdfService : BackgroundService // Random crashes
{
protected override async Task ExecuteAsync(CancellationToken token)
{
//WebView2+ no message pump = hangs, crashes, undefined behavior
}
}
// DANGER: This code WILL cause problems in production
//Problem1: Memory leak - creates newWebView2for each PDF
public async Task<byte[]> GeneratePdf(string html) // Called 1000x/day = server crash
{
using var webView = new WebView2(); // Memory not fully released!
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.NavigateToString(html);
// ... memory accumulates until OOM
}
//Problem2: UI thread requirement - crashes in ASP.NET
public IActionResult GenerateReport() // FAILS - no STA thread
{
var webView = new WebView2(); // InvalidOperationException
}
//Problem3: Windows Service instability
public class PdfService : BackgroundService // Random crashes
{
protected override async Task ExecuteAsync(CancellationToken token)
{
//WebView2+ no message pump = hangs, crashes, undefined behavior
}
}
' DANGER: This code WILL cause problems in production
' Problem1: Memory leak - creates new WebView2 for each PDF
Public Async Function GeneratePdf(html As String) As Task(Of Byte()) ' Called 1000x/day = server crash
Using webView As New WebView2() ' Memory not fully released!
Await webView.EnsureCoreWebView2Async()
webView.CoreWebView2.NavigateToString(html)
' ... memory accumulates until OOM
End Using
End Function
' Problem2: UI thread requirement - crashes in ASP.NET
Public Function GenerateReport() As IActionResult ' FAILS - no STA thread
Dim webView As New WebView2() ' InvalidOperationException
Return Nothing ' Placeholder for actual return
End Function
' Problem3: Windows Service instability
Public Class PdfService
Inherits BackgroundService ' Random crashes
Protected Overrides Async Function ExecuteAsync(token As CancellationToken) As Task
' WebView2+ no message pump = hangs, crashes, undefined behavior
End Function
End Class
IronPDFvs WebView2: Porównanie funkcji
Zrozumienie różnic architektonicznych pomaga decydentom technicznym w ocenie inwestycji w migrację:
| Aspekt | WebView2 | IronPDF |
|---|---|---|
| Cel | Sterowanie przeglądarką (UI) | Biblioteka PDF (przeznaczona dla formatu PDF) |
| Gotowe do produkcji | NIE | TAK |
| Zarządzanie pamięcią | Wycieki w długotrwałych | Stabilny, prawidłowo usunięty |
| Obsługa platform | Tylko dla systemu Windows | Windows, Linux, macOS, Docker |
| Wymagania dotyczące wątku | STA + Message Pump | Każdy wątek |
| Serwer/Chmura | Nieobsługiwane | Obsługiwane |
| Azure/AWS/GCP | Problematyczne | Działa idealnie |
| Docker | Niemożliwe | Dostępne są oficjalne zdjęcia |
| ASP.NET Core | Nie mogę pracować | Wsparcie na najwyższym poziomie |
| Usługi w tle | Niestabilny | Stabilny |
| Obsługiwane konteksty | Tylko WinForms/WPF | Dowolny kontekst .NET: konsola, internet, komputer stacjonarny |
| HTML do PDF | Podstawowe | Pełna |
| URL do pliku PDF | Podstawowe | Pełna |
| Nagłówki/stopki | NIE | Tak (HTML) |
| Znaki wodne | NIE | Tak |
| Łączenie plików PDF | NIE | Tak |
| Podział plików PDF | NIE | Tak |
| Podpisy cyfrowe | NIE | Tak |
| Ochrona hasłem | NIE | Tak |
| Zgodność z PDF/A | NIE | Tak |
| Profesjonalne wsparcie | Brak dla pliku PDF | Tak |
| Dokumentacja | Ograniczone | Obszerne |
Szybki start: Migracja zWebView2do IronPDF
Migrację można rozpocząć natychmiast, wykonując te podstawowe kroki.
Krok 1: Usuń pakiet WebView2
dotnet remove package Microsoft.Web.WebView2
dotnet remove package Microsoft.Web.WebView2
Lub usuń z pliku projektu:
<PackageReference Include="Microsoft.Web.WebView2" Version="*" Remove />
<PackageReference Include="Microsoft.Web.WebView2" Version="*" Remove />
Krok 2: Zainstaluj IronPDF
dotnet add package IronPdf
dotnet add package IronPdf
Krok 3: Aktualizacja przestrzeni nazw
Zastąp przestrzenie nazwWebView2przestrzenią nazw IronPdf:
// Before (WebView2)
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
// After (IronPDF)
using IronPdf;
// Before (WebView2)
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
// After (IronPDF)
using IronPdf;
Imports Microsoft.Web.WebView2.Core
Imports Microsoft.Web.WebView2.WinForms
' After (IronPDF)
Imports IronPdf
Krok 4: Inicjalizacja licencji
Dodaj inicjalizację licencji podczas uruchamiania aplikacji:
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
Przykłady migracji kodu
Konwersja HTML do PDF
Najbardziej podstawowa operacja ujawnia różnicę w złożoności między tymi podejściami do obsługi plików PDF w środowisku .NET.
Podejście WebView2:
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.NavigateToString("<html><body><h1>Hello World</h1></body></html>");
await Task.Delay(2000);
await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
"{}"
);
}
}
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.NavigateToString("<html><body><h1>Hello World</h1></body></html>");
await Task.Delay(2000);
await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
"{}"
);
}
}
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.Web.WebView2.WinForms
Imports Microsoft.Web.WebView2.Core
Module Program
Async Function Main() As Task
Dim webView As New WebView2()
Await webView.EnsureCoreWebView2Async()
webView.CoreWebView2.NavigateToString("<html><body><h1>Hello World</h1></body></html>")
Await Task.Delay(2000)
Await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
"{}"
)
End Function
End Module
Podejście IronPDF:
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<html><body><h1>Hello World</h1></body></html>");
pdf.SaveAs("output.pdf");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<html><body><h1>Hello World</h1></body></html>");
pdf.SaveAs("output.pdf");
}
}
Imports IronPdf
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<html><body><h1>Hello World</h1></body></html>")
pdf.SaveAs("output.pdf")
End Sub
End Class
WersjaWebView2wymaga asynchronicznej inicjalizacji za pomocą EnsureCoreWebView2Async(), nawigacji za pomocą NavigateToString(), zawodnego Task.Delay(2000) do oczekiwania na renderowanie oraz interakcji z protokołem DevTools.IronPDFcałkowicie eliminuje tę procedurę — wystarczy utworzyć renderer, wyrenderować HTML i zapisać.
W przypadku zaawansowanych scenariuszy konwersji HTML do PDF zapoznaj się z przewodnikiem po konwersji HTML do PDF.
Konwersja adresów URL do formatu PDF
Konwersja adresu URL do formatu PDF ilustruje złożony, asynchroniczny przebieg nawigacji w WebView2.
Podejście WebView2:
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
var tcs = new TaskCompletionSource<bool>();
webView.CoreWebView2.NavigationCompleted += (s, e) => tcs.SetResult(true);
webView.CoreWebView2.Navigate("https://example.com");
await tcs.Task;
await Task.Delay(1000);
var result = await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
"{\"printBackground\": true}"
);
var base64 = System.Text.Json.JsonDocument.Parse(result).RootElement.GetProperty("data").GetString();
File.WriteAllBytes("output.pdf", Convert.FromBase64String(base64));
}
}
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
var tcs = new TaskCompletionSource<bool>();
webView.CoreWebView2.NavigationCompleted += (s, e) => tcs.SetResult(true);
webView.CoreWebView2.Navigate("https://example.com");
await tcs.Task;
await Task.Delay(1000);
var result = await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
"{\"printBackground\": true}"
);
var base64 = System.Text.Json.JsonDocument.Parse(result).RootElement.GetProperty("data").GetString();
File.WriteAllBytes("output.pdf", Convert.FromBase64String(base64));
}
}
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.Web.WebView2.WinForms
Imports Microsoft.Web.WebView2.Core
Module Program
Async Function Main() As Task
Dim webView As New WebView2()
Await webView.EnsureCoreWebView2Async()
Dim tcs As New TaskCompletionSource(Of Boolean)()
AddHandler webView.CoreWebView2.NavigationCompleted, Sub(s, e) tcs.SetResult(True)
webView.CoreWebView2.Navigate("https://example.com")
Await tcs.Task
Await Task.Delay(1000)
Dim result As String = Await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
"{""printBackground"": true}"
)
Dim base64 As String = System.Text.Json.JsonDocument.Parse(result).RootElement.GetProperty("data").GetString()
File.WriteAllBytes("output.pdf", Convert.FromBase64String(base64))
End Function
End Module
Podejście IronPDF:
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://example.com");
pdf.SaveAs("output.pdf");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://example.com");
pdf.SaveAs("output.pdf");
}
}
Imports IronPdf
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://example.com")
pdf.SaveAs("output.pdf")
End Sub
End Class
WebView2 wymaga utworzenia TaskCompletionSource, subskrypcji zdarzeń NavigationCompleted, wywołania CallDevToolsProtocolMethodAsync, analizy odpowiedzi JSON oraz dekodowania danych base64.IronPDFudostępnia dedykowaną metodę RenderUrlAsPdf, która wewnętrznie radzi sobie ze wszystkimi złożonymi kwestiami.
Zapoznaj się z dokumentacją dotyczącą konwersji adresów URL do formatu PDF, aby uzyskać informacje na temat uwierzytelniania i opcji niestandardowych nagłówków.
Niestandardowe ustawienia PDF z plików HTML
Konfiguracja orientacji strony, marginesów i rozmiaru papieru wymaga różnych podejść.
Podejście WebView2:
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
string htmlFile = Path.Combine(Directory.GetCurrentDirectory(), "input.html");
webView.CoreWebView2.Navigate(htmlFile);
await Task.Delay(3000);
var printSettings = webView.CoreWebView2.Environment.CreatePrintSettings();
printSettings.Orientation = CoreWebView2PrintOrientation.Landscape;
printSettings.MarginTop = 0.5;
printSettings.MarginBottom = 0.5;
using (var stream = await webView.CoreWebView2.PrintToPdfAsync("custom.pdf", printSettings))
{
Console.WriteLine("Custom PDF created");
}
}
}
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
string htmlFile = Path.Combine(Directory.GetCurrentDirectory(), "input.html");
webView.CoreWebView2.Navigate(htmlFile);
await Task.Delay(3000);
var printSettings = webView.CoreWebView2.Environment.CreatePrintSettings();
printSettings.Orientation = CoreWebView2PrintOrientation.Landscape;
printSettings.MarginTop = 0.5;
printSettings.MarginBottom = 0.5;
using (var stream = await webView.CoreWebView2.PrintToPdfAsync("custom.pdf", printSettings))
{
Console.WriteLine("Custom PDF created");
}
}
}
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.Web.WebView2.Core
Imports Microsoft.Web.WebView2.WinForms
Module Program
Async Function Main() As Task
Dim webView As New WebView2()
Await webView.EnsureCoreWebView2Async()
Dim htmlFile As String = Path.Combine(Directory.GetCurrentDirectory(), "input.html")
webView.CoreWebView2.Navigate(htmlFile)
Await Task.Delay(3000)
Dim printSettings = webView.CoreWebView2.Environment.CreatePrintSettings()
printSettings.Orientation = CoreWebView2PrintOrientation.Landscape
printSettings.MarginTop = 0.5
printSettings.MarginBottom = 0.5
Using stream = Await webView.CoreWebView2.PrintToPdfAsync("custom.pdf", printSettings)
Console.WriteLine("Custom PDF created")
End Using
End Function
End Module
Podejście IronPDF:
// NuGet: Install-Package IronPdf
using IronPdf;
using IronPdf.Rendering;
using System;
using System.IO;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
string htmlFile = Path.Combine(Directory.GetCurrentDirectory(), "input.html");
var pdf = renderer.RenderHtmlFileAsPdf(htmlFile);
pdf.SaveAs("custom.pdf");
Console.WriteLine("Custom PDF created");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using IronPdf.Rendering;
using System;
using System.IO;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
string htmlFile = Path.Combine(Directory.GetCurrentDirectory(), "input.html");
var pdf = renderer.RenderHtmlFileAsPdf(htmlFile);
pdf.SaveAs("custom.pdf");
Console.WriteLine("Custom PDF created");
}
}
Imports IronPdf
Imports IronPdf.Rendering
Imports System
Imports System.IO
Module Program
Sub Main()
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50
Dim htmlFile As String = Path.Combine(Directory.GetCurrentDirectory(), "input.html")
Dim pdf = renderer.RenderHtmlFileAsPdf(htmlFile)
pdf.SaveAs("custom.pdf")
Console.WriteLine("Custom PDF created")
End Sub
End Module
WebView2 wymaga 3-sekundowego Task.Delay (niepewne przypuszczenie), utworzenia ustawień drukowania poprzez Środowisko oraz użycia PrintToPdfAsync ze strumieniem.IronPDFzapewnia bezpośrednie właściwości RenderingOptions o jasnych nazwach i wykorzystuje milimetry do bardziej precyzyjnych pomiarów.
Zaawansowane opcje PDF z protokołem DevTools
Złożone konfiguracjeWebView2wymagają interakcji z protokołem DevTools.
Podejście WebView2:
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using System.Text.Json;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
var htmlPath = Path.GetFullPath("document.html");
var tcs = new TaskCompletionSource<bool>();
webView.CoreWebView2.NavigationCompleted += (s, e) => tcs.SetResult(true);
webView.CoreWebView2.Navigate($"file:///{htmlPath}");
await tcs.Task;
await Task.Delay(1000);
var options = new
{
landscape = false,
printBackground = true,
paperWidth = 8.5,
paperHeight = 11,
marginTop = 0.4,
marginBottom = 0.4,
marginLeft = 0.4,
marginRight = 0.4
};
var result = await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
JsonSerializer.Serialize(options)
);
var base64 = JsonDocument.Parse(result).RootElement.GetProperty("data").GetString();
File.WriteAllBytes("output.pdf", Convert.FromBase64String(base64));
}
}
// NuGet: Install-Package Microsoft.Web.WebView2.WinForms
using System;
using System.IO;
using System.Threading.Tasks;
using System.Text.Json;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
class Program
{
static async Task Main()
{
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
var htmlPath = Path.GetFullPath("document.html");
var tcs = new TaskCompletionSource<bool>();
webView.CoreWebView2.NavigationCompleted += (s, e) => tcs.SetResult(true);
webView.CoreWebView2.Navigate($"file:///{htmlPath}");
await tcs.Task;
await Task.Delay(1000);
var options = new
{
landscape = false,
printBackground = true,
paperWidth = 8.5,
paperHeight = 11,
marginTop = 0.4,
marginBottom = 0.4,
marginLeft = 0.4,
marginRight = 0.4
};
var result = await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
JsonSerializer.Serialize(options)
);
var base64 = JsonDocument.Parse(result).RootElement.GetProperty("data").GetString();
File.WriteAllBytes("output.pdf", Convert.FromBase64String(base64));
}
}
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports System.Text.Json
Imports Microsoft.Web.WebView2.WinForms
Imports Microsoft.Web.WebView2.Core
Module Program
Async Function Main() As Task
Dim webView As New WebView2()
Await webView.EnsureCoreWebView2Async()
Dim htmlPath As String = Path.GetFullPath("document.html")
Dim tcs As New TaskCompletionSource(Of Boolean)()
AddHandler webView.CoreWebView2.NavigationCompleted, Sub(s, e) tcs.SetResult(True)
webView.CoreWebView2.Navigate($"file:///{htmlPath}")
Await tcs.Task
Await Task.Delay(1000)
Dim options = New With {
.landscape = False,
.printBackground = True,
.paperWidth = 8.5,
.paperHeight = 11,
.marginTop = 0.4,
.marginBottom = 0.4,
.marginLeft = 0.4,
.marginRight = 0.4
}
Dim result As String = Await webView.CoreWebView2.CallDevToolsProtocolMethodAsync(
"Page.printToPDF",
JsonSerializer.Serialize(options)
)
Dim base64 As String = JsonDocument.Parse(result).RootElement.GetProperty("data").GetString()
File.WriteAllBytes("output.pdf", Convert.FromBase64String(base64))
End Function
End Module
Podejście IronPDF:
// NuGet: Install-Package IronPdf
using IronPdf;
using IronPdf.Rendering;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginBottom = 40;
renderer.RenderingOptions.MarginLeft = 40;
renderer.RenderingOptions.MarginRight = 40;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
var pdf = renderer.RenderHtmlFileAsPdf("document.html");
pdf.SaveAs("output.pdf");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using IronPdf.Rendering;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginBottom = 40;
renderer.RenderingOptions.MarginLeft = 40;
renderer.RenderingOptions.MarginRight = 40;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
var pdf = renderer.RenderHtmlFileAsPdf("document.html");
pdf.SaveAs("output.pdf");
}
}
Imports IronPdf
Imports IronPdf.Rendering
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter
renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginBottom = 40
renderer.RenderingOptions.MarginLeft = 40
renderer.RenderingOptions.MarginRight = 40
renderer.RenderingOptions.PrintHtmlBackgrounds = True
Dim pdf = renderer.RenderHtmlFileAsPdf("document.html")
pdf.SaveAs("output.pdf")
End Sub
End Class
WebView2 wymaga tworzenia obiektów anonimowych, serializacji do formatu JSON, wywoływania metod protokołu DevTools, analizowania odpowiedzi JSON oraz ręcznego dekodowania base64.IronPDFudostępnia właściwości typowane o jasnych nazwach i wartościach wyliczeniowych, takich jak PdfPaperSize.Letter.
Odnośnik do dokumentacji APIWebView2dla IronPDF
To mapowanie przyspiesza migrację, pokazując bezpośrednie odpowiedniki API:
| Interfejs APIWebView2 | OdpowiednikIronPDF |
|---|---|
new WebView2() |
new ChromePdfRenderer() |
EnsureCoreWebView2Async() |
Nie dotyczy |
NavigateToString(html) + PrintToPdfAsync() |
RenderHtmlAsPdf(html) |
Navigate(url) + PrintToPdfAsync() |
RenderUrlAsPdf(url) |
PrintSettings.PageWidth |
RenderingOptions.PaperSize |
PrintSettings.PageHeight |
RenderingOptions.PaperSize |
PrintSettings.MarginTop |
RenderingOptions.MarginTop |
PrintSettings.Orientation |
RenderingOptions.PaperOrientation |
ExecuteScriptAsync() |
JavaScript w HTML |
AddScriptToExecuteOnDocumentCreatedAsync() |
Tagi HTML <script> |
| Zdarzenia nawigacyjne | WaitFor.JavaScript() |
CallDevToolsProtocolMethodAsync("Page.printToPDF") |
RenderHtmlAsPdf() |
Typowe problemy związane z migracją i ich rozwiązania
Problem1: Wycieki pamięci
Problem z WebView2: Pamięć nie jest w pełni zwalniana podczas usuwania instancji WebView2. Długotrwałe procesy gromadzą pamięć aż do awarii.
Rozwiązanie IronPDF: Prawidłowe zbieranie śmieci bez wycieków:
//IronPDF- clean memory management
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
pdf.SaveAs("output.pdf");
} // Properly disposed
//IronPDF- clean memory management
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
pdf.SaveAs("output.pdf");
} // Properly disposed
Imports IronPdf
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
End Using
Problem2: Brak wątku UI w aplikacjach internetowych
Problem z WebView2: Wymaga wątku STA z pompą komunikatów. Kontrolery ASP.NET Core nie mogą tworzyć instancji WebView2.
Rozwiązanie IronPDF: Działa na dowolnym wątku:
// ASP.NET Core - just works
public async Task<IActionResult> GetPdf()
{
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return File(pdf.BinaryData, "application/pdf");
}
// ASP.NET Core - just works
public async Task<IActionResult> GetPdf()
{
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return File(pdf.BinaryData, "application/pdf");
}
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc
Public Class YourController
Inherits Controller
Public Async Function GetPdf() As Task(Of IActionResult)
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return File(pdf.BinaryData, "application/pdf")
End Function
End Class
Problem3: Złożoność zdarzeń nawigacyjnych
Problem z WebView2: Musi obsługiwać asynchroniczne zdarzenia nawigacyjne, wywołania zwrotne zakończenia oraz warunki wyścigu z TaskCompletionSource.
Rozwiązanie IronPDF: Synchroniczne lub asynchroniczne wywołanie pojedynczej metody:
// Simple and predictable
var pdf = renderer.RenderHtmlAsPdf(html);
// or
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
// Simple and predictable
var pdf = renderer.RenderHtmlAsPdf(html);
// or
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
Problem4: Jednostki miary
WebView2 używa cali jako jednostki wymiarów (8,5 x 11 dla formatu Letter). IronPDF używa milimetrów dla większej precyzji pomiarów.
Podejście do konwersji:
// WebView2: PageWidth = 8.27 (inches for A4)
// IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
// Or custom size in mm
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(210, 297);
// WebView2: PageWidth = 8.27 (inches for A4)
// IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
// Or custom size in mm
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(210, 297);
' WebView2: PageWidth = 8.27 (inches for A4)
' IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
' Or custom size in mm
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(210, 297)
Lista kontrolna migracji WebView2
Zadania przed migracją
Zadokumentuj cały kod generujący pliki PDF wWebView2w swoim kodzie źródłowym. Zidentyfikuj, gdzieWebView2powoduje problemy (wycieki pamięci, awarie, problemy z wdrażaniem). Zapoznaj się z dokumentacją IronPDF, aby poznać możliwości tego rozwiązania.
Zadania związane z aktualizacją kodu
- Usuń pakiet NuGet Microsoft.Web.WebView2
- Zainstaluj pakiet IronPdf NuGet
- Usunąć zależności od WinForms/WPF, jeśli są one używane wyłącznie do generowania plików PDF
- Zastąp kodWebView2przez
ChromePdfRenderer - Usuń wymagania dotyczące wątków STA
- Usuń procedury obsługi zdarzeń nawigacyjnych i wzorce
TaskCompletionSource - Usuń hacki
Task.Delay - Dodaj inicjalizację licencjiIronPDFpodczas uruchamiania
Testy po migracji
Po migracji należy zweryfikować następujące aspekty:
- Przetestuj w środowisku docelowym (ASP.NET, Docker, Linux, jeśli dotyczy)
- Sprawdź, czy jakość pliku PDF odpowiada oczekiwaniom
- Sprawdź, czy strony z dużą ilością kodu JavaScript wyświetlają się poprawnie
- Sprawdź, czy nagłówki i stopki działają z funkcjami HTML IronPDF
- Test obciążeniowy stabilności pamięci podczas długotrwałej pracy
- Testuj scenariusze długotrwałe bez gromadzenia pamięci
Aktualizacje dotyczące wdrażania
- W razie potrzeby zaktualizuj obrazy Docker (usuń EdgeWebView2Runtime)
- Usunąć zależność od środowiska uruchomieniowego EdgeWebView2z wymagań serwera
- Aktualizacja dokumentacji dotyczącej wymagań serwerowych
- Sprawdź, czy wdrożenie wieloplatformowe działa na platformach docelowych
Kluczowe korzyści z migracji do IronPDF
Przejście zWebView2naIronPDFzapewnia kilka kluczowych korzyści:
Obsługa wielu platform: W przeciwieństwie do WebView2, który działa wyłącznie w systemie Windows,IronPDFdziała w systemach Windows, Linux, macOS oraz w środowisku Docker. Ta elastyczność umożliwia wdrożenie w Azure, AWS, GCP i dowolnym środowisku chmurowym bez ograniczeń platformowych.
Brak zależności od interfejsu użytkownika:IronPDFnie wymaga wątków STA, pomp komunikatów ani kontekstów WinForms/WPF. Działa w aplikacjach konsolowych, interfejsach API sieci Web, usługach systemu Windows oraz procesach działających w tle.
Stabilność pamięci: Prawidłowe zbieranie śmieci eliminuje wycieki pamięci, które nękająWebView2w długotrwałych procesach. Serwery produkcyjne pozostają stabilne.
Proste API: pojedyncze wywołania metod zastępują złożone zdarzenia nawigacyjne, wywołania zwrotne po zakończeniu, interakcje z protokołem DevTools oraz dekodowanie base64.
Rozszerzone funkcje PDF: nagłówki, stopki, znaki wodne, scalanie/dzielenie, podpisy cyfrowe, ochrona hasłem i zgodność z PDF/A — funkcje, którychWebView2nie jest w stanie zapewnić.
Aktywny rozwój: W miarę jak do 2026 r. wzrośnie popularność .NET 10 i C# 14, regularne aktualizacjeIronPDFzapewnią zgodność z obecnymi i przyszłymi wersjami .NET.

