푸터 콘텐츠로 바로가기
.NET 도움말

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

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();
        }
    }
}
$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");
    }
}
$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();
        }
    }
}
$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.

자주 묻는 질문

Chromium 기반 웹 브라우저를 내 .NET 데스크톱 애플리케이션에 통합하려면 어떻게 해야 하나요?

Chromium 임베디드 프레임워크의 .NET 래퍼인 CefSharp를 사용하면 Chromium 기반 웹 브라우저를 .NET 데스크톱 애플리케이션에 쉽게 통합할 수 있습니다. 이를 통해 HTML5, CSS3, JavaScript와 같은 최신 웹 기술을 활용할 수 있습니다.

WPF 애플리케이션에서 CefSharp를 설정하려면 어떤 단계를 거쳐야 하나요?

WPF 애플리케이션에서 CefSharp를 설정하려면 먼저 Visual Studio에서 새 프로젝트를 만듭니다. NuGet 패키지 관리자를 사용하여 CefSharp.Wpf 패키지를 설치한 다음 필요한 설정을 구성하여 애플리케이션에 Chromium 브라우저를 임베드합니다.

Chromium 브라우저에서 렌더링된 HTML 콘텐츠를 PDF 문서로 변환하려면 어떻게 해야 하나요?

Chromium 브라우저에서 렌더링된 HTML 콘텐츠를 PDF로 변환하려면 먼저 CefSharp를 사용하여 HTML을 렌더링한 다음 IronPDF의 HtmlToPdf 기능을 사용하여 PDF 문서를 생성할 수 있습니다.

CefSharp를 .NET 애플리케이션의 PDF 생성 도구와 함께 사용할 수 있나요?

예, CefSharp는 .NET 애플리케이션 내에서 IronPDF와 같은 PDF 생성 도구와 함께 사용할 수 있습니다. 직접적인 통합은 없지만 두 도구를 모두 활용하여 HTML 콘텐츠를 렌더링하고 PDF로 변환할 수 있습니다.

CefSharp를 .NET 애플리케이션에 통합하면 어떤 이점이 있나요?

CefSharp를 .NET 애플리케이션에 통합하면 데스크톱 애플리케이션 내에서 직접 최신 웹 콘텐츠를 표시하고 상호 작용할 수 있는 등의 이점이 있습니다. 또한 개발자는 브라우저 동작을 사용자 지정하고 HTML5, CSS3 및 JavaScript와 같은 웹 기술을 사용할 수 있습니다.

CefSharp를 .NET 애플리케이션과 통합할 때 문제를 해결하려면 어떻게 해야 하나요?

CefSharp 통합과 관련된 문제를 해결하려면 모든 NuGet 패키지가 올바르게 설치되었는지 확인하고, .NET 버전과의 호환성을 확인하고, Visual Studio 프로젝트에서 구성 설정을 확인하세요.

.NET 애플리케이션에서 Chromium 브라우저의 동작을 사용자 지정할 수 있나요?

예, CefSharp를 사용하면 개발자가 .NET 애플리케이션에 통합된 Chromium 브라우저의 동작을 사용자 지정할 수 있으므로 브라우저 설정을 제어하고 사용자 지정 코드로 기능을 확장할 수 있습니다.

CefSharp와 IronPDF를 모두 사용하면 어떤 종류의 프로젝트에 도움이 되나요?

동적 웹 콘텐츠를 표시하고 해당 콘텐츠에서 직접 PDF 보고서 또는 문서를 생성해야 하는 프로젝트는 CefSharp와 IronPDF를 모두 사용하는 것이 좋습니다. 이 조합은 강력한 문서 관리 및 웹 콘텐츠 렌더링 기능이 필요한 애플리케이션에 이상적입니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.