Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PDFGeneratorController.cs 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System.Web;
  2. using AutoMapper;
  3. using BlackRock.Reporting.API.Core.Interfaces;
  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. }