You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PDFGeneratorController.cs 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Web;
  2. using AutoMapper;
  3. using BlackRock.Reporting.API.Core;
  4. using BlackRock.Reporting.API.Core.Models;
  5. using Microsoft.AspNetCore.Mvc;
  6. using PuppeteerSharp;
  7. namespace BlackRock.Reporting.API.Controllers
  8. {
  9. [Route("api/[controller]")]
  10. public class PDFGeneratorController : Controller
  11. {
  12. private readonly IHostEnvironment host;
  13. private readonly IGenerator generator;
  14. private readonly IMapper mapper;
  15. public PDFGeneratorController(IHostEnvironment host, IGenerator generator, IMapper mapper)
  16. {
  17. this.mapper = mapper;
  18. this.generator = generator;
  19. this.host = host;
  20. }
  21. [HttpGet("{url}")]
  22. public async Task<IActionResult> Get([FromQuery] OptionsForPdf pdfOptions, string url = "http://localhost:3000/#/dashboard")
  23. {
  24. if (string.IsNullOrEmpty(url))
  25. return BadRequest();
  26. // url must be encoded on client side and here we do decode
  27. var result = HttpUtility.UrlDecode(url);
  28. // Temporary name of file which will be downloaded
  29. var fileName = Guid.NewGuid().ToString() + ".pdf";
  30. // Path to wwwroot folder combined with name of pdf file
  31. string path = Path.Combine(host.ContentRootPath, $"wwwroot/pdfs/{fileName}");
  32. // Mapping from DTO class to Puppeteer PdfOptions class. For margins and paper format
  33. var options = mapper.Map<OptionsForPdf, PdfOptions>(pdfOptions);
  34. await generator.Generate(result, path, options);
  35. FileStream stream = new FileStream(path, FileMode.Open);
  36. return File(stream, "application/pdf", fileName);
  37. }
  38. [HttpGet("isolate/{url}")]
  39. public async Task<IActionResult> GetIsolated([FromQuery] OptionsForPdf pdfOptions, string url = "http://localhost:3000/#/dashboard")
  40. {
  41. if (string.IsNullOrEmpty(url))
  42. return BadRequest();
  43. var result = HttpUtility.UrlDecode(url);
  44. // Temporary name of file which will be downloaded
  45. var fileName = Guid.NewGuid().ToString() + ".pdf";
  46. // Path to wwwroot folder combined with name of pdf file
  47. string path = Path.Combine(host.ContentRootPath, $"wwwroot/pdfs/{fileName}");
  48. var options = mapper.Map<OptionsForPdf, PdfOptions>(pdfOptions);
  49. await generator.Isolate(result, path, options);
  50. FileStream stream = new FileStream(path, FileMode.Open);
  51. return File(stream, "application/pdf", fileName);
  52. }
  53. }
  54. }