.NET HELP

Cefsharp.WPF.NET Core (How It Works For Developers)

Published January 27, 2024
Share:

Introduction

Developers can now easily integrate Chromium's powerful web browser engine into their .NET desktop apps and WPF apps with CefSharp, an inventive .NET wrapper around the Chromium Embedded Framework. Rich web experiences within customized desktop interfaces are made possible for .NET app developers by CefSharp, which allows them to leverage Chromium's web features and developer tools without any external dependencies. With its wide range of new features such as customization options and command over browser behavior, this framework makes it easier to integrate contemporary web technologies like HTML5, CSS3, and JavaScript.

Users' interactions with and experiences with web-based content in desktop solutions are transformed by CefSharp's cross-platform interoperability and web content interaction capabilities, which elevate desktop programs and enable dynamic web surfing experiences right within the application environment. In this article, we are going to see more about CefSharp's open-source version using code snippets.

How to Use CefSharp

  1. Create a new Windows Form from the Visual Studio Project.
  2. Install the library CefSharp.
  3. Declare the required object for CefSharp that is ready to compile minimally.
  4. Enter the URL that needs to be loaded.
  5. Run the code.

Install CefSharp.WinForms:

  • Using Visual Studio's NuGet Package Manager is the easiest method to install CefSharp.
  • Launch the project in Visual Studio.
  • In the Solution Explorer, right-click on your project.
  • Choose "Manage NuGet Packages".
  • Go to the "Browse" tab and search for "CefSharp".
  • Select the CefSharp package (CefSharp.Wpf, CefSharp.WinForms, etc.) that is appropriate for your project.
  • To include the package in your project, click "Install".

Importance of CefSharp

CefSharp is a framework that transforms the way developers construct desktop apps and automation projects with integrated web surfing capabilities by effortlessly integrating the power of Chromium's web browser engine into .NET applications. With the help of CefSharp, we can display remote web content, including embedded UI built with HTML5 support.

Important things to emphasize in a CefSharp introduction are:

  • The Chromium Embedded Framework (CEF) serves as the framework for CefSharp, enabling the integration of the Chromium browser's features into other programs. By using Google's Chromium project, CefSharp enhances desktop programs with sophisticated web features.
  • .NET Integration: CefSharp is a powerful .NET wrapper for Cef. It makes it easy for programmers to use C# or other .NET languages to integrate a fast web browser into their desktop .NET applications.
  • Web surfing in Desktop Apps: With CefSharp, developers can easily incorporate web browsing features into their desktop programs. This feature offers up a world of possibilities for developers, enabling them to incorporate online material into their user interfaces or make unique desktop apps that are web-enabled. It can receive a callback when JavaScript events fire.
  • Rich Web Technologies Support: By using CefSharp, developers can make use of all the capabilities that Chromium has to offer, including support for the newest web standards like HTML5, CSS3, JavaScript, WebGL, and other modern web standards. This makes it possible to include cutting-edge web technologies in desktop programs.
  • Flexibility and Customization: CefSharp gives developers a great deal of flexibility and customization possibilities, allowing them to handle events, execute JavaScript, interact with online content, and modify browser behavior to suit particular application needs. CefSharp with WebGL, which leverages OpenGL/DirectX for hardware-accelerated rendering, supports 3D content.

Through the usage of CefSharp, developers can improve desktop applications by facilitating web surfing experiences, encouraging user interaction, and providing users with rich, contemporary information within the application environment.

Sample Code:

using System;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;

namespace CefSharpExample
{
    public partial class MainForm : Form
    {
        private ChromiumWebBrowser chromeBrowser;

        public MainForm()
        {
            InitializeComponent();

            // Initialize CefSharp settings
            CefSettings settings = new CefSettings();
            Cef.Initialize(settings);

            // Create the ChromiumWebBrowser instance
            chromeBrowser = new ChromiumWebBrowser("https://ironpdf.com/"); // Load a URL

            // Add the ChromiumWebBrowser control to the form
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill; // Fill the entire form

            // Handle when the browser component has finished loading
            chromeBrowser.LoadingStateChanged += ChromeBrowser_LoadingStateChanged;
        }

        private void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if (!e.IsLoading)
            {
                // Page has finished loading
                // Perform actions after the page has loaded
                Console.WriteLine("Finished loading.");
            }
        }

        // Dispose of Cef resources when the form is closed
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }
    }
}
using System;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;

namespace CefSharpExample
{
    public partial class MainForm : Form
    {
        private ChromiumWebBrowser chromeBrowser;

        public MainForm()
        {
            InitializeComponent();

            // Initialize CefSharp settings
            CefSettings settings = new CefSettings();
            Cef.Initialize(settings);

            // Create the ChromiumWebBrowser instance
            chromeBrowser = new ChromiumWebBrowser("https://ironpdf.com/"); // Load a URL

            // Add the ChromiumWebBrowser control to the form
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill; // Fill the entire form

            // Handle when the browser component has finished loading
            chromeBrowser.LoadingStateChanged += ChromeBrowser_LoadingStateChanged;
        }

