Zum Fußzeileninhalt springen
.NET HILFE

Webview2 C# Beispiel (Wie es für Entwickler funktioniert)

WebView2, the latest iteration of web view technology from Microsoft, is based on the Chromium engine, the same engine that powers the popular Microsoft Edge browser. The fixed version distribution allows C# developers to embed web technologies such as Hyper Text Markup Language, CSS, and JavaScript directly into their native applications. This integration opens a world of possibilities, from displaying dynamic content to building complex user interfaces.

IronPDF Overview provides the capability to generate, manipulate, and render PDF documents within C# applications. Whether it's converting online content to PDFs or creating documents from scratch, IronPDF offers a straightforward approach to handling PDFs alongside web-based data and interfaces.

This tutorial will guide you through the integration of WebView2 and IronPDF in a C# app. From basic setup to advanced functionalities, we will explore how these tools can be used in tandem to enhance your application's capabilities.

Introduction to WebView2

WebView2, powered by the Chromium-based Microsoft Edge browser, represents a significant advancement in embedding web content within C# applications. This technology enables developers to incorporate the full spectrum of the modern web into their Windows applications, offering enhanced performance, compatibility, and functionality.

The Chromium Edge Advantage

Chromium-Based: Leveraging the same engine as Microsoft Edge, WebView2 offers a more consistent and reliable rendering of web content compared to older web view controls.

Modern Web Standards: With support for the latest web standards, developers can ensure that the web content in their Windows applications remains up-to-date with current web technologies.

Getting Started with WebView2

Setting Up WebView2 in C# Projects

Integrating WebView2 into a C# project is a straightforward process. It involves adding the WebView2 SDK through NuGet, Microsoft's package manager for .NET. This SDK provides the necessary libraries and tools to embed web content into your applications using WebView2.

Webview2 C# Example (How it Works For Developers): Figure 1 - WebView2

Implementing WebView2 in Windows Forms and WPF

WebView2 can be utilized in different types of C# applications, including Windows Forms (WinForms) and Windows Presentation Foundation (WPF). Each framework has its nuances in terms of implementation, but the core concept remains the same: WebView2 acts as a container for web content within your application.

A Basic Example of Loading Web Content

Once WebView2 is set up, you can start loading web pages into your application. This can be as simple as setting the source URL to display a webpage. Here's a basic example to get you started:

using System;
using Microsoft.Web.WebView2.WinForms; // Ensure WebView2 is included

public class WebViewExample
{
    public void LoadWebPage()
    {
        var webView = new WebView2();
        webView.Source = new Uri("https://www.ironpdf.com");
        // The URI of IronPDF's site is set as the source URL for WebView
    }
}
using System;
using Microsoft.Web.WebView2.WinForms; // Ensure WebView2 is included

public class WebViewExample
{
    public void LoadWebPage()
    {
        var webView = new WebView2();
        webView.Source = new Uri("https://www.ironpdf.com");
        // The URI of IronPDF's site is set as the source URL for WebView
    }
}
Imports System
Imports Microsoft.Web.WebView2.WinForms ' Ensure WebView2 is included

Public Class WebViewExample
	Public Sub LoadWebPage()
		Dim webView = New WebView2()
		webView.Source = New Uri("https://www.ironpdf.com")
		' The URI of IronPDF's site is set as the source URL for WebView
	End Sub
End Class
$vbLabelText   $csharpLabel

In this code snippet, a new instance of WebView2 is created, and IronPDF's website is loaded into it. This illustrates how WebView2 can be used to render web pages within a C# application.

Webview2 C# Example (How it Works For Developers): Figure 2 - IronPDF

Embedding Basic Web Content

Displaying HTML, CSS, and JS in WebView2

WebView2 enables C# applications to embed and display standard web content. This includes HTML pages, Cascading Style Sheets for styling, and JavaScript for interactivity. The control functions are similar to a web browser embedded within your application, rendering web content as it would appear in Microsoft Edge.

Loading Web Pages in WebView2

The primary function of WebView2 is to load and display web pages. This is achieved by specifying a URL or loading HTML content directly. For example:

public void NavigateWebPage()
{
    var webView = new WebView2();
    webView.CoreWebView2.Navigate("https://www.ironpdf.com");
    // Navigates to the specified URL displaying the page in the application
}
public void NavigateWebPage()
{
    var webView = new WebView2();
    webView.CoreWebView2.Navigate("https://www.ironpdf.com");
    // Navigates to the specified URL displaying the page in the application
}
Public Sub NavigateWebPage()
	Dim webView = New WebView2()
	webView.CoreWebView2.Navigate("https://www.ironpdf.com")
	' Navigates to the specified URL displaying the page in the application
End Sub
$vbLabelText   $csharpLabel

