-1

My team mate and I are trying to implement PDF document generation using asp.net core 3.1.

We need to first generate the pdf document and save it locally then pass the file url as json response

I am using the dotnet core library DinkToPdf, to implement PDF generation.

The code below is a sample of my controller which takes a customer Id fetch customer details to create a pdf document.

    [HttpGet("details/{customerId}", Name = "GetCustomerCertificate")]
    [ProducesResponseType(StatusCodes.Status404NotFound, Type = typeof(ResponseMessage))]
    public async Task<IActionResult> GetPolicy(int customerId)
    {
        var customer = _customerRepository.GetCustomerById(customerId);

        if ( customer == null )
        {
            return NotFound(new
            {
                Status = false,
                Message = "No customer found with this policy details.",
                Data = new { }
            });
        }
        var documentName = $"{ customer.Id.ToString() }_{ customer.FirstName}_policy_certificate.pdf";
        var documentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + "customerCertificate";
         if (!Directory.Exists(documentDirectory))
         {
             Directory.CreateDirectory(documentDirectory);
         }
       
          var globalSettings = new GlobalSettings
            {
                ColorMode = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize = PaperKind.A4,
                Margins = new MarginSettings { Top = 10 },
                DocumentTitle = "Certificate of Insurance",
                Out = @$"{documentDirectory}\{documentName}"
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount = true,
                HtmlContent = TemplateGenerator.GetDocument(customer),
                WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = $"{customer.FirstName} {customer.LastName}" }
            };
            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects = { objectSettings }
            };
            
            var generatedPDF = _converter.Convert(pdf);

            return File(generatedPDF , "application/pdf");

    }

The following code produces error when I deploy to staging server - and I also want to return the url for the file created. I wanted to know if this code implementation is correct.

The above code has been modified because of the organisation I work for

The code for TemplateGenerator.GetDocument is shown below

  public static class TemplateGenerator
  {
      public static string GetDocument(Customer customer, Policy policy)
     {            
        var pageBuilder = new StringBuilder();
        pageBuilder.Append(@"<html>"); // html tag
        pageBuilder.Append(@"<head>"); // head tag
        pageBuilder.Append(@"</head>"); // close head tag
        pageBuilder.Append(@"<body>"); // body tag

        pageBuilder.Append(@"<div class='header'>"); // header tag
        pageBuilder.AppendFormat(@"<h3>{0}</h3>", "Customer Document");
        pageBuilder.Append(@"</div>");
        pageBuilder.Append(@"<div class='container'>"); // body

        pageBuilder.Append("<table align='center'");
        pageBuilder.AppendFormat(@"
                            <tr>
                                <td>Customer Name</td>
                                <td>{0}</td>
                                <td>Premium</td>
                                <td>{1}</td>
                            </tr>
                    ", $"{customer.FirstName} {customer.LastName}", $"{customer.Premium}");

                pageBuilder.Append("</table>");

        pageBuilder.Append(@"</div>");
                pageBuilder.Append(@"</div>"); // body
            pageBuilder.Append(@"</body>");
        pageBuilder.Append(@"</html>");

        return pageBuilder.ToString();
    }
}

I get this error:

One or more errors occurred. (Unable to load DLL 'libwkhtmltox' or one of its dependencies: The specified module could not be found. (0x8007007E))

1 Answers1

0

The snippet you provided is a bit confusing as it does not really have anything to do with file handling in .Net Core. I think this answer should provide you with enough information to make it work however.

Pharnax
  • 101
  • 3