Ir para o conteúdo do rodapé
GUIAS DE MIGRAçãO

Como migrar do WebView2 para o IronPDF em C#

WebView2, o controle do navegador Edge/Chromium incorporável da Microsoft (Microsoft.Web.WebView2), oferece aos desenvolvedores uma maneira de exibir conteúdo da web dentro de aplicações Windows. No entanto, quando equipes de desenvolvimento tentam usar oWebView2para geração de PDF, elas encontram limitações arquitetônicas que o tornam inadequado para cenários sem cabeça e de servidores.WebView2é um controle de incorporação de navegador projetado para aplicativos de IU, não uma biblioteca de geração de PDF.

Este guia oferece um caminho de migração doWebView2para o IronPDF, com comparações de código e exemplos práticos para desenvolvedores .NET que precisam de geração de PDF confiável em seus aplicativos.

Por que oWebView2é Inadequado para Geração de PDF

Antes de examinar o caminho de migração, ajuda entender por que oWebView2é inadequado para a criação de PDF sem cabeça:

Problema Impacto Gravidade
Vazamentos de memória Crescimento de memória reportado em processos de longa duração que criam instâncias doWebView2repetidamente. ALTO
Somente para Windows Sem suporte para Linux, macOS, Docker ou ambientes de nuvem não Windows CRÍTICO
Thread da interface do usuário necessária Deve executar em um thread STA com loop de mensagens. Não é adequado para servidores web ou APIs em segundo plano. CRÍTICO
Não foi projetado para PDFs PrintToPdfAsync é uma capacidade secundária, não uma característica central ALTO
Instabilidade nos serviços Falhas e travamentos relatados em Serviços Windows e trabalhadores em segundo plano ALTO
Fluxo assíncrono complexo Eventos de navegação, retornos de chamada de conclusão, condições de corrida ALTO
Dependência de tempo de execução do Edge Requer que o Runtime EdgeWebView2esteja instalado na máquina de destino MÉDIO
Sem modo sem tela Projetado em torno de um controle de IU; não um renderizador sem cabeça MÉDIO
Desempenho Inicialização lenta, alto consumo de recursos MÉDIO
Sem Suporte para PDF A Microsoft não posiciona oWebView2como um produto de geração de PDF MÉDIO

Cenários de falha no mundo real

Esses padrões de código comumente causam problemas em produção:

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

// Problema 1: Memory growth - creates a newWebView2per 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
}

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

// Problema 3: 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

// Problema 1: Memory growth - creates a newWebView2per 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
}

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

// Problema 3: 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

' Problema 1: 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

' Problema 2: 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 here
End Function

' Problema 3: 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
$vbLabelText   $csharpLabel

IronPDF vs WebView2: Comparação de Recursos

Compreender as diferenças arquitetônicas ajuda os responsáveis ​​pelas decisões técnicas a avaliar o investimento em migração:

Aspecto WebView2 IronPDF
Propósito Controle do navegador (interface do usuário) Biblioteca PDF (projetada para PDF)
Pronto para produção NÃO SIM
Gerenciamento de memória Crescimento de memória reportado em longos períodos Estável, devidamente descartado
Suporte da plataforma Somente para Windows Windows, Linux, macOS, Docker
Requisitos de rosca Bomba de massagem STA + Qualquer tópico
Servidor/Nuvem Não suportado Apoiado
Azure/AWS/GCP Problemático Funciona perfeitamente
Docker Não é possível. Imagens oficiais disponíveis
ASP.NET Core Não consigo trabalhar Suporte de primeira classe
Serviços de antecedentes Instável Estável
Contextos suportados Somente WinForms/WPF Qualquer contexto .NET : console, web, desktop
HTML para PDF Básico Completo
URL para PDF Básico Completo
Cabeçalhos/Rodapés NÃO Sim (HTML)
Marcas d'água NÃO Sim
Mesclar PDFs NÃO Sim
Dividir PDFs NÃO Sim
Assinaturas digitais NÃO Sim
Proteção por senha NÃO Sim
Conformidade com PDF/A NÃO Sim
Suporte profissional Nenhuma opção para PDF Sim
Documentação Limitado Extenso

Guia rápido: Migração doWebView2para o IronPDF

A migração pode começar imediatamente com esses passos fundamentais.

Passo 1: Remova o pacote WebView2

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

Ou remova do seu arquivo de projeto:


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

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

Passo 2: Instale o IronPDF

dotnet add package IronPdf

Etapa 3: Atualizar Namespaces

Substituir namespacesWebView2pelo namespace 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

Etapa 4: Inicializar a licença

Adicionar inicialização de licença na inicialização do aplicativo:

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

Exemplos de migração de código

Converter HTML para PDF

A operação mais fundamental revela a diferença de complexidade entre essas abordagens de PDF em .NET .

Abordagem WebView2:

// NuGet: Install-Package Microsoft.Web.WebView2
// (the WinForms host lives in the same package; no separate .WinForms package)
// Requires the EdgeWebView2Runtime 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 EdgeWebView2Runtime 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

Abordagem 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

A versãoWebView2requer inicialização assíncrona com EnsureCoreWebView2Async(), navegação via NavigateToString(), um Task.Delay(2000) para aguardar renderização, e uma chamada final PrintToPdfAsync que retorna um Task<bool> indicando sucesso.IronPDF elimina essa cerimônia - crie um renderizador, renderize HTML, salve.

Para cenários avançados de conversão de HTML para PDF, consulte o guia de conversão de HTML para PDF .

Converter URLs em PDF

A conversão de URL para PDF demonstra o complexo fluxo de navegação assíncrona do WebView2.

