Passer au contenu du pied de page
VIDéOS

Comment assainir un PDF en C# | IronPDF

WebView2, le contrôle de navigateur Edge/Chromium intégrable de Microsoft (Microsoft.Web.WebView2), offre aux développeurs une manière d'afficher du contenu web au sein des applications Windows. Cependant, lorsque les équipes de développement tentent d'utiliser WebView2pour la génération de PDF, elles rencontrent des limitations architecturales qui en font un mauvais choix pour les scénarios sans tête et serveur. WebView2est un contrôle d'incorporation de navigateur conçu pour les applications UI, et non une bibliothèque de génération de PDF.

Ce guide propose un chemin de migration de WebView2vers IronPDF, avec des comparaisons de code et des exemples pratiques pour les développeurs .NET qui ont besoin d'une génération de PDF fiable dans leurs applications.

Pourquoi WebView2n'est pas adapté à la génération de PDF

Avant d'examiner le chemin de migration, il est utile de comprendre pourquoi WebView2n'est pas adapté à la création de PDF sans tête :

Problématique Impact Sévérité
Fuites de mémoire Croissance mémoire signalée dans les processus de longue durée qui créent à plusieurs reprises des instances de WebView2. HAUT
Fenêtres uniquement Pas de support pour Linux, macOS, Docker ou les environnements cloud non-Windows CRITIQUE
Filière UI requise Doit s'exécuter sur un thread STA avec une boucle de messages. Pas adapté pour les serveurs web ou les API en arrière-plan. CRITIQUE
Non conçu pour les PDF PrintToPdfAsync est une fonctionnalité secondaire, non une fonction principale HAUT
Instable dans les services Plantages et blocages signalés dans les services Windows et les travailleurs en arrière-plan HAUT
Flux asynchrone complexe Événements de navigation, rappels d'achèvement, conditions de course HAUT
Dépendance d'exécution Edge Nécessite l'installation du Runtime Edge WebView2sur la machine cible MOYEN
Pas de mode sans tête Conçu autour d'un contrôle UI ; pas un moteur de rendu sans tête MOYEN
Performance Démarrage lent, forte consommation de ressources MOYEN
Pas de prise en charge PDF Microsoft ne positionne pas WebView2comme un produit de génération de PDF MOYEN

Scénarios d'échec dans le monde réel

Ces modèles de code causent couramment des problèmes en production :

// WARNING: These patterns are known to cause problems in headless / server scenarios

// Problématique1: Memory growth - creates a new WebView2per PDF
public async Task<byte[]> GeneratePdf(string html) // High call volume accumulates memory
{
    using var webView = new WebView2(); // Disposal does not fully reclaim native resources
    await webView.EnsureCoreWebView2Async();
    webView.CoreWebView2.NavigateToString(html);
    // ... memory growth reported over time
}

// Problématique2: UI thread requirement - crashes in ASP.NET
public IActionResult GenerateReport() // FAILS - no STA thread
{
    var webView = new WebView2(); // InvalidOperationException
}

// Problématique3: Windows Service instability
public class PdfService : BackgroundService // Random crashes
{
    protected override async Task ExecuteAsync(CancellationToken token)
    {
        // WebView2+ no message pump = hangs, crashes, undefined behavior
    }
}
// WARNING: These patterns are known to cause problems in headless / server scenarios

// Problématique1: Memory growth - creates a new WebView2per PDF
public async Task<byte[]> GeneratePdf(string html) // High call volume accumulates memory
{
    using var webView = new WebView2(); // Disposal does not fully reclaim native resources
    await webView.EnsureCoreWebView2Async();
    webView.CoreWebView2.NavigateToString(html);
    // ... memory growth reported over time
}

// Problématique2: UI thread requirement - crashes in ASP.NET
public IActionResult GenerateReport() // FAILS - no STA thread
{
    var webView = new WebView2(); // InvalidOperationException
}

// Problématique3: Windows Service instability
public class PdfService : BackgroundService // Random crashes
{
    protected override async Task ExecuteAsync(CancellationToken token)
    {
        // WebView2+ no message pump = hangs, crashes, undefined behavior
    }
}
' WARNING: These patterns are known to cause problems in headless / server scenarios

' Problématique1: Memory growth - creates a new WebView2 per PDF
Public Async Function GeneratePdf(html As String) As Task(Of Byte()) ' High call volume accumulates memory
    Using webView As New WebView2() ' Disposal does not fully reclaim native resources
        Await webView.EnsureCoreWebView2Async()
        webView.CoreWebView2.NavigateToString(html)
        ' ... memory growth reported over time
    End Using
