Click here to Skip to main content
15,877,857 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, I need help to open an a/3 pdf file in the Chromium web browser using C#.

I tried some samples but I got some errors. Please help using the sample code.

What I have tried:

using ChromiumWebBrowser = CefSharp.WinForms.ChromiumWebBrowser;
using CefSettings = CefSharp.WinForms.CefSettings;

namespace CefTest
    public class Program
        private static ChromiumWebBrowser browser;

        public static async Task Main(string[] args)
            await HtmlToPdfHeadless();

        private static async Task HtmlToPdfHeadless()
            const string testUrl = "";
            var settings = new CefSettings();
            browser = new ChromiumWebBrowser(testUrl);
            string path = "Test.pdf";
            Task<bool> printToPdfAsync = PrintToPdfAsync(path);
            var result = await printToPdfAsync;
        public static async Task<bool> PrintToPdfAsync(string path)
            return await browser.PrintToPdfAsync(path);


Updated 8-Jan-24 18:19pm
Richard MacCutchan 28-Dec-23 4:28am    
Please show the exact error messages in your question, and indicate where they occur.
runtime_terror 8-Jan-24 4:12am    
System.Exception: 'IBrowser instance is null. Browser has likely not finished initializing or is in the process of disposing.'

Error occurring in this line:--> await HtmlToPdfHeadless();

1 solution

The issue that you are hitting is that you instantiate the web browser, and immediately attempt to call PrintToPdf. At this point, the browser is still loading. The browser exposes an [^]IsBrowserInitializedChanged event that is fired when the browser is initialized. A word of caution - this event is raised on a CEF thread, so you may need to dispatch back to the main thread if you are using this in a screen based application.

Note, as you are attempting to print the current page to a PDF, you need to wait for the page to finish loading. You need to handle this event LoadingStateChanged Event[^] which is fired twice, the first time when the page starts loading, and then a second time when the page load completes. There is every possibility that the load page could fail, so you need to validate that it has completed successfully before you actually attempt to print the page out.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900