· 7 years ago · Oct 25, 2018, 06:32 AM
1using iTextSharp.text;
2using iTextSharp.text.pdf;
3using iTextSharp.text.pdf.draw;
4using System;
5using System.IO;
6using System.Web.Mvc;
7using static PalmAccounting.Models.PurchasesModel;
8using static PalmAccounting.Models.SalesModel;
9using PalmAccounting.ActionFilters;
10using PalmAccounting.App_Start; // for global functions
11using Newtonsoft.Json.Linq;
12using NumberText;
13using System.Linq;
14using System.Net.Mime;
15using PalmAccounting.Models;
16using System.Net;
17
18namespace PalmAccounting.Controllers
19{
20 [SessionTimeout]
21 [AuthorizeUser]
22 public class PDFController : Controller
23 {
24 #region FONTS TO BE USED BY THE DOCUMENT
25 // Document fonts -- embbedded fonts
26 private static Font BebasNeueBold;
27 private static Font ArialUniMs;
28 private static Font BranbolFet;
29
30 private static Font docNameFont;
31 private static Font normal;
32 private static Font BigBold;
33 // method to set the embedded font to be used in creation of the document
34 private void SetFonts()
35 {
36 BaseFont bebNeuBld = null;
37 BaseFont bebNeuLght = null;
38 BaseFont bebNeuRglr = null;
39 BaseFont bebNeuBk = null;
40 BaseFont arlUnMs = null;
41 BaseFont brabolF = null;
42 BaseFont opnSnsCndsdBld = null;
43 BaseFont opnSnsCndsdLght = null;
44 try
45 {
46 // get the path of the fonts folder
47 string fontPath = Server.MapPath(Url.Content("~/assets/fonts"));
48 // create BaseFont objects
49 bebNeuBld = BaseFont.CreateFont(fontPath + "/BebasNeue Bold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
50 bebNeuLght = BaseFont.CreateFont(fontPath + "/BebasNeue Light.otf", BaseFont.WINANSI, BaseFont.EMBEDDED);
51 bebNeuRglr = BaseFont.CreateFont(fontPath + "/BebasNeue Regular.otf", BaseFont.WINANSI, BaseFont.EMBEDDED);
52 bebNeuBk = BaseFont.CreateFont(fontPath + "/BebasNeue Book.otf", BaseFont.WINANSI, BaseFont.EMBEDDED);
53 arlUnMs = BaseFont.CreateFont(fontPath + "/ARIALUNI.TTF", BaseFont.WINANSI, BaseFont.EMBEDDED);
54 brabolF = BaseFont.CreateFont(fontPath + "/BrannbollFet.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
55 opnSnsCndsdBld = BaseFont.CreateFont(fontPath + "/OpenSansCondensed-Bold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
56 opnSnsCndsdLght = BaseFont.CreateFont(fontPath + "/OpenSansCondensed-Light.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
57 }
58 catch (DocumentException e)
59 {
60 Console.WriteLine(e.StackTrace);
61 throw e;
62 }
63 catch (IOException e)
64 {
65 Console.WriteLine(e.StackTrace);
66 throw e;
67 }
68
69 // create Font using BaseFont and Size
70 BebasNeueBold = new Font(bebNeuBld, 6);
71 ArialUniMs = new Font(arlUnMs, 10);
72 BranbolFet = new Font(brabolF, 14, Font.BOLD);
73
74
75 BigBold = new Font(opnSnsCndsdBld, 10);
76 docNameFont = new Font(opnSnsCndsdBld, 25);
77 normal = new Font(opnSnsCndsdLght, 10);
78 }
79 #endregion
80
81 #region QRCODES
82 private static Image GenerateQR(string data)
83 {
84 BarcodeQRCode qrCode = new BarcodeQRCode(data, 1000, 1000, null);
85 return qrCode.GetImage();
86 }
87 #endregion
88
89 #region CONTACT DETAILS
90 // Company variables to be used to set and retrieve company details
91 private static string CoName = "";
92 private static string CoAddress = "";
93 private static string CoTel = "";
94 private static string CoEmail = "";
95 private static string CoTin = "";
96 private static string ClName = "";
97 private static string ClAddress = "";
98 private static string ClTel = "";
99 private static string ClEmail = "";
100 private static string ClTin = "";
101
102 private static void GetContacts(string ID, string Actor, string Client)
103 {
104 try
105 {
106 string requestUrl = "";
107 if (Client.Equals("CUS"))
108 {
109 requestUrl = App_Start.Utilities.GetURL() + "CompanyWS/getContacts?SupID=&CusID=" + ID + "&Actor=" + Actor + "&App=Web";
110 }
111 else
112 {
113 requestUrl = App_Start.Utilities.GetURL() + "CompanyWS/getContacts?SupID=" + ID + "&CusID=&Actor=" + Actor + "&App=Web";
114 }
115
116 string responseFromServer = App_Start.Utilities.callURL(requestUrl);
117 JObject results = JObject.Parse(responseFromServer);
118
119 foreach (var resultObj in results["jsonResult"])
120 {
121 JObject jsonObj = null;
122 string myResult = resultObj.ToString();
123 // remove the unwanted characters
124 myResult = myResult.Replace(Environment.NewLine, "");
125 // qualify string as a json string
126 myResult = "{" + myResult + "}";
127
128 //extract list containing the company contact details
129 if (myResult.Contains("companyData"))
130 {
131 jsonObj = JObject.Parse(myResult);
132 foreach (var result in jsonObj["companyData"])
133 {
134 string Tel2 = "";
135 JToken name = result["Company"];
136 if (name is JValue) { CoName = (string)name; }
137
138 JToken address = result["Address"];
139 if (address is JValue) { CoAddress = (string)address; }
140
141 JToken tel1 = result["Phone1"];
142 if (tel1 is JValue) { CoTel = (string)tel1; }
143
144 JToken tel2 = result["Phone2"];
145 if (tel2 is JValue) { Tel2 = (string)tel2; }
146
147 JToken email = result["Email"];
148 if (email is JValue) { CoEmail = (string)email; }
149
150 JToken tin = result["Tin"];
151 if (tin is JValue) { CoTin = (string)tin; }
152
153 if (!string.IsNullOrEmpty(CoTel) && !string.IsNullOrEmpty(Tel2))
154 {
155 CoTel = CoTel + "/" + Tel2;
156 }
157 else if (string.IsNullOrEmpty(CoTel) && !string.IsNullOrEmpty(Tel2))
158 {
159 CoTel = Tel2;
160 }
161 }
162 }
163
164 //extract list containing the company contact details
165 if (myResult.Contains("clientData"))
166 {
167 jsonObj = JObject.Parse(myResult);
168 foreach (var result in jsonObj["clientData"])
169 {
170 string Tel2 = "";
171
172 JToken name = result["BusName"];
173 if (name is JValue) { ClName = (string)name; }
174
175 JToken address = result["Address"];
176 if (address is JValue) { ClAddress = (string)address; }
177
178 JToken tel1 = result["Phone1"];
179 if (tel1 is JValue) { ClTel = (string)tel1; }
180
181 JToken tel2 = result["Phone2"];
182 if (tel2 is JValue) { Tel2 = (string)tel2; }
183
184 JToken email = result["Email"];
185 if (email is JValue) { ClEmail = (string)email; }
186
187 JToken tin = result["Tin"];
188 if (tin is JValue) { ClTin = (string)tin; }
189
190 if (!string.IsNullOrEmpty(ClTel) && !string.IsNullOrEmpty(Tel2))
191 {
192 ClTel = ClTel + "/" + Tel2;
193 }
194 else if (string.IsNullOrEmpty(ClTel) && !string.IsNullOrEmpty(Tel2))
195 {
196 ClTel = Tel2;
197 }
198 }
199 }
200 }
201 }
202 catch (Exception e)// Document Exception..// FileNotFoundException
203 {
204 Console.WriteLine("{0} Exception caught", e.Message);
205 throw e;
206 }
207 }
208 #endregion
209
210 #region PRINT NOTES
211 // Company variables to be used to set and retrieve company details
212 private static string Line1 = "";
213 private static string Line2 = "";
214 private static string Line3 = "";
215 private static string Line4 = "";
216 private static string Line5 = "";
217 private static string Header = "";
218 private static string Sign = "";
219 private static string Signitory = "";
220 private static string PayHistory = "";
221
222 private static void GetPrintNotes(string DocType, string Actor)
223 {
224 try
225 {
226 string requestUrl = App_Start.Utilities.GetURL() + "CompanyWS/getPrintNotes?DocTyp=" + DocType + "&Actor=" + Actor + "&App=Web";
227
228 string responseFromServer = App_Start.Utilities.callURL(requestUrl);
229 JObject results = JObject.Parse(responseFromServer);
230
231 foreach (var result in results["jsonResult"])
232 {
233 JToken line1 = result["Line1"];
234 if (line1 is JValue) { Line1 = (string)line1; }
235
236 JToken line2 = result["Line2"];
237 if (line2 is JValue) { Line2 = (string)line2; }
238
239 JToken line3 = result["Line3"];
240 if (line3 is JValue) { Line3 = (string)line3; }
241
242 JToken line4 = result["Line4"];
243 if (line4 is JValue) { Line4 = (string)line4; }
244
245 JToken line5 = result["Line5"];
246 if (line5 is JValue) { Line5 = (string)line5; }
247
248 JToken header = result["Header"];
249 if (header is JValue) { Header = (string)header; }
250
251 JToken sign = result["Sign"];
252 if (sign is JValue) { Sign = (string)sign; }
253
254 JToken signitory = result["Signitory"];
255 if (signitory is JValue) { Signitory = (string)signitory; }
256
257 JToken payHistory = result["PayHistory"];
258 if (payHistory is JValue) { PayHistory = (string)payHistory; }
259 }
260 }
261 catch (Exception e)
262 {
263 Console.WriteLine("{0} Exception caught", e.Message);
264 throw e;
265 }
266 }
267 #endregion
268
269 #region CELLS
270 // methods to manage generation of cell with certain properties
271 static PdfPCell NoBdrFntN(string data, int HAlign)
272 {
273 PdfPCell cell = new PdfPCell(new Phrase(data, normal))
274 {
275 Border = 0,
276 HorizontalAlignment = HAlign //0=Left, 1=Centre, 2=Right
277 };
278 return cell;
279 }
280 static PdfPCell NoBdrFntB(string data, int HAlign)
281 {
282 PdfPCell cell = new PdfPCell(new Phrase(data, BigBold))
283 {
284 Border = 0,
285 HorizontalAlignment = HAlign //0=Left, 1=Centre, 2=Right
286 };
287 return cell;
288 }
289 static PdfPCell NoBdrFntN(string data, int HAlign, int VAlign)
290 {
291 PdfPCell cell = new PdfPCell(new Phrase(data, normal))
292 {
293 Border = 0,
294 HorizontalAlignment = HAlign, //0=Left, 1=Centre, 2=Right
295 VerticalAlignment = VAlign
296 };
297 return cell;
298 }
299 static PdfPCell NoBdrFntB(string data, int HAlign, int VAlign)
300 {
301 PdfPCell cell = new PdfPCell(new Phrase(data, BigBold))
302 {
303 Border = 0,
304 HorizontalAlignment = HAlign, //0=Left, 1=Centre, 2=Right
305 VerticalAlignment = VAlign
306 };
307 return cell;
308 }
309 static PdfPCell NoBdrFntN(string data, int HAlign, int colSpan, int rowSpan)
310 {
311 PdfPCell cell = new PdfPCell(new Phrase(data, normal))
312 {
313 Border = 0,
314 Colspan = colSpan,
315 Rowspan = rowSpan,
316 HorizontalAlignment = HAlign //0=Left, 1=Centre, 2=Right
317 };
318 return cell;
319 }
320 static PdfPCell NoBdrFntB(string data, int HAlign, int colSpan, int rowSpan)
321 {
322 PdfPCell cell = new PdfPCell(new Phrase(data, BigBold))
323 {
324 Border = 0,
325 Colspan = colSpan,
326 Rowspan = rowSpan,
327 HorizontalAlignment = HAlign //0=Left, 1=Centre, 2=Right
328 };
329 return cell;
330 }
331 static PdfPCell NoBdrFntN(string data, int HAlign, int VAlign, int colSpan, int rowSpan)
332 {
333 PdfPCell cell = new PdfPCell(new Phrase(data, normal))
334 {
335 Border = 0,
336 Colspan = colSpan,
337 Rowspan = rowSpan,
338 HorizontalAlignment = HAlign, //0=Left, 1=Centre, 2=Right
339 VerticalAlignment = VAlign
340 };
341 return cell;
342 }
343 static PdfPCell NoBdrFntB(string data, int HAlign, int VAlign, int colSpan, int rowSpan)
344 {
345 PdfPCell cell = new PdfPCell(new Phrase(data, BigBold))
346 {
347 Border = 0,
348 Colspan = colSpan,
349 Rowspan = rowSpan,
350 HorizontalAlignment = HAlign, //0=Left, 1=Centre, 2=Right
351 VerticalAlignment = VAlign
352 };
353 return cell;
354 }
355 static PdfPCell BGLightGray(PdfPCell cell)
356 {
357 cell.BackgroundColor = BaseColor.LIGHT_GRAY;
358 cell.UseVariableBorders = true;
359 return cell;
360 }
361 #endregion
362
363 #region FILE HANDLER -- Returns the file path
364 private string FileHandler(string DocName, string DocRefNo)
365 {
366 // get the path to the pdf folder
367 string pdfFolderPath = Server.MapPath(Url.Content("~/PDF"));
368
369 // get the document name
370 string fileName = DocRefNo + ".pdf";
371
372 // name of the folder to which the file is to be saved
373 string docFolder = DocName + "PDFs";
374
375 // name of the folder to which the file is to be saved
376 string docFolderPath = Path.Combine(pdfFolderPath, docFolder);
377
378 // create folder if it doesn't exit
379 Directory.CreateDirectory(docFolderPath);
380
381 // get the path to the document
382 string docPath = Path.Combine(docFolderPath, fileName);
383
384 // check if document already exists and if file exists, move it to the backup folder
385 if (System.IO.File.Exists(docPath))
386 {
387 // set new file name by appending the current time stamp
388 string nwFileName = fileName.AppendTimestamp();
389
390 // name of the backup folder
391 string backupFolder = "BACKUP";
392
393 // getting the path to the backup folder to which the file is to be moved
394 string backupFolderPath = Path.Combine(pdfFolderPath, backupFolder, docFolder);
395
396 // create the folder if it doesn't exist...
397 Directory.CreateDirectory(backupFolderPath);
398
399 // name of the new file location
400 string backupDocPath = Path.Combine(backupFolderPath, nwFileName);
401
402 //move the file to the backup folder
403 System.IO.File.Move(docPath, backupDocPath);
404
405 }
406 return docPath;
407 }
408 #endregion
409
410 // create file
411 public ActionResult CreatePdfFile(string DocName, string RefNo)
412 {
413 try
414 {
415 #region INITIALIZATIONS
416
417 string Actor = (string)Session["UserID"];
418 string DocNamePrinted = "";
419 string AmountInWords = "";
420 // setting the embedded fonts
421 SetFonts();
422
423 PDFModel model = new PDFModel();
424 model = (PDFModel)Session["PdfModel"];
425 if(model==null)
426 {
427 return RedirectToAction("GetDocDetails", new { DocName = DocName, RefNo = RefNo });
428 }
429 //IN CASE WE SELECTED PDF FOR A DOCUMENT DIFERENT FROM ONE IN THE SESSION
430 if(model.DocName != DocName)
431 {
432 return RedirectToAction("GetDocDetails", new { DocName = DocName, RefNo = RefNo });
433 }
434 #endregion
435
436 #region GETTING PRINT NOTES...
437 GetPrintNotes(model.DocName, Actor);
438 #endregion
439
440 #region SETTING DOCUMENT TITLE...
441 if (model.DocName == "QUOTATION")
442 {
443 DocNamePrinted = "Proforma Invoice";
444 DocName = "Quotation";
445 }
446 else if (model.DocName == "INVOICE")
447 {
448 DocNamePrinted = "Tax Invoice";
449 DocName = "Invoice";
450 }
451 else if (model.DocName == "BILL")
452 {
453 DocNamePrinted = "Bill";
454 DocName = "Bill";
455 }
456 else if (model.DocName == "PO")
457 {
458 DocNamePrinted = "Purchase Order";
459 DocName = "PO";
460 }
461 else if (model.DocName == "RECEIPT")
462 {
463 DocNamePrinted = "Receipt";
464 DocName = "Receipt";
465 }
466 else if (model.DocName == "INVRECEIPT")
467 {
468 DocNamePrinted = "Receipt";
469 DocName = "Receipt";
470 }
471 else if (model.DocName == "PAYMENT")
472 {
473 DocNamePrinted = "Payment Voucher";
474 DocName = "Payment";
475 }
476 else if (model.DocName == "DIRECTPAYMENT")
477 {
478 DocNamePrinted = "Payment Voucher";
479 DocName = "Payment";
480 }
481 else if (model.DocName == "ADVANCE")
482 {
483 DocNamePrinted = "Supplier Advance Voucher";
484 DocName = "Advance";
485 }
486 else if (model.DocName == "DEPOSIT")
487 {
488 DocNamePrinted = "Customer Deposit Voucher";
489 DocName = "Deposit";
490 }
491 #endregion
492
493 #region GET FILENAME AND OPEN NEW DOCUMENT.
494 //get the path to the new file that is to be created...
495 string path = FileHandler(model.DocName, model.DocRef);
496
497 //Creating a new pdf document to which we are to write the new data
498 var doc = new Document();
499
500 PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
501 // open the document
502 doc.Open();
503 #endregion
504
505 #region GLOBAL VARIABLES...
506 // global cell to be used by for all the tables
507 PdfPCell cell = new PdfPCell();
508 Phrase blank = new Phrase("");
509 float[] colWidths = new float[] { };
510 #endregion
511
512 #region COMPANY LOGO. tbCompanyLogo
513 string logoFolderPath = Server.MapPath(Url.Content("~/assets/images"));
514 // logo name
515 string logoName = "document_header.png";
516 // getting the path to the logo
517 string logoPath = Path.Combine(logoFolderPath, logoName);
518 // get the users logo...
519 Image CompanyLogo = Image.GetInstance(logoPath);
520 CompanyLogo.Alignment = Element.ALIGN_MIDDLE;
521 PdfPTable tbCompLogo = new PdfPTable(1);
522 tbCompLogo.TotalWidth = 540f;
523 PdfPCell cellLogo = new PdfPCell();
524 cellLogo.Border = 0;
525 cellLogo.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
526 cellLogo.AddElement(CompanyLogo);
527 tbCompLogo.AddCell(cellLogo);
528 #endregion
529
530 #region DOCUMENT HEADER TABLE. tbDocHeader
531 PdfPTable tbDocHeader = new PdfPTable(3);
532 tbDocHeader.DefaultCell.Border = Rectangle.NO_BORDER;
533 tbDocHeader.TotalWidth = 540f;
534 tbDocHeader.LockedWidth = true;
535 colWidths = new float[] { 1f, 88f, 1f };
536 tbDocHeader.SetWidths(colWidths);
537 tbDocHeader.SpacingBefore = 20f;
538 tbDocHeader.AddCell("");
539 tbDocHeader.AddCell(tbCompLogo);
540 tbDocHeader.AddCell("");
541 tbDocHeader.DefaultCell.Border = Rectangle.NO_BORDER;
542 #endregion
543
544 #region DOCUMENT NAME. tbDocName
545 // Company name
546 PdfPTable tbDocName = new PdfPTable(1);
547 cell = new PdfPCell(new Phrase(DocNamePrinted, docNameFont));
548 cell.Border = 0;
549 //cell.VerticalAlignment = Element.ALIGN_MIDDLE;
550 cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
551 tbDocName.AddCell(cell);
552 #endregion
553
554 #region QRCODE. tbQRImage
555 // get the qrImage by supplying the necessary information... DocName+CreateDt+CompanyName+ClientName+DocTotal
556 Image qrCdImg = GenerateQR(CoName + "/" + model.DocRef + "/" + model.TransDt + "/" + ClName + "/" + string.Format("{0:n0}", model.TotAmt));
557 qrCdImg.ScaleAbsolute(60, 60);
558 qrCdImg.Alignment = Element.ALIGN_MIDDLE;
559 PdfPTable tbQRImage = new PdfPTable(1);
560 cell = new PdfPCell();
561 cell.AddElement(qrCdImg);
562 cell.VerticalAlignment = Element.ALIGN_MIDDLE;
563 cell.Border = Rectangle.NO_BORDER;
564 tbQRImage.AddCell(cell);
565 #endregion
566
567 #region COMPANY DETAILS. tbCompanyDtls
568 // Company Details
569 PdfPTable tbCompanyDtls = new PdfPTable(1);
570 tbCompanyDtls.AddCell(NoBdrFntB(CoName, 0));
571 tbCompanyDtls.AddCell(NoBdrFntN(CoAddress, 0));
572 if (!string.IsNullOrEmpty(CoTel))
573 {
574 tbCompanyDtls.AddCell(NoBdrFntN("Phone: " + CoTel, 0));
575 }
576 tbCompanyDtls.AddCell(NoBdrFntN("Email: " + CoEmail, 0));
577 if (!string.IsNullOrEmpty(CoTin))
578 {
579 tbCompanyDtls.AddCell(NoBdrFntB("TIN: " + CoTin, 0));
580 }
581 #endregion
582
583 #region DOC NAME, QR CODE AND COMPANY ADDRESS. tbDocNameQRCode
584 PdfPTable tbDocNameQRCode = new PdfPTable(3);
585 //remove borders
586 tbDocNameQRCode.DefaultCell.Border = Rectangle.NO_BORDER;
587 //actual width of table in points
588 tbDocNameQRCode.TotalWidth = 540f;
589 //fix the absolute width of the table
590 tbDocNameQRCode.LockedWidth = true;
591 colWidths = new float[] { 20f, 50f, 20f };
592 tbDocNameQRCode.SetWidths(colWidths);
593 //leave a gap before and after the table
594 tbDocNameQRCode.SpacingBefore = 20f;
595 //tbDocNameQRCode.AddCell(tbQRImage);
596 tbDocNameQRCode.AddCell("");
597 tbDocNameQRCode.AddCell(tbDocName);// doc name
598 tbDocNameQRCode.AddCell("");
599 tbDocNameQRCode.DefaultCell.Border = Rectangle.NO_BORDER;
600 #endregion
601
602 #region CUSTOMER DETAILS. tbCustomer
603 // Supplier/Customer Details
604 string ClientType = "";
605 if(!string.IsNullOrEmpty(model.CusID))
606 {
607 GetContacts(model.CusID, model.Actor, "CUS");
608 ClientType = "Customer";
609 }
610 if (!string.IsNullOrEmpty(model.SupID))
611 {
612 GetContacts(model.SupID, model.Actor, "SUP");
613 ClientType = "Supplier";
614 }
615
616 PdfPTable tbCustomer = new PdfPTable(1);
617
618 tbCustomer.AddCell(NoBdrFntB(ClientType+":", 0));
619 tbCustomer.AddCell(NoBdrFntB(ClName, 0));
620 if (!string.IsNullOrEmpty(ClAddress))
621 {
622 tbCustomer.AddCell(NoBdrFntN(ClAddress, 0));
623 }
624 if (!string.IsNullOrEmpty(ClTel))
625 {
626 tbCustomer.AddCell(NoBdrFntN("Phone: " + ClTel, 0));
627 }
628 if (!string.IsNullOrEmpty(ClEmail))
629 {
630 tbCustomer.AddCell(NoBdrFntN("Email: " + ClEmail, 0));
631 }
632 if (!string.IsNullOrEmpty(ClTin))
633 {
634 tbCustomer.AddCell(NoBdrFntB("TIN: " + ClTin, 0));
635 }
636 #endregion
637
638 #region DOCUMENT REFERENCES. tbDocReferences
639 //Document specs/Refs
640 PdfPTable tbDocReferences = new PdfPTable(2);
641 //project name
642 if (!string.IsNullOrEmpty(CoTin))
643 {
644 cell = new PdfPCell(new Phrase("TIN: ", ArialUniMs));
645 cell.Border = 0;
646 tbDocReferences.AddCell(cell);
647 cell = new PdfPCell(new Phrase(CoTin, BigBold));
648 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
649 cell.Border = 0;
650 tbDocReferences.AddCell(cell);
651 }
652 //doc number
653 cell = new PdfPCell(new Phrase(DocName + " No: ", ArialUniMs));
654 cell.Border = 0;
655 tbDocReferences.AddCell(cell);
656 cell = new PdfPCell(new Phrase(model.DocRef, BigBold));
657 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
658 cell.Border = 0;
659 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
660 tbDocReferences.AddCell(cell);
661
662 //doc creation date
663 cell = new PdfPCell(new Phrase(DocName + " Date: ", ArialUniMs));
664 cell.Border = 0;
665 tbDocReferences.AddCell(cell);
666 cell = new PdfPCell(new Phrase(model.TransDt, BigBold));
667 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
668 cell.Border = 0;
669 tbDocReferences.AddCell(cell);
670
671 //doc references
672 if (!string.IsNullOrEmpty(model.OtherRef))
673 {
674 cell = new PdfPCell(new Phrase("Refference: ", ArialUniMs));
675 cell.Border = 0;
676 tbDocReferences.AddCell(cell);
677 cell = new PdfPCell(new Phrase(model.OtherRef, BigBold));
678 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
679 cell.Border = 0;
680 tbDocReferences.AddCell(cell);
681 }
682 //doc due date
683 if (!string.IsNullOrEmpty(model.DueDt))
684 {
685 cell = new PdfPCell(new Phrase("Due Date: ", ArialUniMs));
686 cell.Border = 0;
687 tbDocReferences.AddCell(cell);
688 cell = new PdfPCell(new Phrase(model.DueDt, BigBold));
689 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
690 cell.Border = 0;
691 tbDocReferences.AddCell(cell);
692 }
693 //project name
694 if (!string.IsNullOrEmpty(model.Project) || model.Project=="NONE")
695 {
696 cell = new PdfPCell(new Phrase("Project: ", ArialUniMs));
697 cell.Border = 0;
698 tbDocReferences.AddCell(cell);
699 cell = new PdfPCell(new Phrase(model.Project, BigBold));
700 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
701 cell.Border = 0;
702 tbDocReferences.AddCell(cell);
703 }
704 #endregion
705
706 #region CUSTOMER DETAILS AND REFERENCE NUMBERS. tbCusDtls
707 // second document row...
708 PdfPTable tbCusDtls = new PdfPTable(3);
709 //remove borders
710 tbCusDtls.DefaultCell.Border = Rectangle.NO_BORDER;
711 //actual width of table in points
712 tbCusDtls.TotalWidth = 540f;
713 //fix the absolute width of the table
714 tbCusDtls.LockedWidth = true;
715 colWidths = new float[] { 35f, 20f, 35f };
716 tbCusDtls.SetWidths(colWidths);
717 //leave a gap before and after the table
718 tbCusDtls.SpacingBefore = 10f;
719 tbCusDtls.SpacingAfter = 20f;
720
721 //supplier/customer details
722 tbCusDtls.AddCell(tbCustomer);
723 tbCusDtls.AddCell(" ");
724 //document specs/refs
725 tbCusDtls.AddCell(tbDocReferences);
726
727
728 #endregion
729
730 #region ITEMS TABLE. tbItems
731 //ITEMS TABLE HEADERS
732 PdfPTable tbItems = new PdfPTable(6);
733 colWidths = new float[] { 8f, 15f, 8f, 12f, 12f, 12f };
734 tbItems.SetWidths(colWidths);
735 //actual width of table in points
736 tbItems.TotalWidth = 540f;
737 //fix the absolute width of the table
738 tbItems.LockedWidth = true;
739 tbItems.DefaultCell.Border = Rectangle.TOP_BORDER;
740 tbItems.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
741 //TABLE HEADING
742 cell = new PdfPCell(new Phrase("Item Details", BigBold));
743 cell.Colspan = 7;
744 tbItems.AddCell(cell);
745 //TABLE HEADERS
746 tbItems.AddCell(BGLightGray(NoBdrFntB("#", 1)));
747 tbItems.AddCell(BGLightGray(NoBdrFntB("Item Description", 0)));
748 tbItems.AddCell(BGLightGray(NoBdrFntB("Qty", 2)));
749 tbItems.AddCell(BGLightGray(NoBdrFntB("Unit Price", 2)));
750 tbItems.AddCell(BGLightGray(NoBdrFntB("Tax", 2)));
751 tbItems.AddCell(BGLightGray(NoBdrFntB("Amount", 2)));
752 tbItems.HeaderRows = 1; //adding table header
753
754 //looping through the list of items in model
755 int n = 1;//item counter
756 foreach (PDFItemsModel item in model.PDFItemsList)
757 {
758 tbItems.AddCell(NoBdrFntN(n.ToString(), 1));
759
760 tbItems.AddCell(NoBdrFntN(item.ItemDesc, 0));
761
762 tbItems.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", item.Qty), 2));
763
764 tbItems.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", item.UnitPrice), 2));
765
766 tbItems.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", item.Tax), 2));
767
768 tbItems.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", item.Amount), 2));
769 n++;// increase counter
770 }
771 //Add a line at end of Items
772 cell = new PdfPCell(new Phrase("", normal));
773 cell.Border = Rectangle.BOTTOM_BORDER;
774 cell.BorderWidthTop = 0.5f;
775 cell.BorderColorTop = BaseColor.DARK_GRAY;
776 cell.UseVariableBorders = true;
777 cell.Colspan = 6;
778 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
779 tbItems.AddCell(cell);
780
781 #endregion
782
783 #region PAYMENTS TABLE. pmtTable
784 // ASSIGN THE DIFFERENT TABLE HEADERS
785
786 //ITEMS TABLE HEADERS
787 //Item list table
788 PdfPTable tbPayments = new PdfPTable(7);
789 colWidths = new float[] { 5f, 12f, 10f, 10f, 10f, 10f, 10f };
790 tbPayments.SetWidths(colWidths);
791 tbPayments.SpacingBefore = 20f;
792 tbPayments.TotalWidth = 540f;
793 //fix the absolute width of the table
794 tbPayments.LockedWidth = true;
795 tbPayments.DefaultCell.Border = Rectangle.TOP_BORDER;
796 tbPayments.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
797 //TABLE HEADING
798 cell = new PdfPCell(new Phrase("Payment Details", BigBold));
799 cell.Colspan = 7;
800 tbPayments.AddCell(cell);
801 //TABLE HEADERS
802 tbPayments.AddCell(BGLightGray(NoBdrFntB("#", 0)));
803 tbPayments.AddCell(BGLightGray(NoBdrFntB("Payment Date", 0)));
804 tbPayments.AddCell(BGLightGray(NoBdrFntB("Payment No", 0)));
805 tbPayments.AddCell(BGLightGray(NoBdrFntB("Payment Mode", 0)));
806 tbPayments.AddCell(BGLightGray(NoBdrFntB("Reference", 0)));
807 tbPayments.AddCell(BGLightGray(NoBdrFntB("Amount", 2)));
808 tbPayments.AddCell(BGLightGray(NoBdrFntB("Balance", 2)));
809
810 tbPayments.HeaderRows = 1;
811 n = 1;//item counter
812 foreach (PDFPaymentsModel payment in model.PDFPaymentsList)
813 {
814 tbPayments.AddCell(NoBdrFntN(n.ToString(), 0));
815 tbPayments.AddCell(NoBdrFntN(payment.PayDate, 0));
816 tbPayments.AddCell(NoBdrFntN(payment.RctNo, 0));
817 tbPayments.AddCell(NoBdrFntN(payment.PayMode, 0));
818 tbPayments.AddCell(NoBdrFntN(payment.PayRef, 0));
819 tbPayments.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", payment.Amount), 2));
820 tbPayments.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", payment.Bal), 2));
821
822 n++;
823 }
824
825 //Add a line at end of payments table
826 cell = new PdfPCell(new Phrase("", normal));
827 cell.Border = Rectangle.BOTTOM_BORDER;
828 cell.BorderWidthTop = 0.5f;
829 cell.BorderColorTop = BaseColor.DARK_GRAY;
830 cell.UseVariableBorders = true;
831 cell.Colspan = 7;
832 tbPayments.AddCell(cell);
833 #endregion
834
835 #region DOCUMENT TOTALS. tbTotals
836 // Sales Doc Totals
837 PdfPTable tbTotals = new PdfPTable(6);
838 colWidths = new float[] { 8f, 15f, 8f, 12f, 12f, 12f };
839 tbTotals.SetWidths(colWidths);
840 //actual width of table in points
841 tbTotals.TotalWidth = 540f;
842 //fix the absolute width of the table
843 tbTotals.LockedWidth = true;
844
845 colWidths = new float[] { 12f, 12f, 8f, 12f, 12f, 12f };
846 tbTotals.SetWidths(colWidths);
847
848 //no table borders
849 tbTotals.DefaultCell.Border = Rectangle.NO_BORDER;
850
851 tbTotals.AddCell(NoBdrFntN(" ", 1, 6, 1));
852
853 if(model.TotTax > 0)
854 {
855 tbTotals.AddCell(NoBdrFntN("Amount Before Tax: ", 2, 4, 1));
856
857 tbTotals.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", model.TotBTax), 2, 2, 1));
858
859 tbTotals.AddCell(NoBdrFntN("Tax (18%): ", 2, 4, 1));
860
861 tbTotals.AddCell(NoBdrFntN(string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", model.TotTax), 2, 2, 1));
862 }
863
864 if (model.TotAmt > 0)
865 {
866 tbTotals.AddCell(NoBdrFntN(" ", 2, 3, 1));
867 cell = new PdfPCell(new Phrase("Total Amount:", BigBold));
868 cell.Border = Rectangle.TOP_BORDER;
869 cell.BorderWidthTop = 0.5f;
870 cell.BorderColorTop = BaseColor.DARK_GRAY;
871 cell.UseVariableBorders = true;
872 cell.Colspan = 1;
873 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
874 tbTotals.AddCell(cell);
875 cell = new PdfPCell(new Phrase(model.Currency + ". " + string.Format("{0:#,##0.00;(#,##0.00);'0.00'}", model.TotAmt), BigBold));
876 cell.Border = Rectangle.TOP_BORDER;
877 cell.BorderWidthTop = 0.5f;
878 cell.BorderColorTop = BaseColor.DARK_GRAY;
879 cell.UseVariableBorders = true;
880 cell.Colspan = 2;
881 cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
882 tbTotals.AddCell(cell);
883
884 AmountInWords = Convert.ToInt32(model.TotAmt).ToText();
885 tbTotals.AddCell(NoBdrFntN(AmountInWords + " " + model.Currency + " only.", 2, 12, 1));
886 }
887 #endregion
888
889 #region POPULATE DOCUMENT
890
891 //ROW 1. HEADER IMAGE
892 if (Header == "true")
893 {
894 doc.Add(tbDocHeader);
895 }
896
897 //ROW 1. EMPTY HEADER
898 if (Header == "false")
899 {
900 doc.Add(new Paragraph(""));
901 doc.Add(Chunk.NEWLINE);
902 doc.Add(Chunk.NEWLINE);
903 doc.Add(Chunk.NEWLINE);
904 doc.Add(new Paragraph(""));
905 }
906 //ROW 2. DOC NAME, QR CODE AND COMPANY DTLS
907 doc.Add(tbDocNameQRCode);
908
909 //CUSTOMER DETAILS AND REFERENCE NUMBERS
910 doc.Add(tbCusDtls);
911
912 //ITEMS
913 if (model.PDFItemsList.Count > 0)
914 {
915 doc.Add(tbItems);
916 }
917
918 //TOTALS
919 doc.Add(tbTotals);
920
921 //PRINT NOTES
922 doc.Add(new Paragraph("Note:", BigBold));
923 doc.Add(new Paragraph(Line1, ArialUniMs));
924 doc.Add(new Paragraph(Line2, ArialUniMs));
925 doc.Add(new Paragraph(Line3, ArialUniMs));
926 doc.Add(new Paragraph(Line4, ArialUniMs));
927 doc.Add(new Paragraph(Line5, BigBold));
928 doc.Add(new Paragraph(""));
929 doc.Add(Chunk.NEWLINE);
930 doc.Add(new Paragraph(""));
931
932 //SIGNATURE
933 PdfPTable tbSign = new PdfPTable(6);
934 colWidths = new float[] { 8f, 15f, 8f, 12f, 12f, 12f };
935 tbSign.SetWidths(colWidths);
936 tbSign.TotalWidth = 540f;
937 tbSign.LockedWidth = true;
938
939 if (Signitory == "true")
940 {
941 tbSign.AddCell(NoBdrFntN("", 2, 2, 1));
942 tbSign.AddCell(NoBdrFntN("Name:_____________________________________", 2, 4, 1));
943 }
944 if (Sign == "true")
945 {
946 tbSign.AddCell(NoBdrFntN("", 2, 2, 1));
947 tbSign.AddCell(NoBdrFntN("Sign/Date:_____________________________________", 2, 4, 1));
948
949 tbSign.AddCell(NoBdrFntN("", 2, 2, 1));
950 tbSign.AddCell(NoBdrFntN("For " + CoName, 2, 4, 1));
951 }
952 doc.Add(tbSign);
953
954 //PAYMENTS
955 if (PayHistory == "true")
956 {
957 if (model.PDFPaymentsList.Count > 0)
958 {
959 doc.Add(tbPayments);
960 }
961 }
962 //FINALLY... CLOSE DOC, CLEAN UP THE USED SESSIONS AND REDIRECT TO APPROPRIATE PAGE
963 doc.Close();
964
965 //CLEAR PdfModel SESSION
966 Session["PdfModel"] = null;
967
968 //OPEN DOCUMENT
969 return RedirectToAction("PrintFile", new { DocName = model.DocName, RefNo = model.DocRef });
970
971 #endregion
972 }
973 catch (Exception e)
974 {
975 Console.WriteLine("{0} Exception caught", e.Message);
976 throw e;
977 }
978 }
979
980 public ActionResult PrintFile(string DocName, string RefNo)
981 {
982 try
983 {
984 DocName = DocName.ToUpper();
985 // get the path to the pdf folder
986 string pdfFolderPath = Server.MapPath(Url.Content("~/PDF")); //Server.MapPath(DocName + "PDFs");
987
988 // name of the folder to which the file is to be saved
989 string docFolder = DocName + "PDFs";
990
991 // get the document name
992 string fileName = RefNo + ".pdf";
993
994 // name of the folder to which the file is to be saved
995 string docFolderPath = Path.Combine(pdfFolderPath, docFolder);
996
997 // create folder if it doesn't exit
998 Directory.CreateDirectory(docFolderPath);
999
1000 // name of the folder to which the file is to be saved
1001 string filePath = Path.Combine(pdfFolderPath, docFolder, fileName);
1002
1003 var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
1004
1005 var fsResult = new FileStreamResult(fileStream, "application/pdf");
1006
1007 string disposition = new ContentDisposition { FileName = fileName, Inline = true }.ToString();
1008
1009 Response.AppendHeader("Content-Disposition", disposition);
1010
1011 return fsResult;
1012 }
1013 catch (Exception e)
1014 {
1015 Console.WriteLine("{0} Exception caught", e.Message);
1016 throw e;
1017 }
1018 }
1019 //if the document is not available, get information necessary to create it
1020 public ActionResult GetDocDetails(string DocName, string RefNo)
1021 {
1022 if (DocName == "QUOTATION")
1023 {
1024 return RedirectToAction("GetQItemsByQNO", "Sales", new { QNo = RefNo, CreatePDF = "QUOTATION" });
1025 }
1026 else if (DocName == "INVOICE")
1027 {
1028 return RedirectToAction("GetInvoiceItemsByINVNO", "Sales", new { INVNO = RefNo, CreatePDF = "INVOICE" });
1029 }
1030 else if (DocName == "RECEIPT")
1031 {
1032 return RedirectToAction("GetRctDetailsByRctNO", "Sales", new { RecNO = RefNo, CreatePDF = "RECEIPT" });
1033 }
1034 else if (DocName == "PO")
1035 {
1036 return RedirectToAction("GetPOItemsByPONO", "Purchases", new { PONO = RefNo, CreatePDF = "PO" });
1037 }
1038 else if (DocName == "BILL")
1039 {
1040 return RedirectToAction("GetBillItemsByBilNo", "Purchases", new { BilNo = RefNo, CreatePDF = "BILL" });
1041 }
1042 else if (DocName == "PAYMENT")
1043 {
1044 return RedirectToAction("GetPayByPayNO", "Purchases", new { PayNO = RefNo, CreatePDF = "PAYMENT" });
1045 }
1046 else if (DocName == "INVRECEIPT")
1047 {
1048 return RedirectToAction("GetRctDetailsByRctNO", "Sales", new { RecNO = RefNo, CreatePDF = "INVRECEIPT" });
1049 }
1050 else if (DocName == "ADVANCE")
1051 {
1052 return RedirectToAction("GetAdvancePmt", "Payments", new { MYID = RefNo, CreatePDF = "ADVANCE" });
1053 }
1054 else if (DocName == "DEPOSIT")
1055 {
1056 return RedirectToAction("GetDepositPmt", "Payments", new { MYID = RefNo, CreatePDF = "DEPOSIT" });
1057 }
1058 return View("FileNotFound");
1059 }
1060 }
1061}