End Function

' Problématique2: UI thread requirement - crashes in ASP.NET
Public Function GenerateReport() As IActionResult ' FAILS - no STA thread
    Dim webView As New WebView2() ' InvalidOperationException
    ' Additional logic would be needed here
    Return Nothing
End Function

' Problématique3: 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
        ' Additional logic would be needed here
    End Function
End Class
$vbLabelText   $csharpLabel

IronPDF vs WebView2: Comparaison des fonctionnalités

La compréhension des différences architecturales aide les décideurs techniques à évaluer l'investissement dans la migration :

Aspect WebView2 IronPDF
Objectif Contrôle du navigateur (UI) Bibliothèque PDF (conçue pour le format PDF)
Prêt pour la production NON OUI
Gestion de la mémoire Croissance mémoire signalée dans les longues exécutions Stable, bien disposé
Support de la plateforme Windows uniquement Windows, Linux, macOS, Docker
Exigences en matière de fil conducteur STA + Message Pump N'importe quel fil
Serveur/Cloud Non pris en charge Prise en charge
Azure/AWS/GCP Problématique Fonctionne parfaitement
Docker Pas possible Images officielles disponibles
ASP.NET Core Ne peut pas travailler Une assistance de premier ordre
Services d'arrière-plan Instable Stable
Contextes pris en charge WinForms/WPF uniquement Tout contexte .NET : console, web, bureau
HTML à PDF Basique Complet
URL vers PDF Basique Complet
En-têtes/Pieds de page NON Oui (HTML)
Marqueurs d'eau NON Oui
Fusionner des PDF NON Oui
Diviser les PDF NON Oui
Signatures numériques NON Oui
Protection des mots de passe NON Oui
Conformité PDF/A NON Oui
Support professionnel Aucune pour PDF Oui
Documentation Limité Une traduction

Démarrage rapide : Migration de WebView2vers IronPDF

La migration peut commencer immédiatement grâce à ces étapes fondamentales.

Étape 1 : Supprimer le paquet WebView2

dotnet remove package Microsoft.Web.WebView2
dotnet remove package Microsoft.Web.WebView2
SHELL

Ou supprimez-la de votre fichier de projet :


<PackageReference Include="Microsoft.Web.WebView2" Version="*" Remove />

<PackageReference Include="Microsoft.Web.WebView2" Version="*" Remove />
XML

Étape 2 : Installer IronPDF

dotnet add package IronPdf

Étape 3 : Mise à jour des espaces de noms

Remplacez les espaces de noms WebView2par l'espace de nom 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
$vbLabelText   $csharpLabel

Étape 4 : initialisation de la licence

Ajouter l'initialisation de la licence au démarrage de l'application :

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
$vbLabelText   $csharpLabel

Exemples de migration de code

Conversion de HTML en PDF

L'opération la plus fondamentale révèle la différence de complexité entre ces approches PDF .NET.

Approche deWebView2:

// NuGet: Install-Package Microsoft.Web.WebView2
// (the WinForms host lives in the same package; no separate .WinForms package)
// Requires the Edge WebView2Runtime installed on the target machine. Windows-only.
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);

        // PrintToPdfAsync(path, settings) returns Task<bool>; null = default settings
        bool ok = await webView.CoreWebView2.PrintToPdfAsync("output.pdf", null);
    }
}
// NuGet: Install-Package Microsoft.Web.WebView2
// (the WinForms host lives in the same package; no separate .WinForms package)
// Requires the Edge WebView2Runtime installed on the target machine. Windows-only.
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);

        // PrintToPdfAsync(path, settings) returns Task<bool>; null = default settings
        bool ok = await webView.CoreWebView2.PrintToPdfAsync("output.pdf", null);
    }
}
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)

        ' PrintToPdfAsync(path, settings) returns Task(Of Boolean); Nothing = default settings
        Dim ok As Boolean = Await webView.CoreWebView2.PrintToPdfAsync("output.pdf", Nothing)
    End Function
End Module
$vbLabelText   $csharpLabel

Approche 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
$vbLabelText   $csharpLabel

La version WebView2nécessite une initialisation asynchrone avec EnsureCoreWebView2Async(), une navigation via NavigateToString(), un Task.Delay(2000) pour attendre le rendu, et un appel final PrintToPdfAsync qui retourne un Task<bool> indiquant le succès.IronPDF élimine cette cérémonie : créez un moteur de rendu, rendez le HTML, sauvegardez.

Pour les scénarios avancés de conversion de HTML en PDF, voir le guide de conversion de HTML en PDF.

Conversion des URL en PDF

