Converting HTML to PDF with C#

Question:

There is an HTML page consisting of 3 tables (empty), which are filled with JavaScript at a certain frequency (table data is updated). The page is viewed using a WebBrowser in a WPF application. It is necessary to generate a PDF document, which will contain the contents of the page at a certain point in time (filled tables). What libraries can do this?

I tried to execute in 2 ways the first one through ExecWB

IOleServiceProvider sp = Browser.Document as IOleServiceProvider;
if (sp != null)
{
    Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
    Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");
    const int OLECMDID_PRINT = 6;
    const int OLECMDEXECOPT_DONTPROMPTUSER = 2; const short PRINT_WAITFORCOMPLETION = 2;

    dynamic wb; 
    sp.QueryService(IID_IWebBrowserApp, IID_IWebBrowser2, out wb);
    if (wb != null)
    {
        wb.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, PRINT_WAITFORCOMPLETION,null,null);
    }
}

Instead of nulls, you can substitute in and out parameters, when I try to specify the save path, I get UnautorisedAccessException

The second way is through PdfSharp, but there I get in the file only that part of the WebBrowser that I see on the screen, and not the entire page

An alternative solution may be to get a clean Html file after executing JavaScript

Answer:

There is a wonderful service for converting HTML to PDF using C#: http://wkhtmltopdf.org

There is also a small library to speed things up: https://github.com/codaxy/wkhtmltopdf

I think you can figure it out.

Scroll to Top