ContractPdfGenerator.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. using iText.Kernel.Colors;
  2. using iText.Kernel.Font;
  3. using iText.Kernel.Pdf;
  4. using iText.Layout;
  5. using iText.Layout.Element;
  6. using iText.Layout.Properties;
  7. using MTWorkHR.Core.Entities;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using DevExpress.CodeParser;
  14. using iText.Kernel.Events;
  15. using Event = iText.Kernel.Events.Event;
  16. using MTWorkHR.Core.Global;
  17. using MTWorkHR.Infrastructure.Entities;
  18. using Microsoft.Extensions.Options;
  19. namespace MTWorkHR.Infrastructure.Reports
  20. {
  21. public class ContractPdfGenerator
  22. {
  23. public async Task<byte[]> GenerateContractPdf(string outputPath, ContractDetail contractData)
  24. {
  25. try {
  26. // Use MemoryStream to generate the PDF in memory
  27. using (MemoryStream memoryStream = new MemoryStream())
  28. {
  29. using (PdfWriter writer = new PdfWriter(memoryStream))
  30. using (PdfDocument pdf = new PdfDocument(writer))
  31. using (Document document = new Document(pdf))
  32. {
  33. PdfFont boldFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA_BOLD);
  34. PdfFont regularFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);
  35. // Timestamp and Title
  36. document.Add(new Paragraph($"{DateTime.Now:dd/MM/yyyy HH:mm:ss} .")
  37. .SetFont(regularFont)
  38. .SetFontSize(10));
  39. document.Add(new Paragraph("Employee Contract")
  40. .SetFont(boldFont)
  41. .SetFontSize(20)
  42. .SetMarginBottom(20)
  43. .SetTextAlignment(TextAlignment.CENTER));
  44. // Header
  45. // document.Add(new Paragraph("Contract Agreement")
  46. // .SetFont(boldFont)
  47. // .SetFontSize(20)
  48. // .SetTextAlignment(TextAlignment.CENTER));
  49. // Company Information
  50. document.Add(new Paragraph("Company Information:")
  51. .SetFont(boldFont)
  52. .SetFontSize(12));
  53. Table companyTable = new Table(new float[] { 1, 3, 1, 1 }).UseAllAvailableWidth();
  54. companyTable.AddCell(CreateCell("Name:", boldFont));
  55. companyTable.AddCell(CreateCell(contractData.CompanyName, regularFont));
  56. companyTable.AddCell(CreateCell("CR:", boldFont));
  57. companyTable.AddCell(CreateCell(contractData.CompanyCR, regularFont));
  58. companyTable.AddCell(CreateCell("Email:", boldFont));
  59. companyTable.AddCell(CreateCell(contractData.CompanyEmail, regularFont));
  60. companyTable.AddCell(CreateCell("Phone:", boldFont));
  61. companyTable.AddCell(CreateCell(contractData.CompanyPhone, regularFont));
  62. companyTable.AddCell(CreateCell("Address:", boldFont));
  63. companyTable.AddCell(CreateCell(contractData.CompanyAddress, regularFont, 3));
  64. document.Add(companyTable);
  65. // Company Representative
  66. document.Add(new Paragraph("Company Representative:")
  67. .SetFont(boldFont)
  68. .SetFontSize(12)
  69. .SetMarginTop(10));
  70. //Representative Table
  71. Table repTable = new Table(new float[] { 1, 3 }).UseAllAvailableWidth();
  72. // Row 1: Name
  73. repTable.AddCell(CreateCell("Name:", boldFont));
  74. repTable.AddCell(CreateCell(contractData.CompanyRepresentativeName, regularFont));
  75. // Row 2: Passport
  76. repTable.AddCell(CreateCell("Passport:", boldFont));
  77. repTable.AddCell(CreateCell(contractData.CompanyRepresentativePassport, regularFont));
  78. // Row 3: Phone
  79. repTable.AddCell(CreateCell("Phone:", boldFont));
  80. repTable.AddCell(CreateCell(contractData.CompanyRepresentativePhone, regularFont));
  81. // Row 4: Email
  82. repTable.AddCell(CreateCell("Email:", boldFont));
  83. repTable.AddCell(CreateCell(contractData.CompanyRepresentativeEmail, regularFont));
  84. // Row 5: Position
  85. repTable.AddCell(CreateCell("Position:", boldFont));
  86. repTable.AddCell(CreateCell(contractData.CompanyRepresentativePosition, regularFont));
  87. document.Add(repTable);
  88. //Employee Information
  89. document.Add(new Paragraph("Employee Information:")
  90. .SetFont(boldFont)
  91. .SetFontSize(12)
  92. .SetMarginTop(10));
  93. document.Add(new Paragraph($"Name: \t {contractData.EmployeeName}")
  94. .SetFont(regularFont));
  95. document.Add(new Paragraph($"Passport: \t {contractData.EmployeePassport}")
  96. .SetFont(regularFont));
  97. document.Add(new Paragraph($"Date Of Birth: \t {contractData.EmployeeDateOfBirth:dd/MM/yyyy}")
  98. .SetFont(regularFont));
  99. document.Add(new Paragraph($"Phone: \t {contractData.EmployeePhone}")
  100. .SetFont(regularFont));
  101. document.Add(new Paragraph($"University: \t {contractData.EmployeeUniversity}")
  102. .SetFont(regularFont));
  103. document.Add(new Paragraph($"Work Country: \t {contractData.WorkCountry}")
  104. .SetFont(regularFont));
  105. document.Add(new Paragraph($"Job: \t {contractData.JobTitleName}")
  106. .SetFont(regularFont));
  107. document.Add(new Paragraph($"Job Number: \t {contractData.JobNumber}")
  108. .SetFont(regularFont));
  109. document.Add(new Paragraph($"Job Description: \t {contractData.JobDescription}")
  110. .SetFont(regularFont));
  111. //Contract Details
  112. document.Add(new Paragraph("Contract")
  113. .SetFont(boldFont)
  114. .SetFontSize(12)
  115. .SetMarginTop(10));
  116. Table contractTable = new Table(new float[] { 1, 3, 1, 3 }).UseAllAvailableWidth();
  117. contractTable.AddCell(CreateCell("Start Date:", boldFont));
  118. contractTable.AddCell(CreateCell($"{contractData.StartDate:dd/MM/yyyy}", regularFont));
  119. contractTable.AddCell(CreateCell("End Date:", boldFont));
  120. contractTable.AddCell(CreateCell($"{contractData.EndDate:dd/MM/yyyy}", regularFont));
  121. contractTable.AddCell(CreateCell("Duration:", boldFont));
  122. contractTable.AddCell(CreateCell($"{contractData.ContractDuration}", regularFont));
  123. contractTable.AddCell(CreateCell("Contract Type:", boldFont));
  124. contractTable.AddCell(CreateCell((ContractTypeEnum)contractData.ContractTypeId + "", regularFont));
  125. contractTable.AddCell(CreateCell("Vacation Days:", boldFont));
  126. contractTable.AddCell(CreateCell($"{contractData.VacationDays}", regularFont));
  127. contractTable.AddCell(CreateCell("Trial Period:", boldFont));
  128. contractTable.AddCell(CreateCell($"{contractData.TrialPeriod}", regularFont));
  129. contractTable.AddCell(CreateCell("Termination Notice Period:", boldFont));
  130. contractTable.AddCell(CreateCell($"{contractData.NoticePeriodBeforeTermination}", regularFont));
  131. document.Add(contractTable);
  132. // Work Time
  133. document.Add(new Paragraph("Work Time")
  134. .SetFont(boldFont)
  135. .SetFontSize(12)
  136. .SetMarginTop(10));
  137. document.Add(new Paragraph($"Working Days: \t {contractData.WorkingDays}")
  138. .SetFont(regularFont));
  139. document.Add(new Paragraph($"Working Hours: \t {contractData.WorkingHours}")
  140. .SetFont(regularFont));
  141. // Salary
  142. document.Add(new Paragraph("Salary")
  143. .SetFont(boldFont)
  144. .SetFontSize(12)
  145. .SetMarginTop(10));
  146. document.Add(new Paragraph($"Amount: \t {contractData.Salary:F2} {contractData.Currency}")
  147. .SetFont(regularFont));
  148. if (contractData.FixedAllowances != null && contractData.FixedAllowances.Count > 0)
  149. {
  150. // Allowances
  151. document.Add(new Paragraph("Allowances")
  152. .SetFont(boldFont)
  153. .SetFontSize(12)
  154. .SetMarginTop(10));
  155. Table allowanceTable = new Table(new float[] { 2, 1, 2, 1 }).UseAllAvailableWidth();
  156. allowanceTable.AddHeaderCell(CreateCell("Type", boldFont));
  157. allowanceTable.AddHeaderCell(CreateCell("Rate", boldFont));
  158. allowanceTable.AddHeaderCell(CreateCell("Amount", boldFont));
  159. allowanceTable.AddHeaderCell(CreateCell("Frequency", boldFont));
  160. foreach (var allowance in contractData.FixedAllowances)
  161. {
  162. allowanceTable.AddCell(CreateCell(allowance.AllowanceType + "", regularFont));
  163. allowanceTable.AddCell(CreateCell($"{allowance.PaymentType:F2}", regularFont));
  164. allowanceTable.AddCell(CreateCell($"{allowance.EntitlementAmount:F2}", regularFont));
  165. allowanceTable.AddCell(CreateCell($"{allowance.EntitlementPercent}", regularFont));
  166. }
  167. document.Add(allowanceTable);
  168. }
  169. //ProjectStages
  170. if (contractData.ProjectStages != null && contractData.ProjectStages.Count >0)
  171. {
  172. // Allowances
  173. document.Add(new Paragraph("Project Stages")
  174. .SetFont(boldFont)
  175. .SetFontSize(12)
  176. .SetMarginTop(10));
  177. Table ProjectStagesTable = new Table(new float[] { 1, 3 }).UseAllAvailableWidth();
  178. ProjectStagesTable.AddHeaderCell(CreateCell("Title", boldFont));
  179. ProjectStagesTable.AddHeaderCell(CreateCell("Scope of work", boldFont));
  180. foreach (var allowance in contractData.ProjectStages)
  181. {
  182. ProjectStagesTable.AddCell(CreateCell(allowance.Title + "", regularFont));
  183. ProjectStagesTable.AddCell(CreateCell($"{allowance.ScopeOfWork:F2}", regularFont));
  184. }
  185. document.Add(ProjectStagesTable);
  186. }
  187. //ContractTasks
  188. if (contractData.ContractTasks != null && contractData.ContractTasks.Count > 0)
  189. {
  190. // Allowances
  191. document.Add(new Paragraph("Contract Tasks")
  192. .SetFont(boldFont)
  193. .SetFontSize(12)
  194. .SetMarginTop(10));
  195. Table ContractTasksTable = new Table(new float[] { 1, 3, 1, 3 }).UseAllAvailableWidth();
  196. ContractTasksTable.AddHeaderCell(CreateCell("Title", boldFont));
  197. ContractTasksTable.AddHeaderCell(CreateCell("Scope of work", boldFont));
  198. ContractTasksTable.AddHeaderCell(CreateCell("StartDate", boldFont));
  199. ContractTasksTable.AddHeaderCell(CreateCell("Amount", boldFont));
  200. foreach (var allowance in contractData.ContractTasks)
  201. {
  202. ContractTasksTable.AddCell(CreateCell(allowance.Title + "", regularFont));
  203. ContractTasksTable.AddCell(CreateCell($"{allowance.ScopeOfWork:F2}", regularFont));
  204. ContractTasksTable.AddCell(CreateCell($"{allowance.StartDate:dd/MM/yyyy}", regularFont));
  205. ContractTasksTable.AddCell(CreateCell($"{allowance.Amount:F2}", regularFont));
  206. }
  207. document.Add(ContractTasksTable);
  208. }
  209. // Page Numbers
  210. pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new PageNumberEventHandler(document));
  211. }
  212. byte[] pdfBytes = memoryStream.ToArray();
  213. // If you still want to save to file, you can do it here
  214. //if (!string.IsNullOrEmpty(outputPath))
  215. //{
  216. // await File.WriteAllBytesAsync(outputPath, pdfBytes);
  217. //}
  218. return pdfBytes;
  219. //return UploadToAzureBlob(pdfBytes, blobName);
  220. }
  221. }
  222. catch (Exception e)
  223. {
  224. throw e;
  225. }
  226. }
  227. public byte[] GeneratePdf()
  228. {
  229. //_logger.LogInformation("Generating PDF...");
  230. try
  231. {
  232. using (var stream = new MemoryStream())
  233. {
  234. PdfWriter writer = new PdfWriter(stream);
  235. PdfDocument pdf = new PdfDocument(writer);
  236. Document document = new Document(pdf);
  237. document.Add(new Paragraph("Hello, Azure App Service!"));
  238. document.Close();
  239. // _logger.LogInformation("PDF generated successfully.");
  240. return stream.ToArray();
  241. }
  242. }
  243. catch (Exception ex)
  244. {
  245. // _logger.LogError(ex, "Failed to generate PDF.");
  246. throw;
  247. }
  248. }
  249. //private string UploadToAzureBlob(byte[] pdfBytes, string blobName)
  250. //{
  251. // // Create a BlobServiceClient
  252. // BlobServiceClient blobServiceClient = new BlobServiceClient(_storageSettings.ConnectionString);
  253. // // Get a reference to the container
  254. // BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_storageSettings.ContainerName);
  255. // // Create the container if it doesn’t exist
  256. // containerClient.CreateIfNotExists();
  257. // // Get a reference to the blob
  258. // BlobClient blobClient = containerClient.GetBlobClient(blobName);
  259. // // Upload the PDF bytes
  260. // using (MemoryStream uploadStream = new MemoryStream(pdfBytes))
  261. // {
  262. // blobClient.Upload(uploadStream, overwrite: true);
  263. // }
  264. // // Return the Blob URL
  265. // return blobClient.Uri.ToString();
  266. //}
  267. private Cell CreateCell(string text, PdfFont font, int colspan = 1)
  268. {
  269. return new Cell(1, colspan).Add(new Paragraph(text).SetFont(font).SetFontSize(10));
  270. }
  271. private class PageNumberEventHandler : IEventHandler
  272. {
  273. private readonly Document _document;
  274. public PageNumberEventHandler(Document document)
  275. {
  276. _document = document;
  277. }
  278. public void HandleEvent(Event @event)
  279. {
  280. PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
  281. PdfDocument pdf = docEvent.GetDocument();
  282. PdfPage page = docEvent.GetPage();
  283. int pageNumber = pdf.GetPageNumber(page);
  284. PdfFont font = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);
  285. _document.ShowTextAligned(
  286. new Paragraph($"Page {pageNumber}").SetFont(font).SetFontSize(10),
  287. 550, 20, pageNumber, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
  288. }
  289. }
  290. }
  291. }
  292. //public class ContractPdfGenerator
  293. // {
  294. //public void GenerateContractPdf(string outputPath, Contract contractData)
  295. //{
  296. // using (PdfWriter writer = new PdfWriter(outputPath))
  297. // using (PdfDocument pdf = new PdfDocument(writer))
  298. // using (Document document = new Document(pdf))
  299. // {
  300. // PdfFont boldFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA_BOLD);
  301. // PdfFont regularFont = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);
  302. // // Header
  303. // document.Add(new Paragraph("Contract Agreement")
  304. // .SetFont(boldFont)
  305. // .SetFontSize(20)
  306. // .SetTextAlignment(TextAlignment.CENTER));
  307. // // Parties
  308. // document.Add(new Paragraph($"\nThis contract is made on {DateTime.Now:MMMM dd, yyyy}, between:")
  309. // .SetFont(regularFont));
  310. // document.Add(new Paragraph()
  311. // .Add(new Text("Party A: ").SetFont(boldFont))
  312. // .Add(new Text($"{contractData.CompanyId}\n").SetFont(regularFont))
  313. // .Add(new Text("Party B: ").SetFont(boldFont))
  314. // .Add(new Text($"{contractData.JobTitleName}").SetFont(regularFont)));
  315. // // Terms Table
  316. // Table table = new Table(UnitValue.CreatePercentArray(new float[] { 1, 3 })).UseAllAvailableWidth();
  317. // table.AddHeaderCell(new Cell().Add(new Paragraph("Clause").SetFont(boldFont)).SetBackgroundColor(ColorConstants.LIGHT_GRAY));
  318. // table.AddHeaderCell(new Cell().Add(new Paragraph("Description").SetFont(boldFont)).SetBackgroundColor(ColorConstants.LIGHT_GRAY));
  319. // foreach (var term in contractData.ProjectStages)
  320. // {
  321. // table.AddCell(new Cell().Add(new Paragraph(term.Title).SetFont(regularFont)));
  322. // table.AddCell(new Cell().Add(new Paragraph(term.ScopeOfWork).SetFont(regularFont)));
  323. // }
  324. // document.Add(table);
  325. // // Signatures
  326. // document.Add(new Paragraph("\nSignatures:").SetFont(boldFont).SetFontSize(14));
  327. // document.Add(new Paragraph("___________________________\nParty A Representative").SetFont(regularFont));
  328. // document.Add(new Paragraph("___________________________\nParty B Representative").SetFont(regularFont));
  329. // // Page numbers (via event handler if needed)
  330. // pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new PageNumberEventHandler(document));
  331. // }
  332. //}
  333. //private class PageNumberEventHandler : IEventHandler
  334. //{
  335. // private readonly Document _document;
  336. // public PageNumberEventHandler(Document document) => _document = document;
  337. // public void HandleEvent(iText.Kernel.Events.Event @event)
  338. // {
  339. // PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
  340. // PdfDocument pdf = docEvent.GetDocument();
  341. // PdfPage page = docEvent.GetPage();
  342. // int pageNumber = pdf.GetPageNumber(page);
  343. // PdfFont font = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);
  344. // _document.ShowTextAligned(
  345. // new Paragraph($"Page {pageNumber}").SetFont(font).SetFontSize(10),
  346. // 550, 20, pageNumber, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
  347. // }
  348. //}
  349. // }
  350. //}