Search code examples
asp.net-mvcasp.net-mvc-5html-to-pdf

Authentication fail error on convert Html to Pdf


I try to convert Html to PDF use "HtmlToPdf" nuget , It was work fine on local test but when i upload site to host i get this error :

 Conversion error: Authentication error.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Exception: Conversion error: Authentication error.

This is my Convert method Code

        [AllowAnonymous]
        public ActionResult Convert(int id)
        {

            HtmlToPdf converter = new HtmlToPdf();
            var context = System.Web.HttpContext.Current;
            string baseUrl = context.Request.Url.Host + ":"+context.Request.Url.Port + "/Doctor/DietTherapy/LineRegimePrint/";
            PdfDocument doc = converter.ConvertUrl(baseUrl + id);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }

How can i authorize user for this convert ?


Solution

  • It sounds like you just need to authenticate the request being made by the PDF library. For example, if it's using Basic HTTP Authentication:

    HtmlToPdf converter = new HtmlToPdf();
    converter.Options.Authentication.Username = "some username";
    converter.Options.Authentication.Password = "some password";
    // the rest of your code...
    

    The linked documentation also contains examples for other authentication methods.