Print PDF’s on Azure Using an API and RazorLight (Update 1)

The API mentioned in my first tutorial got taken down and so I had to do some updates.  First, choose another 3rd party API.  I currently am trying out  HTML 2 PDF Rocket and modified my code a bit:

[HttpGet]
public async Task<FileStreamResult> PrintAsync(int id)
{
    InvoiceVM invoiceVM = new InvoiceVM();
    invoiceVM = invoiceRepository.Get(id);

    var engine = new RazorLightEngineBuilder()
      .UseFilesystemProject(_hostingEnvironment.WebRootPath + "\\pdf\\")
      .UseMemoryCachingProvider()
      .Build();

    var view = await engine.CompileRenderAsync("PDF.cshtml", invoiceVM);
    string apiKey = "xxxxxxxxxxxxxxxxxxxx";

    using (var client = new WebClient())
    {
        // Build the conversion options
        NameValueCollection options = new NameValueCollection();
        options.Add("apikey", apiKey);
        options.Add("value", view);
        options.Add("MarginLeft", "10");
        options.Add("MarginRight", "10");
        options.Add("MarginTop", "10");
        options.Add("MarginBottom", "10");
        options.Add("PageSize", "Letter");

        MemoryStream ms = new MemoryStream(client.UploadValues("http://api.html2pdfrocket.com/pdf", options));

        return new FileStreamResult(ms, "application/pdf");
    }
}

This is based directly off the HTML 2 Rocket documentation.  For the rest of the code see the first tutorial.

 

You may also like