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

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