        private void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if (!e.IsLoading)
            {
                // Page has finished loading
                // Perform actions after the page has loaded
                Console.WriteLine("Finished loading.");
            }
        }

        // Dispose of Cef resources when the form is closed
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }
    }
}
Imports System
Imports System.Windows.Forms
Imports CefSharp
Imports CefSharp.WinForms

Namespace CefSharpExample
	Partial Public Class MainForm
		Inherits Form

		Private chromeBrowser As ChromiumWebBrowser

		Public Sub New()
			InitializeComponent()

			' Initialize CefSharp settings
			Dim settings As New CefSettings()
			Cef.Initialize(settings)

			' Create the ChromiumWebBrowser instance
			chromeBrowser = New ChromiumWebBrowser("https://ironpdf.com/") ' Load a URL

			' Add the ChromiumWebBrowser control to the form
			Me.Controls.Add(chromeBrowser)
			chromeBrowser.Dock = DockStyle.Fill ' Fill the entire form

			' Handle when the browser component has finished loading
			AddHandler chromeBrowser.LoadingStateChanged, AddressOf ChromeBrowser_LoadingStateChanged
		End Sub

		Private Sub ChromeBrowser_LoadingStateChanged(ByVal sender As Object, ByVal e As LoadingStateChangedEventArgs)
			If Not e.IsLoading Then
				' Page has finished loading
				' Perform actions after the page has loaded
				Console.WriteLine("Finished loading.")
			End If
		End Sub

		' Dispose of Cef resources when the form is closed
		Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
			Cef.Shutdown()
		End Sub
	End Class
End Namespace
VB   C#

This code uses CefSharp to develop a basic WinForms application with an embedded web browser based on Chromium. Here is an explanation:

  • Initializes the CefSharp settings using CefSettings.
  • ChromiumWebBrowser: This class represents the CefSharp-provided web browser control.
  • The LoadingStateChanged event handles the browser's loading state changes, for example, when a page finishes loading.
  • The MainForm_FormClosing event ensures that Cef resources are properly shut down upon form closure.

For a basic example, apps built using CefSharp that are ready to compile, see the project. More complicated example projects are available in the project's source.

CefSharp with IronPDF

Integrating IronPDF's PDF-generating capabilities with CefSharp's Chromium Embedded Framework (CEF) browser requires using CefSharp and IronPDF together in a .NET application. However, as of the most recent version in January 2022, there is no direct, out-of-the-box interface between CefSharp and IronPDF.

The main goal of CefSharp is to integrate the Chromium web browser engine into .NET programs, allowing online content to be displayed and interacted with through the application's user interface. CefSharp provides browser controls for WPF and Windows Forms applications.

Although CefSharp and IronPDF are not directly integrated, developers can still use both libraries within the same application context.

Install IronPDF

To acquire the IronPDF library, you need to follow the upcoming steps. Enter the following code in the Package Manager:

Install-Package IronPdf 
dotnet add package IronPdf

CefSharp.Wpf.NetCore (How It Works for Developers): Figure 1 - Install IronPDF

Alternatively, you can use the NuGet Package Manager to search for the package "IronPDF". From the list of all the NuGet packages related to IronPDF, choose and download the necessary package.

CefSharp.Wpf.NetCore (How It Works for Developers): Figure 2 - IronPDF

Using IronPDF in CefSharp C#

To integrate IronPDF with CefSharp in a C# application, you need to perform two steps: utilize the Chromium-based browser provided by CefSharp to render HTML content and then use IronPDF to convert that HTML information into a PDF document. The following example demonstrates how to accomplish this integration:

using CefSharp;
using IronPdf;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CefSharpIronPdfIntegration
{
    public partial class MainForm : Form
    {
        private ChromiumWebBrowser chromeBrowser;

        public MainForm()
        {
            InitializeComponent();

            // Initialize CefSharp
            CefSettings settings = new CefSettings();
            Cef.Initialize(settings);

            // Create the ChromiumWebBrowser instance
            chromeBrowser = new ChromiumWebBrowser("https://ironpdf.com/"); // Load a URL

            // Add the ChromiumWebBrowser control to the form
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill; // Fill the entire form

            // Handle when the browser component has finished loading
            chromeBrowser.LoadingStateChanged += ChromeBrowser_LoadingStateChanged;
        }

        private async void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if (!e.IsLoading)
            {
                // Page has finished loading
                // Capture HTML content after page load completes
                string htmlContent = await chromeBrowser.GetSourceAsync();

                // Use IronPDF to generate a PDF from the captured HTML content
                var Renderer = new IronPdf.HtmlToPdf();
                var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
                PDF.SaveAs("Output.pdf"); // Save the generated PDF

                Console.WriteLine("PDF generated successfully.");
            }
        }

        // Dispose of Cef resources when the form is closed to avoid unnecessary memory usage
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }
    }
}
using CefSharp;
using IronPdf;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CefSharpIronPdfIntegration
{
    public partial class MainForm : Form
    {
        private ChromiumWebBrowser chromeBrowser;

        public MainForm()
        {
            InitializeComponent();

            // Initialize CefSharp
            CefSettings settings = new CefSettings();
            Cef.Initialize(settings);

            // Create the ChromiumWebBrowser instance
            chromeBrowser = new ChromiumWebBrowser("https://ironpdf.com/"); // Load a URL

            // Add the ChromiumWebBrowser control to the form
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill; // Fill the entire form

            // Handle when the browser component has finished loading
            chromeBrowser.LoadingStateChanged += ChromeBrowser_LoadingStateChanged;
        }

        private async void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if (!e.IsLoading)
            {
                // Page has finished loading
                // Capture HTML content after page load completes
                string htmlContent = await chromeBrowser.GetSourceAsync();

                // Use IronPDF to generate a PDF from the captured HTML content
                var Renderer = new IronPdf.HtmlToPdf();
                var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
                PDF.SaveAs("Output.pdf"); // Save the generated PDF

                Console.WriteLine("PDF generated successfully.");
            }
        }

        // Dispose of Cef resources when the form is closed to avoid unnecessary memory usage
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }
    }
}
Imports CefSharp
Imports IronPdf
Imports System
Imports System.Threading.Tasks
Imports System.Windows.Forms