This code navigates the WebView2 control to a specified web page, displaying it within the application.

Interacting with JavaScript

WebView2 allows for interactions with JavaScript within the embedded web content. This means you can execute JavaScript code from your C# application and vice versa, enabling dynamic content updates and responsive user interfaces.

Customizing the Web Experience

With WebView2, you have control over how web content is displayed and can customize various aspects, such as size, visibility, and user interaction settings. This customization makes it possible to integrate the web content seamlessly into the native user interface of your application.

Integrating WebView2 and IronPDF

IronPDF specializes in converting HTML to PDF, preserving the original layouts and styles with precision. This capability is especially useful for generating PDFs from web-based content like reports, invoices, and documentation. It supports converting HTML files, URLs, and even raw HTML strings into high-quality PDF files.

using IronPdf;

class PdfConversionExample
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class PdfConversionExample
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class PdfConversionExample
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Using WebView2 and IronPDF Together

The combination of WebView2 and IronPDF in a C# project opens up exciting possibilities. While WebView2 is excellent for displaying and interacting with web content, IronPDF excels at converting this content into PDF format. This integration allows developers to create applications that not only display web content but also provide functionality to convert web content to PDF documents.

Capturing WebView2 Content with IronPDF

Creating a Windows Forms application that includes WebView2 allows users to browse the internet within your app. Start by adding a WebView2 control to your form. This control should fill a significant portion of the form, providing ample space for web browsing. Additionally, include navigational controls like address bars and buttons for a complete browsing experience.

Adding the PDF Conversion Feature

Introduce a button on your form labeled "Convert to PDF." This button will be the trigger for users to convert the currently viewed web page into a PDF document using IronPDF.

Install IronPDF Library

Install Using NuGet Package Manager

To integrate IronPDF into your WebView2 project using the NuGet Package manager, follow these steps:

  1. Open Visual Studio and in the solution explorer, right-click on your project.
  2. Choose “Manage NuGet packages…” from the context menu.
  3. Go to the browse tab and search for IronPDF.
  4. Select IronPDF library from the search results and click the install button.
  5. Accept any license agreement prompt.

If you want to include IronPDF in your project via Package manager console, then execute the following command in the Package Manager Console:

Install-Package IronPdf

It’ll fetch and install IronPDF into your project.

Install Using NuGet Website

For a detailed overview of IronPDF, including its features, compatibility, and additional download options, visit the IronPDF page on the NuGet website at https://www.nuget.org/packages/IronPdf.

Install Via DLL

Alternatively, you can incorporate IronPDF directly into your project using its DLL file. Download the ZIP file containing the DLL from this DLL download page. Unzip it, and include the DLL in your project.

Implementing the Conversion Logic

When the user clicks the "Convert to PDF" button, your application should capture the URL or HTML content displayed in the WebView2 control. Utilize IronPDF's capabilities to convert this web content into a PDF. Here's a sample approach:

  1. Capture Current Content: When the user initiates the conversion, fetch the current content from the WebView2 control. This could be the URL or directly the HTML content.
  2. Generate PDF with IronPDF: Use IronPDF to create a PDF from the captured web content. The RenderUrlAsPdf method of ChromePdfRenderer can render the current webpage into a PDF document.
  3. Save and Notify: Save the generated PDF to a predefined location or prompt the user to choose a save location. After the PDF is saved, notify the user of the successful conversion, possibly through a message box.
private void ConvertToPdfButton_Click(object sender, EventArgs e)
{
    var renderer = new IronPdf.ChromePdfRenderer();
    var pdf = renderer.RenderUrlAsPdf(webView.CoreWebView2.Source.ToString());
    pdf.SaveAs("ConvertedWebPage.pdf");
    MessageBox.Show("PDF conversion successful!");
}
private void ConvertToPdfButton_Click(object sender, EventArgs e)
{
    var renderer = new IronPdf.ChromePdfRenderer();
    var pdf = renderer.RenderUrlAsPdf(webView.CoreWebView2.Source.ToString());
    pdf.SaveAs("ConvertedWebPage.pdf");
    MessageBox.Show("PDF conversion successful!");
}
Private Sub ConvertToPdfButton_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim renderer = New IronPdf.ChromePdfRenderer()
	Dim pdf = renderer.RenderUrlAsPdf(webView.CoreWebView2.Source.ToString())
	pdf.SaveAs("ConvertedWebPage.pdf")
	MessageBox.Show("PDF conversion successful!")
End Sub
$vbLabelText   $csharpLabel

Here is the UI output:

Webview2 C# Example (How it Works For Developers): Figure 3 - Web Page to PDF Conversion

When you click on the Convert button, it'll convert the web into PDF and show the following message box:

Webview2 C# Example (How it Works For Developers): Figure 4 - Conversion Confirmation

