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 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System.Web;
  2. using Microsoft.AspNetCore.Mvc;
  3. using PuppeteerSharp;
  4. namespace BlackRock.Reporting.API.Controllers
  5. {
  6. [Route("api/[controller]")]
  7. public class PDFGeneratorController: Controller
  8. {
  9. private readonly IHostEnvironment host;
  10. public PDFGeneratorController(IHostEnvironment host)
  11. {
  12. this.host = host;
  13. }
  14. // Pristize URL adresa izvora web stranice koju treba eksportovati u PDF fajl
  15. [HttpGet("{url}")]
  16. public async Task<IActionResult> Get(string url= "http://localhost:3000/#/dashboard")
  17. {
  18. // Service ima endpint na koji stize zahtev sa urlom strance koju treba eksportovati u PDF
  19. if (string.IsNullOrEmpty(url))
  20. return BadRequest();
  21. var result = HttpUtility.UrlDecode(url);
  22. // Temporary name of file which will be downloaded
  23. var fileName = Guid.NewGuid().ToString() + ".pdf";
  24. // Path to wwwroot folder combined with name of pdf file
  25. string path = Path.Combine(host.ContentRootPath, $"wwwroot/pdfs/{fileName}");
  26. // string path = Path.Combine(host.WebRootPath, fileName);
  27. // Generate PDF file in wwwroot
  28. // Service obradjuje zahtev
  29. // U pozadini se podize chromium koji cemo koristiti za print
  30. // Pupeter otvara stranicu sa zadatim urlom
  31. // Pokrece se Engine Modul i priprema za procesiranje strance
  32. // Transformacija stranice u print ready stranicu
  33. // Daje se instrukija pupeteru da pokrene print nad print ready stranicom
  34. await GeneratePdf(result, path);
  35. // Prepare PDF file to download
  36. // Generisani PDF fails se vraca kao rezultat obrade zahteva
  37. FileStream stream = new FileStream(path, FileMode.Open);
  38. return File(stream, "application/pdf", fileName);
  39. }
  40. private async Task GeneratePdf(string url, string path)
  41. {
  42. await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
  43. var options = new LaunchOptions
  44. {
  45. Headless = true
  46. };
  47. using (var browser = await Puppeteer.LaunchAsync(options))
  48. using (var page = await browser.NewPageAsync())
  49. {
  50. await page.GoToAsync(url, WaitUntilNavigation.DOMContentLoaded);
  51. var allResultsSelector = ".chartjs-render-monitor";
  52. await page.WaitForSelectorAsync(allResultsSelector);
  53. await EvaluateScript(page, "dist/main.js");
  54. // Transform HTML page before printing in PDF
  55. // TODO: Find solution to import some JS library
  56. // await page.EvaluateFunctionAsync("() => {document.getElementsByTagName('p')[0].style.display = 'none'}");
  57. //await page.EvaluateFunctionAsync("() => metoda()");
  58. //await page.ClickAsync("button#prepare");
  59. // Ne moze da radi jer Puppeteer ne pristupa skrivenim elementima
  60. //await page.ClickAsync("button#modify");
  61. // Resenje evaluate JS
  62. //await EvaluateScript(page, "transform.js");
  63. //string present = await CheckIfTransformExists(page);
  64. //// provera da li je transformacija vec odradjena
  65. //if (string.IsNullOrEmpty(present))
  66. //{
  67. // await EvaluateScript(page, "transform.js");
  68. //}
  69. //await EvaluateScript(page, "modify.js");
  70. //await page.EvaluateFunctionAsync("() => document.querySelector('#modify').click()");
  71. await page.PdfAsync(path, new PdfOptions() { PrintBackground = true });
  72. }
  73. }
  74. // private async Task<string> CheckIfTransformExists(Page page)
  75. // {
  76. // string path4 = Path.Combine(host.WebRootPath, "check.js");
  77. // FileStream fs4 = new FileStream(path4, FileMode.Open);
  78. // StreamReader streamReader4 = new StreamReader(fs4);
  79. // string result4 = "";
  80. // while (!streamReader4.EndOfStream)
  81. // {
  82. // result4 += (streamReader4.ReadLine() + Environment.NewLine);
  83. // }
  84. // fs4.Close();
  85. // var present = await page.EvaluateFunctionAsync<string>(result4);
  86. // return present;
  87. // }
  88. private async Task EvaluateScript(Page page,string fileName)
  89. {
  90. string path2 = Path.Combine(host.ContentRootPath, fileName);
  91. var result = await System.IO.File.ReadAllTextAsync(path2);
  92. await page.EvaluateExpressionAsync(result);
  93. }
  94. }
  95. }