Namespace CefSharpIronPdfIntegration
	Partial Public Class MainForm
		Inherits Form

		Private chromeBrowser As ChromiumWebBrowser

		Public Sub New()
			InitializeComponent()

			' Initialize CefSharp
			Dim settings As New CefSettings()
			Cef.Initialize(settings)

			' Create the ChromiumWebBrowser instance
			chromeBrowser = New ChromiumWebBrowser("https://ironpdf.com/") ' Load a URL

			' Add the ChromiumWebBrowser control to the form
			Me.Controls.Add(chromeBrowser)
			chromeBrowser.Dock = DockStyle.Fill ' Fill the entire form

			' Handle when the browser component has finished loading
			AddHandler chromeBrowser.LoadingStateChanged, AddressOf ChromeBrowser_LoadingStateChanged
		End Sub

		Private Async Sub ChromeBrowser_LoadingStateChanged(ByVal sender As Object, ByVal e As LoadingStateChangedEventArgs)
			If Not e.IsLoading Then
				' Page has finished loading
				' Capture HTML content after page load completes
				Dim htmlContent As String = Await chromeBrowser.GetSourceAsync()

				' Use IronPDF to generate a PDF from the captured HTML content
				Dim Renderer = New IronPdf.HtmlToPdf()
				Dim PDF = Renderer.RenderHtmlAsPdf(htmlContent)
				PDF.SaveAs("Output.pdf") ' Save the generated PDF

				Console.WriteLine("PDF generated successfully.")
			End If
		End Sub

		' Dispose of Cef resources when the form is closed to avoid unnecessary memory usage
		Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
			Cef.Shutdown()
		End Sub
	End Class
End Namespace
VB   C#

This code demonstrates a simple integration where the HTML content loaded in the Chromium browser is intercepted, and IronPDF is used to transform it into a PDF document. Here's an explanation:

  • Initialize CefSharp to integrate the Chromium browser into a Windows Forms application.
  • ChromiumWebBrowser Control: This control loads a specific URL (in this example, "https://ironpdf.com/") into the browser and creates an instance of it.
  • LoadingStateChanged Event: Tracks the loading progress of the browser. When the page finishes loading (e.IsLoading is false), the ChromeBrowser asynchronously captures the HTML content of the loaded page using GetSourceAsync().
  • IronPDF Integration: The captured HTML content (htmlContent) is converted into a PDF document using IronPDF's HtmlToPdf capability. The generated PDF is saved as "Output.pdf".
  • Form Closing: Ensure that Cef resources are properly shut down by calling Cef.Shutdown() after the form is closed.

CefSharp.Wpf.NetCore (How It Works for Developers): Figure 3 - Output

This code demonstrates a simple integration where the HTML content loaded in the Chromium browser is intercepted and then converted into a PDF document using IronPDF. Customize the URL, error handling, and other aspects according to your application's specific needs. For more information on IronPDF documentation, please refer here.

Conclusion

The integration of IronPDF with CefSharp in a C# application opens up new possibilities for managing documents and online information. By combining IronPDF's PDF-generating features with the Chromium-based browser provided by CefSharp, developers can create flexible applications that can generate high-quality PDF documents while incorporating dynamic web content.

The Lite package of IronPDF is available for $749 and includes a one-year software maintenance contract, upgrade options, a permanent license, and a thirty-day money-back guarantee. During the thirty-day trial period, users can evaluate the product in real-world scenarios with a watermarked trial version. To learn more about the cost, licensing, and free version of IronPDF, visit the link. For further information about Iron Software, please visit their website.

< PREVIOUS
Npgsql C# .NET (How It Works For Developers)
NEXT >
Microsoft Logging C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >