Search code examples
c#htmlpdfwkhtmltopdf

How Do I Use WkHtmlToXSharp in C#


I've read a lot about WkHtmlToXSharp (wrapper for wkhtmltopdf) so I downloaded it. The one page that appears to be the only documentation states you only need the wkhtmltosharp.dll, but I can't find it in the file I downloaded. It appears to be several projects, and the thing that looks like a DLL in the Libs/Win64 folder won't load into my project.

I'd GREATLY appreciate it if someone could point me to some instructions, and maybe some basic samples. I need to know where the .DLL is, what namespace to use, and general usage syntax to convert a HTML file to PDF.

THANK YOU!!


Solution

  • public static string ConvertHTMLtoPDF(string htmlFullPath, string pageSize, string orientation)
    {
       string pdfUrl = htmlFullPath.Replace(".html", ".pdf");
    
       try
       {
           #region USING WkHtmlToXSharp.dll
           //IHtmlToPdfConverter converter = new WkHtmlToPdfConverter();
           IHtmlToPdfConverter converter = new MultiplexingConverter();
    
           converter.GlobalSettings.Margin.Top = "0cm";
           converter.GlobalSettings.Margin.Bottom = "0cm";
           converter.GlobalSettings.Margin.Left = "0cm";
           converter.GlobalSettings.Margin.Right = "0cm";
           converter.GlobalSettings.Orientation = (PdfOrientation)Enum.Parse(typeof(PdfOrientation), orientation);
           if (!string.IsNullOrEmpty(pageSize))
               converter.GlobalSettings.Size.PageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pageSize);
    
           converter.ObjectSettings.Page = htmlFullPath;
           converter.ObjectSettings.Web.EnablePlugins = true;
           converter.ObjectSettings.Web.EnableJavascript = true;
           converter.ObjectSettings.Web.Background = true;
           converter.ObjectSettings.Web.LoadImages = true;
           converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
    
           Byte[] bufferPDF = converter.Convert();
    
           System.IO.File.WriteAllBytes(pdfUrl, bufferPDF);
    
           converter.Dispose();
    
           #endregion
       }
       catch (Exception ex)
       {
           throw new Exception(ex.Message, ex);
       }
    
       return pdfUrl;
    }