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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. using iTextSharp.text;
  8. using iTextSharp.text.pdf;
  9. namespace BlackRock.Reporting.API.Controllers
  10. {
  11. [Route("api/[controller]")]
  12. public class PDFGeneratorController : Controller
  13. {
  14. private readonly IHostEnvironment host;
  15. private readonly IGenerator generator;
  16. private readonly IMapper mapper;
  17. public PDFGeneratorController(IHostEnvironment host, IGenerator generator, IMapper mapper)
  18. {
  19. this.mapper = mapper;
  20. this.generator = generator;
  21. this.host = host;
  22. }
  23. [HttpGet("{url}")]
  24. public async Task<IActionResult> Get([FromQuery] OptionsForPdf pdfOptions, string url = "http://localhost:3000/#/dashboard")
  25. {
  26. if (string.IsNullOrEmpty(url))
  27. return BadRequest();
  28. var result = HttpUtility.UrlDecode(url);
  29. // Temporary name of file which will be downloaded
  30. var fileName = Guid.NewGuid().ToString() + ".pdf";
  31. // Path to wwwroot folder combined with name of pdf file
  32. string path = Path.Combine(host.ContentRootPath, $"wwwroot/pdfs/{fileName}");
  33. var options = mapper.Map<OptionsForPdf, PdfOptions>(pdfOptions);
  34. await generator.Generate(result, path, options);
  35. // Document document = new Document(PageSize.A4, 36, 36, 36 + 100, 36); // note height should be set here
  36. // MyEvent e = new MyEvent(host);
  37. // PdfWriter pw = PdfWriter.GetInstance(document, new FileStream(Path.Combine(host.ContentRootPath, "logtest.pdf"), FileMode.Create));
  38. // pw.PageEvent = e;
  39. // document.Open();
  40. // for (int i = 0; i < 100; i++)
  41. // {
  42. // document.Add(new Phrase("TESTING\n"));
  43. // }
  44. // document.Close();
  45. var pixels = CalculatePixels(options.MarginOptions.Top);
  46. ModifyPDF(path, pixels);
  47. FileStream stream = new FileStream(path, FileMode.Open);
  48. return File(stream, "application/pdf", fileName);
  49. }
  50. private double CalculatePixels(string v)
  51. {
  52. float Result;
  53. if(float.TryParse(v,out Result))
  54. return 2.83*Result;
  55. var num = float.Parse(v.Split(' ')[0]);
  56. return 2.83*num;
  57. }
  58. [HttpGet("isolate/{url}")]
  59. public async Task<IActionResult> GetIsolated([FromQuery] OptionsForPdf pdfOptions, string url = "http://localhost:3000/#/dashboard")
  60. {
  61. if (string.IsNullOrEmpty(url))
  62. return BadRequest();
  63. var result = HttpUtility.UrlDecode(url);
  64. // Temporary name of file which will be downloaded
  65. var fileName = Guid.NewGuid().ToString() + ".pdf";
  66. // Path to wwwroot folder combined with name of pdf file
  67. string path = Path.Combine(host.ContentRootPath, $"wwwroot/pdfs/{fileName}");
  68. var options = mapper.Map<OptionsForPdf, PdfOptions>(pdfOptions);
  69. await generator.Isolate(result, path, options);
  70. var pixels = CalculatePixels(options.MarginOptions.Top);
  71. ModifyPDF(path, pixels);
  72. FileStream stream = new FileStream(path, FileMode.Open);
  73. return File(stream, "application/pdf", fileName);
  74. }
  75. private void Nesto()
  76. {
  77. //string oldFile = Path.Combine(host.ContentRootPath, "0bd7e2f4-b01e-4c17-8f1e-99562d2bab4a.pdf");
  78. string oldFile = Path.Combine(host.ContentRootPath, "oldFile.pdf");
  79. string newFile = Path.Combine(host.ContentRootPath, "newFilxex.pdf");
  80. // open the reader
  81. PdfReader reader = new PdfReader(oldFile);
  82. Rectangle size = reader.GetPageSizeWithRotation(1);
  83. Document document = new Document(size);
  84. AcroFields form = reader.AcroFields;
  85. try
  86. {
  87. for (int pagew = 1; pagew <= reader.NumberOfPages; pagew++)
  88. {
  89. }
  90. }
  91. catch { }
  92. // open the writer
  93. FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
  94. PdfWriter writer = PdfWriter.GetInstance(document, fs);
  95. document.Open();
  96. // the pdf content
  97. PdfContentByte cb = writer.DirectContent;
  98. // select the font properties
  99. BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
  100. cb.SetColorFill(BaseColor.DARK_GRAY);
  101. cb.SetFontAndSize(bf, 8);
  102. // write the text in the pdf content
  103. cb.BeginText();
  104. string text = "Some random blablablabla...";
  105. // put the alignment and coordinates here
  106. cb.ShowTextAligned(1, text, 520, 640, 0);
  107. cb.EndText();
  108. cb.BeginText();
  109. text = "Other random blabla...";
  110. // put the alignment and coordinates here
  111. cb.ShowTextAligned(2, text, 100, 200, 0);
  112. cb.EndText();
  113. // create the new page and add it to the pdf
  114. PdfImportedPage page = writer.GetImportedPage(reader, 1);
  115. var pages = reader.GetPageN(1);
  116. var content = writer.DirectContent;
  117. var template = content.CreateTemplate(100, 100);
  118. float width = 100, height = 100;
  119. // PdfDictionary
  120. // pages.CreateTemplate(writer,100,100);
  121. // cb.AddTemplate(page, 0, 0);
  122. // cb.AddTemplate()
  123. // Document document = new Document(PageSize.A4, 36, 36, 36 + 100, 36); // note height should be set here
  124. MyEvent e = new MyEvent(host);
  125. //PdfWriter pw = PdfWriter.GetInstance(document, new FileStream(Path.Combine(host.ContentRootPath, "logtest.pdf"), FileMode.Create));
  126. writer.PageEvent = e;
  127. document.Open();
  128. // for (int i = 0; i < 100; i++)
  129. // {
  130. // document.Add(new Phrase("TESTING\n"));
  131. // }
  132. //document.Close();
  133. // close the streams and voilá the file should be changed :)
  134. document.Close();
  135. fs.Close();
  136. writer.Close();
  137. reader.Close();
  138. }
  139. private void ModifyPDF(string path,double marginTop)
  140. {
  141. var filePath = path;
  142. byte[] bytes = System.IO.File.ReadAllBytes(filePath);
  143. var pdfReader = new PdfReader(bytes);
  144. using (Stream output = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
  145. {
  146. using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output))
  147. {
  148. for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
  149. {
  150. pdfStamper.FormFlattening = false;
  151. Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
  152. PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
  153. pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10);
  154. PdfGState graphicsState = new PdfGState
  155. {
  156. FillOpacity = 0.3F
  157. };
  158. pdfData.SetGState(graphicsState);
  159. Image image = Image.GetInstance(Path.Combine(host.ContentRootPath, "logo.png"));
  160. var OriginalWidth = image.Width;
  161. var OriginialHeight = image.Height;
  162. var scale = OriginalWidth/OriginialHeight;
  163. OriginialHeight = (float)marginTop-5;
  164. OriginalWidth = OriginialHeight*scale;
  165. image.ScaleAbsoluteWidth(OriginalWidth);
  166. image.ScaleAbsoluteHeight(OriginialHeight);
  167. image.SetAbsolutePosition(5,pageRectangle.Height-OriginialHeight-5);
  168. pdfData.AddImage(image);
  169. // pdfData.BeginText();
  170. // // select the font properties
  171. // BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
  172. // pdfData.SetColorFill(BaseColor.BLACK);
  173. // pdfData.SetFontAndSize(bf, 8);
  174. // write the text in the pdf content
  175. // pdfData.BeginText();
  176. // string text = "Faisal Pathan";
  177. // // put the alignment and coordinates here
  178. // pdfData.ShowTextAligned(1, text, 70, 775, 0);
  179. // pdfData.EndText();
  180. // pdfData.BeginText();
  181. // string text1 = "faisalmpathan@gmail.com";
  182. // pdfData.ShowTextAligned(1, text1, 550, 775, 0);
  183. // pdfData.ShowTextAligned(0,"logo",pageRectangle.Width/2,pageRectangle.Height-15,0);
  184. // pdfData.EndText();
  185. }
  186. }
  187. output.Close();
  188. output.Dispose();
  189. }
  190. }
  191. }
  192. public partial class MyEvent : PdfPageEventHelper
  193. {
  194. public MyEvent(IHostEnvironment host)
  195. {
  196. this.host = host;
  197. }
  198. iTextSharp.text.Image image1;
  199. PdfPTable header = new PdfPTable(3);
  200. private readonly IHostEnvironment host;
  201. public override void OnOpenDocument(PdfWriter writer, Document document)
  202. {
  203. image1 = Image.GetInstance(Path.Combine(host.ContentRootPath, "logo.png"));
  204. image1.SetAbsolutePosition(20, (document.PageSize.Height - 120));
  205. //header.WriteSelectedRows(0, -1, document.Left, document.Top, writer.DirectContent);
  206. }
  207. public override void OnEndPage(PdfWriter writer, Document document)
  208. {
  209. PdfPTable tbHeader = new PdfPTable(1);
  210. tbHeader.AddCell(image1);
  211. //tbHeader.TotalWidth = image1.Width;
  212. // tbHeader.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 15, writer.DirectContent);
  213. tbHeader.WriteSelectedRows(0, -1, document.PageSize.Width / 2 - image1.Width / 2, document.PageSize.Height - 15, writer.DirectContent);
  214. }
  215. }
  216. }