La conversion d'URL en PDF démontre le flux de navigation asynchrone complexe de WebView2.

Approche deWebView2:

// NuGet: Install-Package Microsoft.Web.WebView2
// (Edge Chromium control; requires Edge WebView2Runtime; Windows-only.)
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
// (Edge Chromium control; requires Edge WebView2Runtime; Windows-only.)
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
$vbLabelText   $csharpLabel

Approche 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
$vbLabelText   $csharpLabel

WebView2 nécessite la création d'un TaskCompletionSource, l'abonnement aux événements NavigationCompleted, l'appel de CallDevToolsProtocolMethodAsync, l'analyse des réponses JSON, et le décodage des données base64.IronPDF fournit une méthode dédiée RenderUrlAsPdf qui gère toute la complexité en interne.

Explorez la URL vers la documentation PDF pour l'authentification et les options d'en-tête personnalisées.

Paramètres PDF personnalisés à partir de fichiers HTML

La configuration de l'orientation des pages, des marges et de la taille du papier nécessite différentes approches.

Approche deWebView2:

// NuGet: Install-Package Microsoft.Web.WebView2
// CreatePrintSettings() lives on CoreWebView2Environment.
// Margin* / PageWidth / PageHeight on CoreWebView2PrintSettings are in INCHES.
// PrintToPdfAsync(path, settings) returns Task<bool> (true on success) — not a stream.
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);

        CoreWebView2PrintSettings printSettings = webView.CoreWebView2.Environment.CreatePrintSettings();
        printSettings.Orientation = CoreWebView2PrintOrientation.Landscape;
        printSettings.MarginTop = 0.5;     // inches
        printSettings.MarginBottom = 0.5;  // inches
        printSettings.ShouldPrintBackgrounds = true;

        bool ok = await webView.CoreWebView2.PrintToPdfAsync("custom.pdf", printSettings);
        Console.WriteLine(ok ? "Custom PDF created" : "PrintToPdfAsync returned false");
    }
}
// NuGet: Install-Package Microsoft.Web.WebView2
// CreatePrintSettings() lives on CoreWebView2Environment.
// Margin* / PageWidth / PageHeight on CoreWebView2PrintSettings are in INCHES.
// PrintToPdfAsync(path, settings) returns Task<bool> (true on success) — not a stream.
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);

        CoreWebView2PrintSettings printSettings = webView.CoreWebView2.Environment.CreatePrintSettings();
        printSettings.Orientation = CoreWebView2PrintOrientation.Landscape;
        printSettings.MarginTop = 0.5;     // inches
        printSettings.MarginBottom = 0.5;  // inches
        printSettings.ShouldPrintBackgrounds = true;

        bool ok = await webView.CoreWebView2.PrintToPdfAsync("custom.pdf", printSettings);
        Console.WriteLine(ok ? "Custom PDF created" : "PrintToPdfAsync returned false");
    }
}
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 As CoreWebView2PrintSettings = webView.CoreWebView2.Environment.CreatePrintSettings()
        printSettings.Orientation = CoreWebView2PrintOrientation.Landscape
        printSettings.MarginTop = 0.5 ' inches
        printSettings.MarginBottom = 0.5 ' inches
        printSettings.ShouldPrintBackgrounds = True

        Dim ok As Boolean = Await webView.CoreWebView2.PrintToPdfAsync("custom.pdf", printSettings)
        Console.WriteLine(If(ok, "Custom PDF created", "PrintToPdfAsync returned false"))
    End Function
End Module
$vbLabelText   $csharpLabel

Approche 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
$vbLabelText   $csharpLabel

WebView2 nécessite un Task.Delay de 3 secondes (une estimation peu fiable), la création de paramètres d'impression via le CoreWebView2.Environment, et un await sur PrintToPdfAsync(path, settings) qui retourne Task<bool> au lieu d'un flux. WebView2exprime les marges en pouces ;IronPDF utilise des millimètres via des propriétés RenderingOptions directes.

Options PDF avancées avec DevTools Protocol

Les configurations complexes de WebView2nécessitent une interaction avec le protocole DevTools.

Approche deWebView2:

// NuGet: Install-Package Microsoft.Web.WebView2
// Uses raw Chrome DevTools Protocol via CallDevToolsProtocolMethodAsync.
// (Page.printToPDF returns base64 in result.data; units are inches.)
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
// Uses raw Chrome DevTools Protocol via CallDevToolsProtocolMethodAsync.
// (Page.printToPDF returns base64 in result.data; units are inches.)
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
$vbLabelText   $csharpLabel