Abordagem WebView2:

// NuGet: Install-Package Microsoft.Web.WebView2
// (Edge Chromium control; requires EdgeWebView2Runtime; 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 EdgeWebView2Runtime; 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

Abordagem 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 requer a criação de um TaskCompletionSource, assinando eventos NavigationCompleted, chamando CallDevToolsProtocolMethodAsync, analisando respostas JSON e decodificando dados base64.IronPDF fornece um método RenderUrlAsPdf dedicado que lida com toda a complexidade internamente.

Consulte a documentação sobre URLs para PDF para obter informações sobre autenticação e opções de cabeçalho personalizadas.

Configurações personalizadas de PDF a partir de arquivos HTML

Configurar a orientação da página, as margens e o tamanho do papel requer abordagens diferentes.

Abordagem WebView2:

// 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

Abordagem 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 requer um Task.Delay de 3 segundos (um palpite não confiável), criando configurações de impressão através do CoreWebView2.Environment, e um await em PrintToPdfAsync(path, settings) que retorna Task<bool> ao invés de um fluxo.WebView2expressa margens em polegadas;IronPDF utiliza milímetros através de propriedades RenderingOptions diretas.

Opções avançadas de PDF com o protocolo DevTools

Configurações complexas doWebView2exigem interação com o protocolo DevTools.

Abordagem WebView2:

// 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

Abordagem 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 requer a construção de objetos anônimos, serialização para JSON, chamadas de métodos do Protocolo DevTools, análise de respostas JSON e decodificação manual de base64.IronPDF fornece propriedades tipadas com nomes claros e valores enum como PdfPaperSize.Letter.

Referência de mapeamento da APIWebView2para o IronPDF

Este mapeamento acelera a migração ao mostrar equivalentes diretos da API:

APIWebView2 Equivalente ao IronPDF
new WebView2() new ChromePdfRenderer()
EnsureCoreWebView2Async() N / D
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 em HTML
AddScriptToExecuteOnDocumentCreatedAsync() Etiquetas HTML <script>
Eventos de navegação WaitFor.JavaScript()
CallDevToolsProtocolMethodAsync("Page.printToPDF") RenderHtmlAsPdf()

Problemas e soluções comuns em migrações

Problema 1: Crescimento de Memória

Problema do WebView2: Crescimento de memória reportado em processos de longa duração que criam repetidamente instâncias do WebView2, particularmente sem uma bomba de mensagens constante.

Solução IronPDF: Descarte previsível e ciclo de vida compatível com 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

Problema 2: Ausência de thread de interface do usuário em aplicativos da Web

Problema com o WebView2: Requer uma thread STA com loop de mensagens. Controladores ASP.NET Core não conseguem criar instâncias do WebView2.

Solução IronPDF: Funciona em qualquer thread:

// 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

Problema 3: Complexidade do Evento de Navegação

Problema do WebView2: Deve lidar com eventos de navegação assíncronos, callbacks de conclusão e condições de corrida com TaskCompletionSource.

Solução IronPDF: Chamada de método único síncrona ou assíncrona:

// 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

Edição 4: Unidades de Medida

O WebView2 usa polegadas para dimensões (8,5 x 11 para o formato Carta). O IronPDF usa milímetros para medições mais precisas.

Abordagem de conversão:

// 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

Lista de verificação para migração do WebView2

Tarefas pré-migração

Documente todo o código de geração de PDF doWebView2em sua base de código. Identifique onde oWebView2está causando problemas (vazamentos de memória, travamentos, problemas de implantação). Consulte a documentação do IronPDF para se familiarizar com as funcionalidades.

Tarefas de atualização de código

  1. Remova o pacote NuGet Microsoft.Web.WebView2.
  2. Instale o pacote NuGet do IronPDF
  3. Remova as dependências do WinForms/WPF se forem usadas apenas para geração de PDFs.
  4. Substitua o códigoWebView2com ChromePdfRenderer
  5. Remover requisitos de thread STA
  6. Remova manipuladores de eventos de navegação e padrões TaskCompletionSource
  7. Remova hacks Task.Delay
  8. Adicionar inicialização da licença do IronPDF na inicialização do sistema.

Testes pós-migração

Após a migração, verifique os seguintes aspectos:

  • Testar no ambiente de destino (ASP.NET, Docker, Linux, se aplicável)
  • Verificar se a qualidade do PDF gerado corresponde às expectativas.
  • Testar se as páginas com uso intensivo de JavaScript são renderizadas corretamente.
  • Verificar se os cabeçalhos e rodapés funcionam com os recursos HTML do IronPDF.
  • Teste de carga para estabilidade da memória durante operações prolongadas
  • Teste cenários de longa duração sem acúmulo de memória

Atualizações de Implantação

  • Atualize as imagens do Docker, se aplicável (remova o EdgeWebView2Runtime).
  • Remover a dependência do EdgeWebView2Runtime dos requisitos do servidor
  • Atualizar a documentação de requisitos do servidor
  • Verificar se a implementação multiplataforma funciona nas plataformas de destino.

ObserveWebView2 é uma marca registrada de seu respectivo proprietário. Este site não é afiliado, endossado ou patrocinado pela Microsoft. Todos os nomes de produtos, logotipos e marcas são propriedade de seus respectivos proprietários. As comparações são apenas para fins informativos e refletem informações disponíveis publicamente no momento da redação.

Curtis Chau
Redator Técnico

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais ...

Leia mais

Equipe de Suporte Iron

Estamos online 24 horas por dia, 5 dias por semana.
Bater papo
E-mail
Liga para mim