Saltar al pie de página
.NET AYUDA

Cefsharp.WPF.NET Core (Cómo funciona para desarrolladores)

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

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

  • Initialize 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 Minimal Example Project on GitHub. 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.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

using IronPdf;

class Program
{
    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 Program
{
    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 Program
	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

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
Install-Package IronPdf 
dotnet add package IronPdf
SHELL

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

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 to the IronPDF NuGet Package.

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 $799 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 IronPDF Licensing Information. For further information about Iron Software, please visit their Iron Software Website.

Preguntas Frecuentes

¿Cómo puedo integrar un navegador web basado en Chromium en mi aplicación de escritorio .NET?

Puedes utilizar CefSharp, un contenedor de .NET alrededor del Chromium Embedded Framework, para integrar fácilmente un navegador web basado en Chromium en tus aplicaciones de escritorio .NET. Esto te permite aprovechar tecnologías web modernas como HTML5, CSS3 y JavaScript.

¿Qué pasos están involucrados en la configuración de CefSharp en una aplicación WPF?

Para configurar CefSharp en una aplicación WPF, comienza creando un nuevo proyecto en Visual Studio. Usa el Administrador de Paquetes NuGet para instalar el paquete CefSharp.Wpf y luego configura los ajustes necesarios para incrustar el navegador Chromium en tu aplicación.

¿Cómo convierto contenido HTML renderizado en un navegador Chromium a un documento PDF?

Para convertir contenido HTML renderizado en un navegador Chromium a PDF, primero puedes renderizar el HTML usando CefSharp y luego utilizar la función HtmlToPdf de IronPDF para generar un documento PDF.

¿Se puede utilizar CefSharp junto con herramientas de generación de PDF en una aplicación .NET?

Sí, CefSharp puede usarse junto con herramientas de generación de PDF como IronPDF dentro de una aplicación .NET. Aunque no hay una integración directa, puedes utilizar ambos para renderizar contenido HTML y convertirlo en PDFs.

¿Cuáles son los beneficios de integrar CefSharp en una aplicación .NET?

Integrar CefSharp en una aplicación .NET proporciona beneficios como la capacidad de mostrar e interactuar con contenido web moderno directamente dentro de aplicaciones de escritorio. También permite a los desarrolladores personalizar el comportamiento del navegador y utilizar tecnologías web como HTML5, CSS3 y JavaScript.

¿Cómo puedo solucionar problemas al integrar CefSharp con una aplicación .NET?

Para solucionar problemas con la integración de CefSharp, asegúrate de que todos los paquetes de NuGet estén correctamente instalados, verifica la compatibilidad con tu versión .NET y confirma la configuración en tu proyecto de Visual Studio.

¿Es posible personalizar el comportamiento del navegador Chromium en una aplicación .NET?

Sí, CefSharp permite a los desarrolladores personalizar el comportamiento del navegador Chromium integrado en una aplicación .NET, ofreciendo control sobre la configuración del navegador y la capacidad de extender funcionalidades con código personalizado.

¿Qué tipo de proyectos se benefician del uso combinado de CefSharp e IronPDF?

Proyectos que requieren mostrar contenido web dinámico y generar informes o documentación PDF directamente desde ese contenido se benefician del uso combinado de CefSharp e IronPDF. Esta combinación es ideal para aplicaciones que necesitan una gestión robusta de documentos y capacidades de renderización de contenido web.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más