Approche 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
$vbLabelText   $csharpLabel

WebView2 nécessite la construction d'objets anonymes, la sérialisation en JSON, l'appel de méthodes du DevTools Protocol, l'analyse des réponses JSON, et le décodage manuel de base64.IronPDF fournit des propriétés typées avec des noms clairs et des valeurs d'énumération comme PdfPaperSize.Letter.

Référence de mappage de l'APIWebView2 vers IronPDF

Cette cartographie accélère la migration en indiquant les équivalents directs des API :

API WebView2 Équivalent d'IronPDF
new WebView2() new ChromePdfRenderer()
EnsureCoreWebView2Async() N/A
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 en HTML
AddScriptToExecuteOnDocumentCreatedAsync() tags HTML <script>
Événements de navigation WaitFor.JavaScript()
CallDevToolsProtocolMethodAsync("Page.printToPDF") RenderHtmlAsPdf()

Problèmes de migration courants et solutions

Problème 1 : Croissance de la mémoire

Problème WebView2: La croissance de la mémoire est signalée dans les processus de longue durée qui créent à plusieurs reprises des instances de WebView2, en particulier sans une boucle de messages régulière.

Solution IronPDF: Élimination prévisible et cycle de vie compatible using:

//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
$vbLabelText   $csharpLabel

Édition 2 : Pas de fil d'Ariane dans les applications web

ProblèmeWebView2: Requiert un thread STA avec une pompe à messages. Les contrôleurs ASP.NET Core ne peuvent pas créer d'instances de WebView2.

La solution IronPDF: Fonctionne sur n'importe quel fil :

// 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
$vbLabelText   $csharpLabel

Édition 3 : Complexité des événements de navigation

Problème WebView2: Doit gérer les événements de navigation asynchrones, les rappels de complétion, et les conditions de course avec TaskCompletionSource.

Solution IronPDF: Appel de méthode unique synchrone ou asynchrone :

// 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);
$vbLabelText   $csharpLabel

Edition 4 : Unités de mesure

WebView2 utilise les pouces pour les dimensions (8.5 x 11 pour Letter). IronPDF utilise des millimètres pour des mesures plus précises.

Approche de conversion:

// 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)
$vbLabelText   $csharpLabel

Liste de contrôle pour la migration versWebView2

Tâches préalables à la migration

Documentez tout le code de génération de PDF WebView2dans votre base de code. Identifier où WebView2pose des problèmes (fuites de mémoire, plantages, problèmes de déploiement). Consultez la documentation IronPDF pour vous familiariser avec les capacités.

Tâches de mise à jour du code

  1. Supprimer le paquet NuGet Microsoft.Web.WebView2
  2. Installez le package NuGet IronPDF
  3. Supprimer les dépendances WinForms/WPF si elles ne sont utilisées que pour la génération de PDF
  4. Remplacer le code WebView2par ChromePdfRenderer
  5. Supprimer les exigences relatives aux fils STA
  6. Supprimer les gestionnaires d'événements de navigation et les modèles TaskCompletionSource
  7. Supprimer les hacks Task.Delay
  8. Ajouter l'initialisation de la licence IronPDF au démarrage

Test de post-migration

Après la migration, vérifiez ces aspects :

  • Test dans l'environnement cible (ASP.NET, Docker, Linux le cas échéant)
  • Vérifier que la qualité de la sortie PDF correspond aux attentes
  • Tester le bon rendu des pages contenant beaucoup de JavaScript
  • Vérifier que les en-têtes et les pieds de page fonctionnent avec les capacités HTML d'IronPDF
  • Test de charge pour la stabilité de la mémoire lors d'opérations prolongées
  • Tester des scénarios de longue durée sans accumulation de mémoire

Mises à jour du déploiement

  • Mettre à jour les images Docker le cas échéant (supprimer Edge WebView2Runtime)
  • Supprimer la dépendance Edge WebView2Runtime des exigences du serveur
  • Mise à jour de la documentation sur les exigences du serveur
  • Vérifier que le déploiement multiplateforme fonctionne sur les plateformes cibles

Veuillez noterWebView2 est une marque déposée de son propriétaire respectif. Ce site n'est pas affilié à Microsoft, ni approuvé par elle, ni sponsorisé par elle. Tous les noms de produits, logos et marques sont la propriété de leurs propriétaires respectifs. Les comparaisons sont à titre informatif uniquement et reflètent les informations publiquement disponibles au moment de l'écriture.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite

Équipe de soutien Iron

Nous sommes en ligne 24 heures sur 24, 5 jours sur 7.
Chat
Email
Appelez-moi