Conclusion

Webview2 C# Example (How it Works For Developers): Figure 5 - License

As we conclude our exploration of WebView2 and IronPDF in the realm of C# development, it's clear that the synergy between these two technologies offers a rich set of capabilities for creating dynamic and versatile applications.

By integrating WebView2, you can embed advanced web technologies directly into your C# applications, enhancing their functionality and user experience. IronPDF complements this by providing the tools to convert these web-based interfaces and content into accessible PDF documents, ideal for reporting, documentation, and data sharing.

Experience the full potential of IronPDF with a free trial of IronPDF and unlock the complete range of features with licenses beginning at $799.

Häufig gestellte Fragen

Was ist WebView2 und warum ist es wichtig für C#-Entwickler?

WebView2 ist die neueste Web-Viewer-Technologie von Microsoft, basierend auf der Chromium-Engine. Sie ermöglicht C#-Entwicklern, Webtechnologien wie HTML, CSS und JavaScript in ihre Anwendungen einzubetten und dadurch dynamische Inhalte und komplexe Benutzeroberflächen zu erstellen.

Wie kann ich WebView2 in eine C#-Anwendung integrieren?

Um WebView2 in eine C#-Anwendung zu integrieren, müssen Sie das WebView2-SDK über NuGet hinzufügen. Dies bietet die notwendigen Bibliotheken, um Webinhalte innerhalb Ihrer Anwendung einzubetten, sei es für Windows Forms oder WPF-Projekte.

Wie konvertiere ich in WebView2 angezeigte HTML-Inhalte in einer C#-Anwendung in PDF?

Sie können IronPDF verwenden, um in WebView2 angezeigte HTML-Inhalte in PDF umzuwandeln. Erfassen Sie den Inhalt oder die URL von WebView2 und verwenden Sie dann die Methoden RenderUrlAsPdf oder RenderHtmlAsPdf von IronPDF, um sie in ein PDF-Dokument zu konvertieren.

Welche Vorteile bietet die Verwendung von WebView2 gegenüber herkömmlichen Web-Viewer-Technologien in C#?

WebView2 bietet Vorteile wie die Unterstützung moderner Webstandards, zuverlässiges Rendern durch die Chromium-Engine und die nahtlose Integration von Webinhalten in native Anwendungen, was sowohl die Leistung als auch die Benutzererfahrung verbessert.

Kann ich WebView2 in sowohl Windows Forms als auch WPF-Anwendungen verwenden?

Ja, WebView2 kann sowohl in Windows Forms als auch in WPF-Anwendungen implementiert werden und dient als vielseitiger Container zum Rendern von Webinhalten innerhalb dieser Arten von C#-Anwendungen.

Wie verbessert IronPDF die Funktionalität von Anwendungen, die WebView2 verwenden?

IronPDF verbessert die Funktionalität, indem es Anwendungen, die WebView2 verwenden, ermöglicht, angezeigte Webinhalte in PDF-Dokumente zu konvertieren. Dies ist nützlich für Funktionen wie Berichterstellung und die direkte Dokumentenerstellung aus der Anwendung heraus.

Welche Schritte sind erforderlich, um IronPDF in einem C#-Projekt mit NuGet zu installieren?

Um IronPDF mit NuGet zu installieren, öffnen Sie Visual Studio, klicken Sie mit der rechten Maustaste auf Ihr Projekt, wählen Sie 'NuGet-Pakete verwalten...', suchen Sie nach IronPDF und klicken Sie auf 'Installieren'. Alternativ können Sie die Paket-Manager-Konsole mit dem Befehl Install-Package IronPdf verwenden.

Kann IronPDF Online-URLs in PDF in einer C#-Anwendung umwandeln?

Ja, IronPDF kann Online-URLs in PDF-Dokumente umwandeln. Sie können die Methode RenderUrlAsPdf verwenden, um die Webseite von einer URL abzurufen und in ein PDF zu konvertieren, wobei das Layout und die Stile beibehalten werden.

Was ist ein einfaches Beispiel zum Laden von Webinhalten in WebView2 für C#?

Ein einfaches Beispiel ist das Erstellen einer neuen Instanz von WebView2, das Setzen der Quelle auf eine URL und dann das Anzeigen der Webseite innerhalb Ihrer C#-Anwendung, wodurch eingebettete Webinhalte ermöglicht werden.

Wie können Entwickler vom Kombinieren von WebView2 und IronPDF in ihren Anwendungen profitieren?

Durch die Kombination von WebView2 und IronPDF können Entwickler Anwendungen erstellen, die Webinhalte anzeigen und in PDF umwandeln, wodurch Funktionen wie dynamisches Inhaltsmanagement, Berichterstellung und die Generierung von Dokumentationen erweitert werden.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen