· 6 years ago · Nov 08, 2019, 07:40 PM
1using iText.Barcodes;
2using iText.Kernel.Colors;
3using iText.Kernel.Font;
4using iText.Kernel.Geom;
5using iText.Kernel.Pdf;
6using iText.Kernel.Pdf.Action;
7using iText.Kernel.Pdf.Annot;
8using iText.Kernel.Pdf.Canvas;
9using iText.Kernel.Pdf.Xobject;
10using iText.Kernel.Utils;
11using iText.Layout;
12using iText.Layout.Element;
13using iText.Layout.Properties;
14using Newtonsoft.Json;
15//using org.pdfclown.documents.contents.composition;
16//using org.pdfclown.documents.contents.entities;
17//using org.pdfclown.documents.interaction.annotations;
18using System;
19using System.Collections.Generic;
20using System.IO;
21using System.Linq;
22using System.Threading.Tasks.Dataflow;
23
24namespace AlchemeEngineering
25{
26 public class Engineering
27 {
28 public class EngineerConfig
29 {
30 public int scale { get; set; }
31 public string editorWidth { get; set; }
32 public string pageCount { get; set; }
33 public List<Racami.Common.pages> pages { get; set; }
34
35 public String Path { get; set; }
36
37
38 public Racami.Common.Workflow Workflow { get; set; }
39 }
40
41
42 public class XmlBlock
43 {
44 public System.Xml.XmlNode node { get; set; }
45 public int Objectid { get; set; }
46 }
47
48
49 public class FontFamilyStage
50 {
51 public System.Drawing.FontFamily Family { get; set; }
52 public String FontName { get; set; }
53 public byte[] FontBytes { get; set; }
54 public String FamilyName { get; set; }
55 }
56
57
58 public static System.Drawing.FontFamily LoadFontFamily(byte[] buffer)
59 {
60 var handle = System.Runtime.InteropServices.GCHandle.Alloc(buffer, System.Runtime.InteropServices.GCHandleType.Pinned);
61 try
62 {
63 var ptr = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
64 using (var pvc = new System.Drawing.Text.PrivateFontCollection())
65 {
66
67 pvc.AddMemoryFont(ptr, buffer.Length);
68 return pvc.Families[0];
69 }
70 }
71 finally
72 {
73 handle.Free();
74 }
75 }
76
77 public List<FontFamilyStage> LoadFontFamilies()
78 {
79
80 List<FontFamilyStage> fontDic = new List<FontFamilyStage>();
81 System.Reflection.Assembly _assembly = System.Reflection.Assembly.GetExecutingAssembly();
82 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Load fonts");
83
84 // foreach (org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum fontFamily
85 //in (org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum[])Enum.GetValues(typeof(org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum)))
86 // {
87 // if (fontFamily != org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum.Symbol
88 // && fontFamily != org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum.ZapfDingbats
89 // && fontFamily != org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum.NA)
90 // fontDic.Add(new FontFamilyStage() { Family = null, FamilyName = fontFamily.ToString(), FontName = fontFamily.ToString(), FontBytes = null });
91 // }
92
93 string Fontxmlpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\fonts\fonts.xml";
94
95 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(Fontxmlpath);
96 try
97 {
98 //fontDic.Add(new FontFamily() { Name = "Segoesc", FontType = @"font\segoesc.ttf" });
99 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
100 doc.Load(Fontxmlpath);
101
102 foreach (System.Xml.XmlNode node in doc.DocumentElement.SelectNodes("/fonts/font"))
103 {
104 string fontpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\fonts\" + node.SelectSingleNode("location").InnerText;
105 if (!System.IO.File.Exists(fontpath))
106 continue;
107 byte[] buffer = System.IO.File.ReadAllBytes(fontpath);
108 //fontDic.Add(new FontFamily() { Name = node.SelectSingleNode("name").InnerText, FontType = node.SelectSingleNode("location").InnerText });
109 System.Drawing.FontFamily fam = LoadFontFamily(buffer);
110 fontDic.Add(new FontFamilyStage() { Family = fam, FamilyName = fam.Name, FontName = System.IO.Path.GetFileNameWithoutExtension(fontpath.Replace("AlchemeEngineering.Engineering.fonts.", "")), FontBytes = buffer });
111 }
112 }
113 catch (Exception ex)
114 {
115 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(ex.Message);
116 // System.IO.File.WriteAllText(logPath + @"\FontError.txt", ex.ToString());
117 }
118
119 foreach (string resourceName in _assembly.GetManifestResourceNames())
120 {
121 try
122 {
123 System.Diagnostics.Trace.WriteLine(resourceName);
124 System.IO.Stream _imageStream = _assembly.GetManifestResourceStream(resourceName);
125 var buffer = new byte[_imageStream.Length];
126 _imageStream.Read(buffer, 0, buffer.Length);
127 System.Drawing.FontFamily fam = LoadFontFamily(buffer);
128
129 fontDic.Add(new FontFamilyStage() { Family = fam, FamilyName = fam.Name, FontName = System.IO.Path.GetFileNameWithoutExtension(resourceName.Replace("AlchemeEngineering.Engineering.fonts.", "")), FontBytes = buffer });
130 }
131 catch (Exception ex)
132 {
133 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(ex.Message);
134 // System.IO.File.WriteAllText(logPath + @"\FontError.txt", ex.ToString());
135 }
136 }
137
138 //List<FontFamilyStage> fontDic = new List<FontFamilyStage>();
139
140 return fontDic;
141 }
142
143
144 public class TextPositions
145 {
146 public float X { get; set; }
147 public float Y { get; set; }
148 public float Width { get; set; }
149 public float Height { get; set; }
150 public string Name { get; set; }
151 public DeviceRgb Color { get; set; }
152 // public org.pdfclown.documents.contents.colorSpaces.DeviceRGBColor Color { get; set; }
153 public int Rotation { get; set; }
154 public List<FontFamilyStage> Fonts { get; set; }
155 public string fontstyle { get; set; }
156 public string fontweight { get; set; }
157
158 }
159
160
161
162 public System.Xml.XmlNode MakeXmlChanges(System.Data.DataRow Row, System.Data.DataTable table, string Option)
163 {
164 var node = String.IsNullOrEmpty(Row["XmlData"].ToString()) ? "<Details></Details>" : Row["XmlData"];
165 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
166 doc.LoadXml(node.ToString());
167 if (doc.DocumentElement.Name != "Details")
168 {
169 System.Xml.XmlNode newnode = doc.CreateNode(System.Xml.XmlNodeType.Element, "Details", "");
170
171 newnode.AppendChild(doc.DocumentElement);
172 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Do new work");
173 System.Xml.XmlNode pdfnode = doc.CreateElement("PDF");
174 System.Xml.XmlElement originalnode = doc.CreateElement("Original");
175 originalnode.SetAttribute("StartPage", table.Columns.Contains("start_page") ? Row["start_page"].ToString() : Row["StartPage"].ToString());
176 originalnode.SetAttribute("Endpage", table.Columns.Contains("endt_page") ? Row["end_page"].ToString() : Row["EndPage"].ToString());
177 pdfnode.AppendChild(originalnode);
178
179 System.Xml.XmlElement currentnode = doc.CreateElement("Current");
180 currentnode.SetAttribute("Level", Option == "Job" ? "Job" : "Detail");
181 currentnode.SetAttribute("StartPage", table.Columns.Contains("start_page") ? Row["start_page"].ToString() : Row["StartPage"].ToString());
182 currentnode.SetAttribute("Endpage", table.Columns.Contains("endt_page") ? Row["end_page"].ToString() : Row["EndPage"].ToString());
183 pdfnode.AppendChild(originalnode);
184
185 newnode.AppendChild(pdfnode);
186 doc.AppendChild(newnode);
187 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Add new entry and get ready for process");
188 }
189
190 int temppage = Convert.ToInt32(table.Columns.Contains("start_page") ? Row["start_page"] : Row["StartPage"]);
191
192 int Startpage = Convert.ToInt32(table.Columns.Contains("start_page") ? Row["start_page"] : Row["StartPage"]);
193
194 var nodesto = doc.DocumentElement.SelectNodes("PDF/Original");
195 if (nodesto.Count == 0)
196 {
197 nodesto = doc.DocumentElement.SelectNodes("PDF");
198 if (nodesto.Count == 0)
199 {
200 System.Xml.XmlNode pdfnode = doc.CreateElement("PDF");
201 System.Xml.XmlElement originalnode = doc.CreateElement("Original");
202 originalnode.SetAttribute("StartPage", table.Columns.Contains("start_page") ? Row["start_page"].ToString() : Row["StartPage"].ToString());
203 originalnode.SetAttribute("Endpage", table.Columns.Contains("endt_page") ? Row["end_page"].ToString() : Row["EndPage"].ToString());
204
205 System.Xml.XmlElement currentnode = doc.CreateElement("Current");
206 currentnode.SetAttribute("Level", Option == "Job" ? "Job" : "Detail");
207 currentnode.SetAttribute("StartPage", table.Columns.Contains("start_page") ? Row["start_page"].ToString() : Row["StartPage"].ToString());
208 currentnode.SetAttribute("Endpage", table.Columns.Contains("endt_page") ? Row["end_page"].ToString() : Row["EndPage"].ToString());
209 pdfnode.AppendChild(currentnode);
210
211 pdfnode.AppendChild(originalnode);
212 doc.DocumentElement.AppendChild(pdfnode);
213 }
214 }
215 else
216 {
217 int oristartpage = Convert.ToInt32(nodesto[0].Attributes["StartPage"].InnerText);
218 var currentpagelevel = doc.DocumentElement.SelectSingleNode(Option == "Job" ? "PDF/Current[@Level='Job']" : "PDF/Current[@Level='Detail']") == null ?
219 doc.DocumentElement.SelectSingleNode("PDF/Current") == null ? doc.DocumentElement.SelectSingleNode("PDF") : doc.DocumentElement.SelectSingleNode("PDF/Current")
220 : doc.DocumentElement.SelectSingleNode(Option == "Job" ? "PDF/Current[@Level='Job']" : "PDF/Current[@Level='Detail']");
221
222 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Entry point to the xml is " + currentpagelevel.Name);
223 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info("Entry point to the xml is " + currentpagelevel.InnerXml);
224 if (currentpagelevel.Name == "PDF")
225 {
226 System.Xml.XmlElement currentnode = doc.CreateElement("Current");
227 currentnode.SetAttribute("Level", Option == "Job" ? "Job" : "Detail");
228 currentnode.SetAttribute("StartPage", table.Columns.Contains("start_page") ? Row["start_page"].ToString() : Row["StartPage"].ToString());
229 currentnode.SetAttribute("Endpage", table.Columns.Contains("endt_page") ? Row["end_page"].ToString() : Row["EndPage"].ToString());
230 currentpagelevel.AppendChild(currentnode);
231
232 }
233 else
234 {
235 string level = Option == "Job" ? "Job" : "Detail";
236 if (currentpagelevel.Attributes["Level"].Value != level)
237 {
238 System.Xml.XmlElement currentnode = doc.CreateElement("Current");
239 currentnode.SetAttribute("Level", Option == "Job" ? "Job" : "Detail");
240 currentnode.SetAttribute("StartPage", table.Columns.Contains("start_page") ? Row["start_page"].ToString() : Row["StartPage"].ToString());
241 currentnode.SetAttribute("Endpage", table.Columns.Contains("endt_page") ? Row["end_page"].ToString() : Row["EndPage"].ToString());
242 doc.DocumentElement.SelectSingleNode("PDF").AppendChild(currentnode);
243 }
244
245 }
246 //else if (currentpagelevel.Name == "Current")
247 //{
248 // // if (String.IsNullOrEmpty(currentpagelevel.InnerXml))
249 // // {
250 // ((System.Xml.XmlElement)currentpagelevel).SetAttribute("Level", cisobject.Options == null ? "Job" : "Detail");
251 // ((System.Xml.XmlElement)currentpagelevel).SetAttribute("StartPage", cisobject.NewRecordDetails.Columns.Contains("start_page") ? Row["start_page"].ToString() : Row["StartPage"].ToString());
252 // ((System.Xml.XmlElement)currentpagelevel).SetAttribute("Endpage", cisobject.NewRecordDetails.Columns.Contains("endt_page") ? Row["end_page"].ToString() : Row["EndPage"].ToString());
253 // // currentpagelevel.AppendChild(currentnode);
254
255
256 //}
257
258 }
259 return doc;
260
261 }
262
263 public bool IsOdd(int value)
264 {
265 return value % 2 != 0;
266 }
267
268 List<TextPositions> textpositions = new List<TextPositions>();
269
270
271 public System.Data.DataTable RemoveDuplicateRows(System.Data.DataTable dTable, string colName)
272 {
273 System.Collections.Hashtable hTable = new System.Collections.Hashtable();
274 System.Collections.ArrayList duplicateList = new System.Collections.ArrayList();
275
276 //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
277 //And add duplicate item value in arraylist.
278 foreach (System.Data.DataRow drow in dTable.Rows)
279 {
280 if (hTable.Contains(drow[colName]))
281 duplicateList.Add(drow);
282 else
283 hTable.Add(drow[colName], string.Empty);
284 }
285
286 //Removing a list of duplicate items from datatable.
287 foreach (System.Data.DataRow dRow in duplicateList)
288 dTable.Rows.Remove(dRow);
289
290 //Datatable which contains unique records will be return as output.
291 return dTable;
292 }
293
294
295 public System.Data.DataRow[] RemoveDuplicateRows(List<System.Data.DataRow> rRows, string colName)
296 {
297 System.Collections.Hashtable hTable = new System.Collections.Hashtable();
298 System.Collections.ArrayList duplicateList = new System.Collections.ArrayList();
299
300 //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
301 //And add duplicate item value in arraylist.
302 foreach (System.Data.DataRow drow in rRows)
303 {
304 if (hTable.Contains(drow[colName]))
305 duplicateList.Add(drow);
306 else
307 hTable.Add(drow[colName], string.Empty);
308 }
309
310 //Removing a list of duplicate items from datatable.
311 foreach (System.Data.DataRow dRow in duplicateList)
312 rRows.Remove(dRow);
313
314 //Datatable which contains unique records will be return as output.
315 return rRows.ToArray();
316 }
317
318 int RECSTART = 1;
319 int RECCOUNT = 1;
320 int RECPAGECOUNT = 1;
321
322 int CURRENTDOC = 0;
323 int DOCCOUNT = 1;
324 int HOUSEHOLDPAGE = 0;
325 int HOUSEHOLDODDPAGE = 0;
326 int HOUSEHOLDEVENPAGE = 0;
327
328 public class FileManip
329 {
330
331 public static void CopyTime(string source, string destination)
332 {
333 DateTime start_time = DateTime.Now;
334 FCopy(source, destination);
335 long size = new FileInfo(destination).Length;
336 int milliseconds = 1 + (int)((DateTime.Now - start_time).TotalMilliseconds);
337 // size time in milliseconds per hour
338 long tsize = size * 3600000 / milliseconds;
339 tsize = tsize / (int)Math.Pow(2, 30);
340 Console.WriteLine(tsize + "GB/hour");
341 }
342
343 public static void MoveTime(string source, string destination)
344 {
345 DateTime start_time = DateTime.Now;
346 FMove(source, destination);
347 long size = new FileInfo(destination).Length;
348 int milliseconds = 1 + (int)((DateTime.Now - start_time).TotalMilliseconds);
349 // size time in milliseconds per hour
350 long tsize = size * 3600000 / milliseconds;
351 tsize = tsize / (int)Math.Pow(2, 30);
352 Console.WriteLine(tsize + "GB/hour");
353 }
354
355 /// <summary> Fast file move with big buffers
356 /// </summary>
357 /// <param name="source">Source file path</param>
358 /// <param name="destination">Destination file path</param>
359 static void FMove(string source, string destination)
360 {
361 int array_length = (int)Math.Pow(2, 19);
362 byte[] dataArray = new byte[array_length];
363 using (FileStream fsread = new FileStream
364 (source, FileMode.Open, FileAccess.Read, FileShare.None, array_length))
365 {
366 using (BinaryReader bwread = new BinaryReader(fsread))
367 {
368 using (FileStream fswrite = new FileStream
369 (destination, FileMode.Create, FileAccess.Write, FileShare.None, array_length))
370 {
371 using (BinaryWriter bwwrite = new BinaryWriter(fswrite))
372 {
373 for (; ; )
374 {
375 int read = bwread.Read(dataArray, 0, array_length);
376 if (0 == read)
377 break;
378 bwwrite.Write(dataArray, 0, read);
379 }
380 }
381 }
382 }
383 }
384 File.Delete(source);
385 }
386
387
388 /// <summary> Fast file move with big buffers
389 /// </summary>
390 /// <param name="source">Source file path</param>
391 /// <param name="destination">Destination file path</param>
392 static void FCopy(string source, string destination)
393 {
394 int array_length = (int)Math.Pow(2, 19);
395 byte[] dataArray = new byte[array_length];
396 using (FileStream fsread = new FileStream
397 (source, FileMode.Open, FileAccess.Read, FileShare.None, array_length))
398 {
399 using (BinaryReader bwread = new BinaryReader(fsread))
400 {
401 using (FileStream fswrite = new FileStream
402 (destination, FileMode.Create, FileAccess.Write, FileShare.None, array_length))
403 {
404 using (BinaryWriter bwwrite = new BinaryWriter(fswrite))
405 {
406 for (; ; )
407 {
408 int read = bwread.Read(dataArray, 0, array_length);
409 if (0 == read)
410 break;
411 bwwrite.Write(dataArray, 0, read);
412 }
413 }
414 }
415 }
416 }
417 // File.Delete(source);
418 }
419 }
420
421 class EngineeringData
422 {
423
424 }
425
426
427 public string[] ExecuteCommandline(string[] Parameters)
428 {
429 try
430 {
431 System.Diagnostics.Process proc = new System.Diagnostics.Process();
432 string filename = Parameters[0];//PATH
433 string cParams = String.Empty;
434
435 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("Executable File: ={0}=", filename));
436
437 if (!System.IO.File.Exists(filename))
438 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(filename + " does not exist");
439
440
441
442
443
444
445 if (!String.IsNullOrEmpty(Parameters[1]))
446 cParams = string.Format(Parameters[1]);//argument
447
448 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("Parameter to Run: ={0}=", cParams));
449
450
451 proc.StartInfo.FileName = filename;
452 proc.StartInfo.Arguments = cParams;//argument
453 proc.StartInfo.UseShellExecute = false;
454 proc.StartInfo.RedirectStandardOutput = true;
455 proc.StartInfo.RedirectStandardError = true;
456 proc.Start();
457
458 //
459 // Read in all the text from the process with the StreamReader.
460 //
461 string output;
462 using (System.IO.StreamReader reader = proc.StandardOutput)
463 {
464 output = reader.ReadToEnd();
465 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(output);
466 }
467
468
469 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("executing");
470 proc.WaitForExit();
471 string[] result = new string[] { output, proc.ExitCode.ToString() };
472
473 if (proc.ExitCode < 0)
474 {
475 throw new Exception(output);
476 }
477
478 proc.Close();
479 proc.Dispose();
480 return result;
481 }
482 catch (Exception e)
483 {
484 throw new Exception(e.Message);
485 }
486 }
487
488 public class PDfMeta
489 {
490 public System.Data.DataRow Row { get; set; }
491 public PdfPage Page { get; set; }
492 // org.pdfclown.documents.Page Page { get; set; }
493 public int Index { get; set; }
494
495 }
496
497 List<FontFamilyStage> fontDic = null;
498 public class RowData
499 {
500 public int index { get; set; }
501 public System.Data.DataRow Row { get; set; }
502 }
503
504 class PDFLoctions
505 {
506
507 public class Markers
508 {
509 // public ObjectTextRender Marker { get; set; }
510 }
511 public PDFLoctions()
512 {
513 IsBlank = true;
514 render = new Markers();
515 }
516 public void Dispose()
517 {
518
519
520
521 if (this.Image != null)
522 {
523 this.Image.Dispose();
524 // this.Image = null;
525 }
526
527 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Delete temp file. Temp Filename: {tempfile}");
528
529 try
530 {
531 if (System.IO.File.Exists(this.FilePath))
532 System.IO.File.Delete(this.FilePath);
533 }
534 catch (Exception ioex)
535 {
536 //putting try catch here as IC group is running into some weird issues where sometimes it errors out with message cannot access file being used by another process
537 //2019-07-18
538 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Delete temp file Temp Filename: {tempfile} failed: {ioex.Message}");
539 }
540 }
541
542 public System.Data.DataRow Row { get; set; }
543 public System.Drawing.Image GetImage()
544 {
545
546 //MemoryStream stream = new MemoryStream();
547 //PdfDocument pdf = new PdfDocument(new PdfWriter(stream));
548 //document.CopyPagesTo(PageNumber, PageNumber, pdf);
549 //pdf.Close();
550
551
552 //Irondocument = new IronPdf.PdfDocument(stream.GetBuffer());
553 // System.Drawing.Image retimage = Irondocument.ToBitmap(PageNumber)[0];
554
555
556 //spirepdfdocument = new Spire.Pdf.PdfDocument();
557 //spirepdfdocument.LoadFromBytes(stream.GetBuffer());
558 //System.Drawing.Image retimage = spirepdfdocument.SaveAsImage(0);
559 //spirepdfdocument.Close();
560 //this.pdfRasterizer.Load(stream);
561 //pdfRasterizer.EndPageNumber = 1;
562 //pdfRasterizer.StartPageNumber = 1;
563 //System.Drawing.Image retimage = pdfRasterizer.ConvertToImages()[0];
564
565 System.Drawing.Image retimage = System.Drawing.Image.FromFile(this.FilePath);
566 // System.Drawing.Image retimage = _rasterizer?.GetPage(300, 300, 1);
567 // this._rasterizer.Close();
568 return retimage;
569 }
570 public String FilePath { get; set; }
571
572 public System.Drawing.Image Image { get; set; }
573 public Markers render { get; set; }
574 // public List<tablenames> tables { get; set; }
575 public PdfPage page { get; set; }
576 // public FilteredEventListener listener { get; set; }
577 public PdfDocument document { get; set; }
578 public int PageNumber { get; set; }
579 public int OrgPageNumber { get; set; }
580 // public IndexResults dtResult { get; set; }
581 public bool IsBlank { get; set; }
582 public string TempRastfile { get; set; }
583 public int StartPage { get; set; }
584 public int EndPage { get; set; }
585 public PdfPage PdfPage { get; set; }
586
587 public void Process()
588 {
589
590
591 }
592
593
594 }
595
596
597
598 public class PDFMapping
599 {
600 public PDFMapping()
601 {
602 mappings = new List<Mapping>();
603 }
604
605 public List<Mapping> mappings { get; set; }
606
607 public class Mapping
608 {
609 public Mapping()
610 {
611 PageMappings = new List<PageMapping>();
612 Pages = new List<int>();
613 }
614 public string PDFFile { get; set; }
615 public string Rasterfile { get; set; }
616 public List<PageMapping> PageMappings { get; set; }
617 public PdfDocument pdfDocument { get; set; }
618 public List<int> Pages { get; set; }
619 // public Patagames.Pdf.Net.PdfDocument pdfium { get; set; }
620 // public Ghostscript.NET.Rasterizer.GhostscriptRasterizer _rasterizer { get; set; }
621 // public SelectPdf.PdfRasterizer pdfRasterizer { get; set; }
622 //public void BuildRaster()
623 //{
624 // string rasterfilename = Guid.NewGuid().ToString();
625 // this.Rasterfile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), rasterfilename + $".raster");
626
627 // PdfWriter rasterwriter = new PdfWriter(Rasterfile);
628 // rasterwriter.SetSmartMode(true);
629 // PdfDocument rasterwritedoc = new PdfDocument(rasterwriter);
630 // pdfDocument.CopyPagesTo(1, pdfDocument.GetNumberOfPages(), rasterwritedoc);
631 // rasterwritedoc.Close();
632 // // pdfium = Patagames.Pdf.Net.PdfDocument.Load(Rasterfile);
633 // this.pdfRasterizer = new SelectPdf.PdfRasterizer();
634 // this.pdfRasterizer.Load(Rasterfile);
635 // // _rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer();
636 // // _rasterizer.Open(Rasterfile);
637 //}
638 public class PageMapping
639 {
640 public PageMapping()
641 {
642 Row = null;
643 //PdfDocument = new PdfDocument(new PdfReader(new MemoryStream()));
644 }
645 public System.Data.DataRow Row { get; set; }
646 public int Orgpagenumber { get; set; }
647 public int Mappedpagenumber { get; set; }
648 public PdfPage PdfPage { get; set; }
649 public PdfDocument PdfDocument { get; set; }
650 }
651 }
652 }
653
654
655 public void DoMapping(PdfDocument document, PDFMapping pDFMapping, List<System.Data.DataRow> rows, PdfDocument mwritedoc)
656 {
657 int filecnt = 0;
658 string filename = Guid.NewGuid().ToString();
659 string rasterfile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), filename + $"_{filecnt}.engineer");
660 int splitcnt = 1;
661 PDFMapping.Mapping mapping = new PDFMapping.Mapping();
662 mapping.PDFFile = rasterfile;
663 PdfWriter writer = new PdfWriter(rasterfile);
664 writer.SetSmartMode(true);
665 PdfDocument writedoc = new PdfDocument(writer);
666
667 try
668 {
669 for (int i = 0; i < rows.Count; i++)
670 {
671 System.Data.DataRow dataRow = rows[i];
672 int startpage = Convert.ToInt32(dataRow["StartPage"]);
673 if (splitcnt >= 70000)
674 {
675
676
677 mapping.pdfDocument = writedoc;// new PdfDocument(new PdfReader(rasterfile));
678 // mapping.pdfDocument = new PdfDocument(new PdfReader(mapping.PDFFile), new PdfWriter(mapping.PDFFile + "wr"));
679 pDFMapping.mappings.Add(mapping);
680 // document.CopyPagesTo(pages, writedoc);
681 splitcnt = 1;
682 filecnt++;
683 rasterfile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), filename + $"_{filecnt}.engineer");
684 mapping = new PDFMapping.Mapping();
685 mapping.PDFFile = rasterfile;
686 writer = new PdfWriter(rasterfile);
687 writer.SetSmartMode(true);
688 writedoc = new PdfDocument(writer);
689 }
690
691 mapping.Pages.Add(startpage);
692 mapping.PageMappings.Add(new PDFMapping.Mapping.PageMapping() { Orgpagenumber = (int)startpage, Mappedpagenumber = splitcnt, Row = dataRow });
693 splitcnt++;
694 // pages.Add(startpage);
695 for (int pag = (int)startpage + 1; pag < Convert.ToInt32(dataRow["EndPage"]) + 1; pag++)
696 {
697 // document.CopyPagesTo((int)pag, (int)pag, writedoc);
698 //pages.Add(pag);
699 PDFMapping.Mapping.PageMapping pmapping = new PDFMapping.Mapping.PageMapping() { Orgpagenumber = pag, Mappedpagenumber = splitcnt, Row = null };
700 mapping.Pages.Add(pag);
701 mapping.PageMappings.Add(pmapping);
702 splitcnt++;
703 }
704
705 // document.CopyPagesTo((int)startpage, Convert.ToInt32(dataRow["EndPage"]), writedoc);
706 // mapping.pdfDocument.FlushCopiedObjects(document);
707 // splitcnt++;
708 }
709 }
710 catch (Exception ex)
711 {
712 Console.WriteLine("TT");
713 }
714
715
716 mapping.pdfDocument = writedoc;
717 pDFMapping.mappings.Add(mapping);
718 Console.Write("Parse");
719
720 pDFMapping.mappings.ForEach(map =>
721 {
722
723 Console.WriteLine("Add pages");
724 document.CopyPagesTo(map.Pages, map.pdfDocument);
725 // map.pdfDocument.FlushCopiedObjects(document);
726 // map.pdfDocument.Close();
727 });
728 Console.Write("Parse");
729 // List<int> pages = new List<int>();
730 //for (int i = 1; i < document.GetNumberOfPages() + 1; i++)
731 //{
732 // if (splitcnt == 40000)
733 // {
734
735 // writedoc.SetFlushUnusedObjects(true);
736 // writedoc.Close();
737 // // mapping.pdfDocument = writedoc;// new PdfDocument(new PdfReader(rasterfile));
738 // pDFMapping.mappings.Add(mapping);
739 // splitcnt = 1;
740 // filecnt++;
741 // rasterfile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), filename + $"_{filecnt}.engineer");
742 // mapping = new PDFMapping.Mapping();
743 // mapping.PDFFile = rasterfile;
744 // writer = new PdfWriter(rasterfile);
745 // writer.SetSmartMode(true);
746 // writedoc = new PdfDocument(writer);
747
748 // }
749 // //PdfPage page = document.GetPage(i);//.CopyPagesTo(i, i, writedoc);
750 // //page.CopyTo(writedoc);
751 // ////page?.Flush();
752 // //Console.Write(".");
753 // document.CopyPagesTo(i, i, writedoc);
754 // // System.Data.DataRow dataRow = rows.Find(mast => mast["StartPage"].ToString() == i.ToString());
755 // // mapping.PageMappings.Add(new PDFMapping.Mapping.PageMapping() { Orgpagenumber = i, Mappedpagenumber = splitcnt, Row = dataRow });
756 // // if (dataRow != null)
757 // // rows.Remove(dataRow);
758 // splitcnt++;
759 //}
760
761
762 }
763 public void DoEngineering(System.Data.DataTable dt, String filepath, string pathofjson, string Option, String ConnectionString, EngineObject.CISObjects CISObject)
764 {
765
766
767 fontDic = LoadFontFamilies();
768 List<XmlBlock> nodes = new List<XmlBlock>();
769
770 //load the record details here
771 if (string.IsNullOrEmpty(pathofjson))
772 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Json path is empty");
773
774 //need to know how and where to pull this data
775 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(String.Format("engineering json path {0}", pathofjson));
776 string JsonString = System.IO.File.ReadAllText(pathofjson);
777 var jsonResult = JsonConvert.DeserializeObject(JsonString);
778 EngineerConfig config = JsonConvert.DeserializeObject<EngineerConfig>(JsonString);
779
780 if (EngineObject.CISObjects.MasterLog != null) if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(String.Format("engineering json path {0}", pathofjson));
781 List<Racami.Common.pages> pages = new List<Racami.Common.pages>();
782 config?.pages?.ForEach(p =>
783 {
784 //if (p.isAdded)
785 // pages.Add(p);
786 if (p?.texts?.Count > 0 || p?.variables?.Count > 0 ||
787 p?.shapes?.Count > 0 || p?.masks?.Count > 0 || p?.customTexts?.Count > 0 || p?.links?.Count > 0 || p.isAdded)
788 pages.Add(p);
789
790
791 });
792 config?.Workflow?.pages?.ForEach(p =>
793 {
794 //if (p.isAdded)
795 // pages.Add(p);
796 if (p?.texts?.Count > 0 || p?.variables?.Count > 0 ||
797 p?.shapes?.Count > 0 || p?.masks?.Count > 0 || p?.customTexts?.Count > 0 || p?.links?.Count > 0 || p.isAdded)
798 pages.Add(p);
799
800
801 });
802 if (System.IO.Path.GetExtension(filepath).ToLower() != ".pdf")
803 throw new Exception("This process is designed for pdf only!!");
804 //copy the pdf to the local drive of the machine doing the processing
805
806 string tempfile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid() + ".pdf");
807 //copy the file to the server
808 FileManip.CopyTime(filepath, tempfile);
809
810 //ExecuteCommandline(new string[] { $"{System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\qpdf\\qpdf.exe"}", $" --object-streams=disable {"\"" + filepath + "\""} {"\"" + tempfile + "\""}" });
811
812 if (!System.IO.File.Exists(tempfile))
813 throw new Exception($"process of file {filepath} did not transfer to the temp directory.. FATAL");
814
815 //if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(String.Format("File for engineering is {0}", filepath));
816
817
818 //we need to segment the file here..
819
820 PdfDocument document = new PdfDocument(new PdfReader(tempfile));
821 long Totalpages = document.GetNumberOfPages();
822
823
824 // PdfWriter outputpdfWriter = new PdfWriter(tempfile + "mk");
825 // outputpdfWriter.SetSmartMode(smartMode: true);
826 ////now we need to do the engineering work
827 //PdfDocument pdfDoc = new PdfDocument(new PdfReader(tempfile));
828 // PdfDocument writedoc = null;// new PdfDocument(outputpdfWriter);
829 // org.pdfclown.files.File file = new org.pdfclown.files.File(tempfile);
830 // org.pdfclown.documents.Document document = file.Document;
831
832 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(String.Format("File loaded for engineering is {0}", filepath));
833
834 bool bexception = false;
835 try
836 {
837
838 //if (pdfDoc == null)
839 // throw new Exception("Reader did not create successfully");
840 //if (writedoc == null)
841 // throw new Exception("Writer did not create successfully");
842
843 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Engineering get pages to work with by sorting the Seq number");
844 //check to see if the new column is there first then if so
845 //documentsequence
846 List<System.Data.DataColumn> columns = new List<System.Data.DataColumn>();
847 foreach (System.Data.DataColumn item in dt.Columns)
848 columns.Add(item);
849
850
851 // Document doc = new Document(writedoc);
852
853
854 #region Sorting
855 //do the lookup to see if the DocumentSequence column exists
856 System.Data.DataRow[] rows = dt.Select();
857 if (CISObject.Keys != null)
858 {
859 if (!(bool)CISObject?.Keys?.Keys.Contains("CustomSort"))
860 {
861 rows = dt.Select("SequenceNumber is not null", "SequenceNumber asc");
862 if (columns.Find(c => c.ColumnName.ToLower() == "documentsequence") != null)
863 {
864 rows = dt.Select("SequenceNumber is not null and DocumentSequence is not null", "SequenceNumber, DocumentSequence asc");
865 if (rows?.Length == 0)
866 rows = dt.Select("SequenceNumber is not null", "SequenceNumber asc");
867 }
868 //if all else fails sort by recorddetails id
869 if (rows?.Length == 0)
870 {
871 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Sequence number not populate sort by the id column");
872 rows = new System.Data.DataRow[dt.Rows.Count];
873 dt.Rows.CopyTo(rows, 0);
874 }
875
876 }
877 else
878 {
879 bool nullvariable = String.IsNullOrEmpty(CISObject?.Keys["CustomSort"]?.ToString());
880 if ((String.IsNullOrEmpty(CISObject?.Keys["CustomSort"]?.ToString()) ? false :
881 Convert.ToBoolean(String.IsNullOrEmpty(CISObject?.Keys["CustomSort"]?.ToString()) ? "false" : CISObject?.Keys["CustomSort"]?.ToString())) == false)
882 {
883 rows = dt.Select("SequenceNumber is not null", "SequenceNumber asc");
884 if (columns.Find(c => c.ColumnName.ToLower() == "documentsequence") != null)
885 {
886 // System.Data.DataView view = new System.Data.DataView(dt);
887 // view.Sort = "SequenceNumber ASC,DocumentSequence ASC";
888 // view.ToTable().Rows.CopyTo(rows,0);
889 rows = dt.Select("SequenceNumber is not null and DocumentSequence is not null", "SequenceNumber, DocumentSequence");
890 if (rows?.Length == 0)
891 rows = dt.Select("SequenceNumber is not null", "SequenceNumber asc");
892 }
893 //if all else fails sort by recorddetails id
894 if (rows?.Length == 0)
895 {
896 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Sequence number not populate sort by the id column");
897 rows = new System.Data.DataRow[dt.Rows.Count];
898 dt.Rows.CopyTo(rows, 0);
899 }
900 }
901 }
902
903 }
904 else
905 {
906 rows = dt.Select("SequenceNumber is not null", "SequenceNumber asc");
907 if (columns.Find(c => c.ColumnName.ToLower() == "documentsequence") != null)
908 {
909 rows = dt.Select("SequenceNumber is not null and DocumentSequence is not null", "SequenceNumber, DocumentSequence asc");
910 if (rows?.Length == 0)
911 rows = dt.Select("SequenceNumber is not null", "SequenceNumber asc");
912 }
913 //if all else fails sort by recorddetails id
914 if (rows?.Length == 0)
915 {
916 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Sequence number not populate sort by the id column");
917 rows = new System.Data.DataRow[dt.Rows.Count];
918 dt.Rows.CopyTo(rows, 0);
919 }
920 }
921 #endregion
922 System.Data.DataRow[] parentrow = new System.Data.DataRow[dt.Rows.Count];
923 dt.Rows.CopyTo(parentrow, 0);
924
925 List<System.Data.DataRow> parentrows = new List<System.Data.DataRow>(parentrow);
926 rows = this.RemoveDuplicateRows(new List<System.Data.DataRow>(rows), "StartPage");
927 List<System.Data.DataRow> MasterlistofRows = new List<System.Data.DataRow>(rows);
928
929 //get the overall documentcount
930 DOCCOUNT = MasterlistofRows.Count - 1;
931
932 List<Racami.Common.pages> ExistingPages = pages.FindAll(ptg => String.IsNullOrEmpty(ptg.applyTo));
933 List<Racami.Common.pages> FirstPages = pages.FindAll(fl => fl.isAdded && !String.IsNullOrEmpty(fl.applyTo) && String.IsNullOrEmpty(fl.addedPage));
934 List<Racami.Common.pages> AdditionalPages = pages.FindAll(fl => fl.isAdded && !String.IsNullOrEmpty(fl.applyTo) && !String.IsNullOrEmpty(fl.addedPage));
935
936 //get all other variables
937 bool firstpage = false;
938 bool lastpage = false;
939 int ifirstpage = 0;
940 List<Racami.Common.customTexts> allpages = null;
941 List<Racami.Common.customTexts> oddpages = null;
942 List<Racami.Common.customTexts> evenpages = null;
943 List<Racami.Common.customTexts> custom = null;
944
945 List<Racami.Common.masks> sallpages = null;
946 List<Racami.Common.masks> soddpages = null;
947 List<Racami.Common.masks> sevenpages = null;
948 List<Racami.Common.masks> scustom = null;
949
950
951 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Engineering Get all custom all , odd, even work");
952 //we need to get at all custom actions first
953 System.Threading.Tasks.Parallel.ForEach(pages, (pg) =>
954 {
955 if (pg?.masks?.Count > 0)
956 {
957 sallpages = new List<Racami.Common.masks>(pg?.masks.FindAll(ct => ct.condition == "ALL"));
958 soddpages = new List<Racami.Common.masks>(pg?.masks.FindAll(ct => ct.condition == "ODD"));
959 sevenpages = new List<Racami.Common.masks>(pg?.masks.FindAll(ct => ct.condition == "EVEN"));
960 scustom = new List<Racami.Common.masks>(pg?.masks.FindAll(ct => ct.condition == "CUSTOM"));
961
962 sallpages.AddRange(new List<Racami.Common.masks>(pg?.masks.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ALL"))));
963 soddpages.AddRange(new List<Racami.Common.masks>(pg?.masks.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ODD"))));
964 sevenpages.AddRange(new List<Racami.Common.masks>(pg?.masks.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=EVEN"))));
965
966 pg?.masks.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=EVEN")).ForEach(fl => { pg?.masks.Remove(fl); });
967 pg?.masks.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ODD")).ForEach(fl => { pg?.masks.Remove(fl); });
968 pg?.masks.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ALL")).ForEach(fl => { pg?.masks.Remove(fl); });
969
970 pg?.masks.FindAll(ct => ct.condition == "ALL").ForEach(fl => { pg?.masks.Remove(fl); });
971 pg?.masks.FindAll(ct => ct.condition == "ODD").ForEach(fl => { pg?.masks.Remove(fl); });
972 pg?.masks.FindAll(ct => ct.condition == "EVEN").ForEach(fl => { pg?.masks.Remove(fl); });
973
974
975 }
976 if (pg?.customTexts?.Count > 0)
977 {
978 allpages = new List<Racami.Common.customTexts>(pg?.customTexts.FindAll(ct => ct.condition == "ALL"));
979 oddpages = new List<Racami.Common.customTexts>(pg?.customTexts.FindAll(ct => ct.condition == "ODD"));
980 evenpages = new List<Racami.Common.customTexts>(pg?.customTexts.FindAll(ct => ct.condition == "EVEN"));
981 custom = new List<Racami.Common.customTexts>(pg?.customTexts.FindAll(ct => ct.condition == "CUSTOM"));
982
983
984
985
986 allpages.AddRange(new List<Racami.Common.customTexts>(pg?.customTexts.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ALL"))));
987 oddpages.AddRange(new List<Racami.Common.customTexts>(pg?.customTexts.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ODD"))));
988 evenpages.AddRange(new List<Racami.Common.customTexts>(pg?.customTexts.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=EVEN"))));
989
990
991
992 pg?.customTexts.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=EVEN")).ForEach(fl => { pg?.customTexts.Remove(fl); });
993 pg?.customTexts.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ODD")).ForEach(fl => { pg?.customTexts.Remove(fl); });
994 pg?.customTexts.FindAll(ct => ct.logic.ToUpper().Contains("APPLYTO=ALL")).ForEach(fl => { pg?.customTexts.Remove(fl); });
995
996 pg?.customTexts.FindAll(ct => ct.condition == "ALL").ForEach(fl => { pg?.customTexts.Remove(fl); });
997 pg?.customTexts.FindAll(ct => ct.condition == "ODD").ForEach(fl => { pg?.customTexts.Remove(fl); });
998 pg?.customTexts.FindAll(ct => ct.condition == "EVEN").ForEach(fl => { pg?.customTexts.Remove(fl); });
999
1000 }
1001 });
1002
1003 System.Data.DataRow lastrow = null;
1004 RECSTART = 1;
1005 int household = 0;
1006
1007 System.Diagnostics.Stopwatch stepa = new System.Diagnostics.Stopwatch();
1008 stepa.Start();
1009 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Pre---Processing started in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}"); else Console.WriteLine($"Pre-Processing started in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}");
1010
1011
1012 PDFMapping pDFMapping = new PDFMapping();
1013 DoMapping(document, pDFMapping, new List<System.Data.DataRow>(MasterlistofRows), null);
1014 int TotalPages = document.GetNumberOfPages();
1015 document.Close();
1016
1017 stepa.Stop();
1018 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Pre---Processing completed in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}"); else Console.WriteLine($"Pre-Processing completed in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}");
1019
1020 System.Data.DataRow irows = null;
1021 int listcnt = 0;
1022 stepa = new System.Diagnostics.Stopwatch();
1023 stepa.Start();
1024 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"reassignment Processing started in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}"); else Console.WriteLine($"reassignment Processing started in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}");
1025
1026 //for (int i = 1; i < pdfDoc.GetNumberOfPages(); i++)
1027 // pdfDoc.CopyPagesTo(i, i, writedoc);
1028 stepa.Stop();
1029 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"reassignment Processing completed in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}"); else Console.WriteLine($"reassignment Processing completed in {stepa.Elapsed} for file {System.IO.Path.GetFileName(tempfile)}");
1030
1031 // pdfDoc.Close();
1032
1033 var pdftoprocess = new ActionBlock<List<PDFLoctions>>(pdf =>
1034
1035 {
1036 pdf?.ForEach(ipg =>
1037 {
1038 System.Diagnostics.Stopwatch stepaa = new System.Diagnostics.Stopwatch();
1039 stepaa.Start();
1040
1041 PdfPage pg = ipg.document.GetPage(ipg.PageNumber);// writedoc.GetPage(ipg.OrgPageNumber);
1042 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Processing {ipg.OrgPageNumber} "); else Console.WriteLine($"Processing {ipg.OrgPageNumber}");
1043
1044 if (pg != null)
1045 {
1046 int pagenum = ipg.PageNumber;// pg.Index + 1;
1047 var spaage = ipg.Row;// MasterlistofRows.Find(r => r["StartPage"].ToString() == (pg.Index + 1).ToString());
1048
1049 if (lastpage != null)
1050 {
1051 if (sallpages?.Count > 0)
1052 DoMaskWork(sallpages, pg, config, CISObject);
1053
1054
1055 if (allpages?.Count > 0)
1056 DoCustomTextWork(allpages, pg, config, fontDic, lastrow, CISObject);
1057 }
1058
1059 if (spaage != null)
1060 {
1061 RECPAGECOUNT = Convert.ToInt32(spaage["EndPage"].ToString()) + 1 - Convert.ToInt32(spaage["StartPage"].ToString());
1062 //check to see if the householdid is there.. if so use it for this
1063 if (spaage.Table.Columns.Contains("HouseHoldingId"))
1064 {
1065 if (!String.IsNullOrEmpty(spaage["HouseHoldingId"].ToString()))
1066 {
1067
1068
1069 if (household != Convert.ToInt32(spaage["HouseHoldingId"].ToString()))
1070 {
1071 household = Convert.ToInt32(spaage["HouseHoldingId"].ToString());
1072 CURRENTDOC = 1;
1073 HOUSEHOLDPAGE = 1;
1074 HOUSEHOLDODDPAGE = 1;
1075 HOUSEHOLDEVENPAGE = 1;
1076 }
1077 else
1078 {
1079 var cnt = String.IsNullOrEmpty(spaage["HouseHoldingId"].ToString()) ? 0 : MasterlistofRows.FindAll(ml => ml["HouseHoldingId"].ToString() == spaage["HouseHoldingId"].ToString()).Count;
1080 if (cnt <= 1)
1081 {
1082 CURRENTDOC = 1;
1083 HOUSEHOLDPAGE = 1;
1084 HOUSEHOLDODDPAGE = 1;
1085 HOUSEHOLDEVENPAGE = 1;
1086 }
1087 else
1088 {
1089 CURRENTDOC++;
1090 if (IsOdd(pagenum))//pg.Index + 1))
1091 HOUSEHOLDODDPAGE++;
1092 else
1093 HOUSEHOLDEVENPAGE++;
1094 }
1095 }
1096
1097
1098 }
1099 else
1100 {
1101 CURRENTDOC = 1;
1102 HOUSEHOLDPAGE = 1;
1103 HOUSEHOLDODDPAGE = 1;
1104 HOUSEHOLDEVENPAGE = 1;
1105 }
1106 // }
1107 }
1108 else
1109 {
1110 CURRENTDOC = 1;
1111 HOUSEHOLDPAGE = 1;
1112 HOUSEHOLDODDPAGE = 1;
1113 HOUSEHOLDEVENPAGE = 1;
1114 }
1115 lastrow = spaage;
1116
1117 RECSTART = 1;
1118 lastrow = spaage;
1119 #region xmldata
1120 System.Xml.XmlNode node = this.MakeXmlChanges(lastrow, dt, Option);
1121 string Expression = Option == "Job" ? "PDF/Current[@Level='Job']" : "PDF/Current[@Level='Detail']";
1122 var Startpagen = ((System.Xml.XmlDocument)node).DocumentElement.SelectSingleNode(Expression);
1123 int spage = Convert.ToInt32(Startpagen.Attributes["StartPage"].InnerText);
1124 int espage = Convert.ToInt32(Startpagen.Attributes["Endpage"].InnerText);
1125 List<int> intpgs = new List<int>();
1126 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("start page is " + spage.ToString());
1127 System.Xml.XmlElement currentnode = ((System.Xml.XmlDocument)node).CreateElement("Engineering");
1128 currentnode.SetAttribute("Level", Option == "Job" ? "Job" : "Detail");
1129 currentnode.SetAttribute("RunDate", System.DateTime.Now.ToString());
1130 currentnode.SetAttribute("StartPage", spage.ToString());
1131 #endregion
1132 int Startpage = spage;// Convert.ToInt32(dt.Columns.Contains("start_page") ? Row["start_page"] : Row["StartPage"]);
1133 bool addedapage = false;
1134 int addedpagecnt = 0;
1135
1136 //add the first or last page first.. keep track of the first or last entry so the start page can be added to
1137 //System.Threading.Tasks.Parallel.ForEach(pages.FindAll(fl => fl.isAdded && !String.IsNullOrEmpty(fl.applyTo)), (p) =>
1138 FirstPages.ForEach(p =>
1139 {
1140 PdfPage page = null;
1141 //org.pdfclown.documents.Page page = null;
1142 //as for right now we do not do conditional logic on this type of page setup
1143 //this could change in the future
1144 if (p?.applyTo == "FIRST" && !firstpage)
1145 {
1146 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("ADDED FIRST PAGE");
1147 page = ipg.document.AddNewPage(1, new PageSize(ipg.document.GetFirstPage().GetPageSize())); //document.Pages.First();
1148 // document.Pages.Insert(page.Index, new org.pdfclown.documents.Page(document) { Size = page.Size });
1149 // page = document.Pages.First();
1150 firstpage = true;
1151 ifirstpage++;
1152 RECPAGECOUNT++;
1153
1154 }
1155 if (p.applyTo == "LAST" && !lastpage)
1156 {
1157 //page = document.Pages.Last();
1158 lastpage = true;
1159 // document.Pages.Add(new org.pdfclown.documents.Page(document) { Size = page.Size });
1160 page = ipg.document.AddNewPage(ipg.document.GetNumberOfPages() + 1);// document.Pages.Last();
1161 lastpage = true;
1162 RECPAGECOUNT++;
1163
1164 }
1165 // Startpage++;
1166
1167 if (page != null)
1168 {
1169 //process masks first so if it is a cover up or a redaction it will not be overwrite text being placed there
1170 DoMaskWork(p.masks, page, config, CISObject);
1171 DoVariableWork(p.variables, page, config, fontDic, lastrow, CISObject);
1172 DoCustomTextWork(p.customTexts, page, config, fontDic, lastrow, CISObject);
1173 DoLinkWork(p.links, page, config, CISObject);
1174
1175 }
1176
1177 });
1178 Startpage += ifirstpage;
1179
1180
1181 // System.Threading.Tasks.Parallel.ForEach(pages.FindAll(ptg => String.IsNullOrEmpty(ptg.applyTo)), (p) =>
1182 // System.Threading.Tasks.Parallel.ForEach(ExistingPages , (p) => //.ForEach(p =>
1183 ExistingPages.ForEach(p =>
1184 {
1185 PdfPage page = null;
1186 //org.pdfclown.documents.Page page = null;
1187 //do the add new pages work else get the existing page
1188 if (p.isAdded)
1189 {
1190 addedpagecnt++;
1191 // document.Pages.Insert(Startpage, new org.pdfclown.documents.Page(document));
1192 page = ipg.document.AddNewPage(Startpage, new PageSize(ipg.document.GetFirstPage().GetPageSize())); //document.Pages.Last();
1193
1194 }
1195 else
1196 page = pg;// writedoc.GetPage(ipg.OrgPageNumber);// document.Pages[Startpage - 1];//epages.Find(ee => == Startpage) != null ? epages.Find(ee => writedoc.GetPageNumber(ee) == Startpage) : null;
1197
1198 if (IsOdd(pagenum))
1199 {
1200 // HOUSEHOLDODDPAGE++;
1201 if (soddpages?.Count > 0)
1202 DoMaskWork(soddpages, page, config, CISObject);
1203 if (oddpages?.Count > 0)
1204 DoCustomTextWork(oddpages, page, config, fontDic, lastrow, CISObject);
1205
1206 }
1207 else
1208 {
1209 // HOUSEHOLDEVENPAGE++;
1210 if (sevenpages?.Count > 0)
1211 DoMaskWork(sevenpages, page, config, CISObject);
1212 if (evenpages?.Count > 0)
1213 DoCustomTextWork(evenpages, page, config, fontDic, lastrow, CISObject);
1214
1215 }
1216
1217 if (page != null)
1218 {
1219 //process masks first so if it is a cover up or a redaction it will not be overwrite text being placed there
1220 DoMaskWork(p.masks, page, config, CISObject);
1221 DoVariableWork(p.variables, page, config, fontDic, lastrow, CISObject);
1222 DoCustomTextWork(p.customTexts, page, config, fontDic, lastrow, CISObject);
1223 DoLinkWork(p.links, page, config, CISObject);
1224 Startpage++;
1225 }
1226
1227 });
1228
1229 //now add the additional page functionality
1230 //System.Threading.Tasks.Parallel.ForEach(pages.FindAll(fl => fl.isAdded && !String.IsNullOrEmpty(fl.applyTo)), (p) =>
1231 AdditionalPages.ForEach(p =>
1232 {
1233 PdfPage page = null;
1234 //org.pdfclown.documents.Page page = null;
1235 //as for right now we do not do conditional logic on this type of page setup
1236 //this could change in the future
1237 if (p.isAdded)
1238 {
1239 if ((bool)p?.applyTo.ToUpper().Contains("ADDEDPAGE") || (bool)p?.applyTo.ToUpper().Contains("ADD_TO_PAGE"))
1240 {
1241
1242 //page = writedoc.AddNewPage(1, new iText.Kernel.Geom.PageSize(writedoc.GetFirstPage().GetPageSize()));
1243 String pagenumber = p.addedPage;
1244 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("ADDED " + pagenumber + " PAGE");
1245 page = ipg.document.AddNewPage(Convert.ToInt32(p.addedPage), new PageSize(ipg.document.GetFirstPage().GetPageSize())); //document.Pages.First();
1246 //page = document.Pages.First();
1247 //document.Pages.Insert(Convert.ToInt32(pagenumber), new org.pdfclown.documents.Page(document) { Size = page.Size });
1248 //page = document.Pages[Convert.ToInt32(pagenumber)];
1249 // firstpage = true;
1250 //ifirstpage++;
1251 addedpagecnt++;
1252 RECPAGECOUNT++;
1253 }
1254
1255
1256 if (page != null)
1257 {
1258
1259 //process masks first so if it is a cover up or a redaction it will not be overwrite text being placed there
1260 DoMaskWork(p.masks, page, config, CISObject);
1261 DoVariableWork(p.variables, page, config, fontDic, lastrow, CISObject);
1262 DoCustomTextWork(p.customTexts, page, config, fontDic, lastrow, CISObject);
1263 DoLinkWork(p.links, page, config, CISObject);
1264
1265 }
1266 p.isAdded = false;
1267 }
1268
1269 });
1270
1271 ((System.Xml.XmlElement)Startpagen).SetAttribute("Endpage", (espage + addedpagecnt).ToString());
1272 currentnode.SetAttribute("Endpage", (espage + addedpagecnt).ToString());
1273 var extract = ((System.Xml.XmlDocument)node).DocumentElement.SelectSingleNode("PDF");
1274 extract.AppendChild(currentnode);
1275 nodes.Add(new XmlBlock() { node = node, Objectid = Convert.ToInt32(spaage["RecordDetailsID"]) });
1276
1277
1278 }
1279 else
1280 {
1281 RECSTART++;
1282 // this will handle each page if the conditional logic is assigne to do so
1283 if (lastrow != null)
1284 {
1285
1286
1287 if (IsOdd(pagenum))
1288 {
1289 HOUSEHOLDODDPAGE++;
1290 if (soddpages?.Count > 0)
1291 DoMaskWork(soddpages, pg, config, CISObject);
1292 if (oddpages?.Count > 0)
1293 DoCustomTextWork(oddpages, pg, config, fontDic, lastrow, CISObject);
1294
1295 }
1296 else
1297 {
1298 HOUSEHOLDEVENPAGE++;
1299 if (sevenpages?.Count > 0)
1300 DoMaskWork(sevenpages, pg, config, CISObject);
1301 if (evenpages?.Count > 0)
1302 DoCustomTextWork(evenpages, pg, config, fontDic, lastrow, CISObject);
1303
1304 }
1305 }
1306 }
1307
1308 HOUSEHOLDPAGE++;
1309
1310 }
1311
1312 pg?.Flush(true);
1313 // ipg?.page?.Flush(true);
1314 // Console.WriteLine($"Processed {pagenum} in {stepa.Elapsed}");
1315 stepaa.Stop();
1316 });
1317 // GC.Collect();
1318 });
1319
1320 List<PDFLoctions> pDFLoctions = new List<PDFLoctions>();
1321
1322
1323 foreach (var lmapping in pDFMapping.mappings)
1324 {
1325 int processamount = 1;
1326 for (int i = 1; i < lmapping.pdfDocument.GetNumberOfPages() + 1; i++)
1327 {
1328 PDFLoctions locc = null;
1329 PdfPage page = lmapping.pdfDocument.GetPage(i);
1330
1331
1332 locc = new PDFLoctions()
1333 {
1334 IsBlank = true,
1335 PageNumber = lmapping.PageMappings.Find(m => m.Mappedpagenumber == i).Mappedpagenumber,
1336 document = lmapping.pdfDocument,
1337 page = page,
1338 Row = lmapping.PageMappings.Find(m => m.Mappedpagenumber == i).Row,
1339 // dtResult = dtResult,
1340 // listener = new FilteredEventListener(),
1341 // pdfRasterizer = lmapping.pdfRasterizer,
1342 OrgPageNumber = lmapping.PageMappings.Find(m => m.Mappedpagenumber == i).Orgpagenumber
1343
1344
1345 };
1346 pDFLoctions.Add(locc);
1347 processamount++;
1348 }
1349
1350 pdftoprocess.Post(new List<PDFLoctions>(pDFLoctions.ToArray()));
1351 pDFLoctions.Clear();
1352 }
1353
1354 pdftoprocess.Post(new List<PDFLoctions>(pDFLoctions.ToArray()));
1355 pdftoprocess.Complete();
1356 pdftoprocess.Completion.ContinueWith(task =>
1357 {
1358
1359 Console.WriteLine("CleAN UP ");
1360 // metadatas.ForEach(m => { m.document.Close(); });
1361 });
1362
1363 // Wait for completion in a try/catch block.
1364 try
1365 {
1366 pdftoprocess.Completion.Wait();
1367 }
1368 catch (AggregateException ae)
1369 {
1370 // If an unhandled exception occurs during dataflow processing, all
1371 // exceptions are propagated through an AggregateException object.
1372 ae.Handle(e =>
1373 {
1374 Console.WriteLine("Encountered {0}: {1}",
1375 e.GetType().Name, e.Message);
1376 return true;
1377 });
1378 }
1379
1380 PdfWriter outputpdfWriter = new PdfWriter(tempfile + "mk");
1381 outputpdfWriter.SetSmartMode(smartMode: true);
1382 PdfDocument writedoc = new PdfDocument(outputpdfWriter);
1383 PdfMerger pDFMerger = new PdfMerger(writedoc);
1384 pDFMerger.SetCloseSourceDocuments(true);
1385 pDFLoctions.ForEach(loc => { loc.Dispose(); });
1386
1387 foreach (var lmapping in pDFMapping.mappings)
1388 {
1389 lmapping.pdfDocument.Close();
1390 PdfDocument pdfDocument = new PdfDocument(new PdfReader(lmapping.PDFFile));
1391 try
1392 {
1393 pDFMerger.Merge(pdfDocument, 1, pdfDocument.GetNumberOfPages());
1394 writedoc.FlushCopiedObjects(pdfDocument);
1395 // pdfDocument.CopyPagesTo(1, pdfDocument.GetNumberOfPages(), writedoc);
1396
1397 }
1398 finally
1399 {
1400 // pdfDocument.Close();
1401
1402 }
1403
1404
1405 if (System.IO.File.Exists(lmapping.PDFFile))
1406 System.IO.File.Delete(lmapping.PDFFile);
1407
1408 if (System.IO.File.Exists(lmapping.PDFFile + "wr"))
1409 System.IO.File.Delete(lmapping.PDFFile + "wr");
1410
1411 // lmapping.
1412 if (System.IO.File.Exists(lmapping.Rasterfile))
1413 System.IO.File.Delete(lmapping.Rasterfile);
1414
1415 }
1416 pDFMerger.Close();
1417 // writedoc.SetFlushUnusedObjects(flushUnusedObjects: true);
1418 writedoc.Close();
1419
1420
1421 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Update the database on the engineering xmldata");
1422 using (System.Data.SqlClient.SqlConnection connect = new System.Data.SqlClient.SqlConnection(ConnectionString))
1423 {
1424 connect.Open();
1425 foreach (XmlBlock item in nodes)
1426 {
1427 using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
1428 {
1429 cmd.Connection = connect;
1430 cmd.CommandTimeout = 600;
1431 cmd.CommandText = string.Format("update recorddetailsv2 set xmldata = '{0}' where recorddetailsid = {1}", item.node.InnerXml, item.Objectid);
1432 cmd.ExecuteNonQuery();
1433 cmd.Dispose();
1434 }
1435
1436 }
1437 connect.Close();
1438 connect.Dispose();
1439 }
1440 Console.WriteLine("After DB");
1441 }
1442 catch (Exception ex)
1443 {
1444 bexception = true;
1445 throw new Exception(ex.Message, ex);
1446 }
1447 finally
1448 {
1449 if (!bexception)
1450 {
1451 // org.pdfclown.files.SerializationModeEnum serializationMode = org.pdfclown.files.SerializationModeEnum.Standard;
1452 try
1453 {
1454
1455 //{
1456 // System.IO.FileStream fileStream = new FileStream(tempfile + "mk", System.IO.FileMode.Create, FileAccess.Write);
1457 // file.Save(fileStream, serializationMode);
1458 // file.Dispose();
1459 // fileStream.Dispose();
1460
1461 // writedoc.SetFlushUnusedObjects(flushUnusedObjects: true);
1462 // writedoc.Close();
1463
1464
1465 if (System.IO.File.Exists(filepath))
1466 {
1467 string[] files = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(filepath), System.IO.Path.GetFileName(filepath) + ".org*");
1468 string orgpath = System.IO.Path.GetDirectoryName(filepath) + "//" + System.IO.Path.GetFileName(filepath) + String.Format(".org{0}", files.Length);
1469 System.IO.File.Move(filepath, orgpath);
1470 }
1471 if (System.IO.File.Exists(tempfile + "mk"))
1472 System.IO.File.Move(tempfile + "mk", filepath);
1473 // }
1474 //if (System.IO.File.Exists(filepath + "mk"))
1475 // System.IO.File.Move(filepath + "mk", filepath);
1476 }
1477 catch (Exception e)
1478 {
1479 //if it fails let's see if we can do the qpdf to correct it to save it
1480 // try
1481
1482 //catch
1483 //{
1484 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("File writing failed: " + e.Message);
1485 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(e.StackTrace);
1486 throw e;
1487 //}
1488 }
1489 finally
1490 {
1491 // file.Dispose();
1492 // pdfDoc.Close();
1493 // writedoc.Close();
1494 //make sure the temp file is removed..
1495 if (System.IO.File.Exists(tempfile))
1496 System.IO.File.Delete(tempfile);
1497 if (!System.IO.File.Exists(filepath))
1498 throw new Exception($"There was no error and the {filepath} does not exist... this is fatal");
1499
1500
1501
1502 }
1503 }
1504 else
1505 {
1506
1507 // pdfDoc.Close();
1508 // writedoc.Close();
1509
1510 // file.Dispose();
1511 if (System.IO.File.Exists(tempfile + "mk"))
1512 System.IO.File.Delete(tempfile + "mk");
1513 if (System.IO.File.Exists(tempfile))
1514 System.IO.File.Delete(tempfile);
1515 if (!System.IO.File.Exists(filepath))
1516 throw new Exception($"There was no error and the {filepath} does not exist... this is fatal");
1517 }
1518
1519
1520 }
1521
1522
1523
1524 }
1525
1526
1527
1528 #region custom
1529 #region internal utils
1530 public int[] GetRGB(string input)
1531 {
1532 int[] result = new int[3];
1533 // if the input is in the format of "rgb(0,0,0)"
1534 if (input.Contains("rgb"))
1535 {
1536 int start = input.IndexOf('(');
1537 int end = input.IndexOf(')');
1538
1539 try
1540 {
1541 string sub = input.Substring(start + 1, end - start - 1);
1542 string[] split = sub.Split(',');
1543 result = new int[]{int.Parse(split[0]),
1544 int.Parse(split[1]),
1545 int.Parse(split[2])};
1546 return result;
1547 }
1548 catch (ArgumentOutOfRangeException e)
1549 {
1550 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(e);
1551 }
1552 }
1553 // HTML Hex color format
1554 else
1555 {
1556 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"HEX value color {input}");
1557 System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml(input);
1558 result = new int[] { int.Parse(col.R.ToString()), int.Parse(col.G.ToString()), int.Parse(col.B.ToString()) };
1559 }
1560 return result;
1561 }
1562
1563 public List<Racami.Common.variables> CombineSameline(List<Racami.Common.variables> variables)
1564 {
1565 List<Racami.Common.variables> retlist = new List<Racami.Common.variables>();
1566 Racami.Common.variables[] array = new Racami.Common.variables[variables.Count];
1567 variables.CopyTo(array);
1568 List<Racami.Common.variables> varlist = new List<Racami.Common.variables>(array);
1569 for (int varr = 0; varr < varlist.Count; varr++)
1570 //foreach (Racami.Common.variables item in variables)
1571 {
1572 Racami.Common.variables item = varlist[varr];
1573 //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("item.value is ={0}", item.value));
1574 var top = item.styles.position.top;
1575 int t = item.styles.position.top.ToString().IndexOf(".") + 1;
1576 List<char> number = new List<char>();
1577 if (t == 0)
1578 {
1579 for (int i = 0; i < item.styles.position.top.ToString().Length; i++)
1580 {
1581 number.Add(item.styles.position.top.ToString()[i]);
1582 }
1583 }
1584 else
1585 {
1586
1587 for (int i = 0; i < t; i++)
1588 {
1589 number.Add(item.styles.position.top.ToString()[i]);
1590 }
1591 }
1592
1593 var floatNumber = (int)Convert.ToDecimal(top);
1594
1595 //var x = floatNumber - Math.Truncate(floatNumber);
1596
1597 string num = new string(number.ToArray());
1598 // int tt = Convert.ToInt32(num);
1599 var nn = num.Contains(".") ? num : num + ".";
1600 // var testlook = Convert.ToDecimal(top);
1601 List<Racami.Common.variables> ret = varlist.FindAll(v => (int)Convert.ToDecimal(v.styles.position.top) == floatNumber);
1602 if (ret.Count == 1) //ret.count is always 1, so the else part will never be executed...hmmm
1603 {
1604 if (ret[0].value.Contains("{{{RecordDetailsV2.UpdatedCity}}}{{{RecordDetailsV2.UpdatedState}}}") || ret[0].value.Contains("{{{RecordDetailsV2.City}}}{{{RecordDetailsV2.State}}}"))
1605 {
1606 if (ret[0].value.Contains("{{{RecordDetailsV2.UpdatedCity}}}{{{RecordDetailsV2.UpdatedState}}}"))
1607 {
1608 ret[0].value = ret[0].value.Replace("{{{RecordDetailsV2.UpdatedCity}}}{{{RecordDetailsV2.UpdatedState}}}", "{{{RecordDetailsV2.UpdatedCity}}},{{{RecordDetailsV2.UpdatedState}}}");
1609 }
1610 if (ret[0].value.Contains("{{{RecordDetailsV2.City}}}{{{RecordDetailsV2.State}}}"))
1611 {
1612 ret[0].value = ret[0].value.Replace("{{{RecordDetailsV2.City}}}{{{RecordDetailsV2.State}}}", "{{{RecordDetailsV2.City}}},{{{RecordDetailsV2.State}}}");
1613 }
1614 }
1615 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("ret[0] is ={0}=, ret[0].value is ={1}=", ret[0], ret[0].value));
1616 retlist.Add(ret[0]);
1617
1618 }
1619 else
1620 {
1621 if (ret.Count > 0)
1622 {
1623 Racami.Common.variables varf = new Racami.Common.variables();// { font = ret[0].font, model = ret[0].model,
1624 // origin = ret[0].origin, styles=ret[0].styles, type = ret[0].type, value = ret[0].value};
1625
1626
1627 //foreach (Racami.Common.variables sect in ret)
1628 for (int i = 0; i < ret.Count; i++)
1629
1630 {
1631 varf = new Racami.Common.variables()
1632 {
1633 font = ret[i].font,
1634 model = ret[i].model,
1635 origin = ret[i].origin,
1636 styles = ret[i].styles,
1637 type = ret[i].type,
1638 value = ret[i].value
1639 };
1640
1641 Racami.Common.variables sect = ret[i];
1642 if (sect.value != varf.value)
1643 {
1644 if (!varf.value.Contains(sect.value))
1645 {
1646 varf.value += sect.value;
1647 }
1648
1649 }
1650 // varlist.Remove(sect);
1651 }
1652
1653 //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("varf.value is ={0}=", varf.value)); //for debugging only
1654
1655 if (retlist.Find(r => r.value == varf.value) == null)
1656 {
1657 if (varf.value.Contains("{{{RecordDetailsV2.UpdatedCity}}}{{{RecordDetailsV2.UpdatedState}}}") || varf.value.Contains("{{{RecordDetailsV2.City}}}{{{RecordDetailsV2.State}}}"))
1658 {
1659 if (varf.value.Contains("{{{RecordDetailsV2.UpdatedCity}}}{{{RecordDetailsV2.UpdatedState}}}"))
1660 {
1661 varf.value = varf.value.Replace("{{{RecordDetailsV2.UpdatedCity}}}{{{RecordDetailsV2.UpdatedState}}}", "{{{RecordDetailsV2.UpdatedCity}}},{{{RecordDetailsV2.UpdatedState}}}");
1662 }
1663 if (varf.value.Contains("{{{RecordDetailsV2.City}}}{{{RecordDetailsV2.State}}}"))
1664 {
1665 varf.value = varf.value.Replace("{{{RecordDetailsV2.City}}}{{{RecordDetailsV2.State}}}", "{{{RecordDetailsV2.City}}},{{{RecordDetailsV2.State}}}");
1666 }
1667 }
1668
1669 retlist.Add(varf);
1670 }
1671
1672 }
1673 }
1674 }
1675
1676 return retlist;
1677 }
1678
1679 public static T Clone<T>(T source)
1680 {
1681 if (!typeof(T).IsSerializable)
1682 {
1683 throw new ArgumentException("The type must be serializable.", "source");
1684 }
1685
1686 // Don't serialize a null object, simply return the default for that object
1687 if (Object.ReferenceEquals(source, null))
1688 {
1689 return default(T);
1690 }
1691
1692 System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
1693 System.IO.Stream stream = new System.IO.MemoryStream();
1694 using (stream)
1695 {
1696 formatter.Serialize(stream, source);
1697 stream.Seek(0, System.IO.SeekOrigin.Begin);
1698 return (T)formatter.Deserialize(stream);
1699 }
1700 }
1701 public string TextAssignment(object vari, System.Data.DataRow Row, EngineObject.CISObjects CISObject)
1702 {
1703 string TextValue = "";
1704
1705 #region text assignment
1706 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Assigned Text : " + (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value));
1707 try
1708 {
1709
1710 TextValue = Racami.TextSubstitute.Substitute.Convert(vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value, CISObject, Row);
1711
1712 // int count = 1; //dummy count, needed for the citystatezip combination so it displays as "city state zip", not "citystatezip"
1713 // if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("}}},{{{") : ((Racami.Common.variables)vari).value.Contains("}}},{{{")) //city,state zip, sample value = {{{UpdatedCity}}},{{{UpdatedState}}}{{{UpdatedZip}}}
1714 // {
1715 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("vari.value is ={0}=", vari.value));
1716 // string[] tempi = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Split(',') : ((Racami.Common.variables)vari).value.Split(',');
1717 // foreach (string t in tempi)
1718 // {
1719 // if (!t.Contains("}}}{{{"))
1720 // {
1721 // if (t.Contains("{{{"))
1722 // {
1723 // string temppp = t.Replace("{{{", "#");
1724 // string[] temps = temppp.Split('#');
1725 // foreach (var vars in temps)
1726 // {
1727 // try
1728 // {
1729 // if (String.IsNullOrEmpty(TextValue))
1730 // TextValue = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value;
1731
1732 // TextValue = Racami.TextSubstitute.Substitute.Convert(vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value, CISObject, Row);
1733
1734 // if (TextValue.Contains("Job_Option_Details") || TextValue.Contains("Jobs") || TextValue.Contains("Files"))
1735 // {
1736 // if (CISObject.JobDetails == null && CISObject.Jobs == null && CISObject.Files == null)
1737 // throw new Exception("The job , option or file must be populated to process the substitutions");
1738 // string column = vars.ToLower().Replace("job_option_details.", "").Replace("jobs.", "").Replace("files.", "").Replace("}}}", "");
1739
1740 // List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(!vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0].GetType().GetProperties() : CISObject.Jobs[0].GetType().GetProperties() : CISObject.JobDetails[0].GetType().GetProperties());
1741 // System.Reflection.PropertyInfo prop = info.Find(p => p.Name.ToLower() == column);
1742 // if (prop == null)
1743 // throw new Exception("Substitution value is not supported " + (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value));
1744 // Type tt = !vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0].GetType() : CISObject.Jobs[0].GetType() : CISObject.JobDetails[0].GetType();
1745 // object obj = !vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0] : CISObject.Jobs[0] as object : CISObject.JobDetails[0] as object;
1746 // var propvalue = prop.GetValue(obj, null);
1747 // TextValue = TextValue.Replace(column, propvalue.ToString()).Replace("Job_Option_Details.", "").Replace("Jobs", "").Replace("Files", "").Replace("{{{", "").Replace("}}}", "");
1748 // }
1749 // else if (TextValue.Contains("RecordDetailsV2"))
1750 // {
1751 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else only"));
1752 // string column = vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1753 // TextValue = TextValue.Replace(column, Row[column].ToString()).ToString().Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1754 // }
1755 // // TextValue = TextValue.Replace(column, Row[column].ToString()).ToString().Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1756 // }
1757 // catch
1758 // {
1759
1760 // }
1761
1762 // }
1763 // //string columnname = vari.value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1764 // //TextValue = Row[columnname].ToString() as string;
1765 // }
1766 // else
1767 // {
1768 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("if t: ={0}=", t)); //for debugging only
1769 // //TextValue += Row[t.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "")].ToString() as string + ", ";
1770 // if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("{{{") : ((Racami.Common.variables)vari).value.Contains("{{{"))
1771 // {
1772 // string temppp = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Replace("{{{", "#") : ((Racami.Common.variables)vari).value.Replace("{{{", "#");
1773 // string[] temps = temppp.Split('#');
1774 // foreach (var vars in temps)
1775 // {
1776 // try
1777 // {
1778
1779 // if (vars.Contains("Job_Option_Details") || vars.Contains("Jobs") || vars.Contains("Files"))
1780 // {
1781 // if (CISObject.JobDetails == null && CISObject.Jobs == null && CISObject.Files == null)
1782 // throw new Exception("The job , option or file must be populated to process the substitutions");
1783 // string column = vars.ToLower().Replace("job_option_details.", "").Replace("jobs.", "").Replace("files.", "").Replace("}}}", "");
1784
1785 // List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(!vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0].GetType().GetProperties() : CISObject.Jobs[0].GetType().GetProperties() : CISObject.JobDetails[0].GetType().GetProperties());
1786 // System.Reflection.PropertyInfo prop = info.Find(p => p.Name.ToLower() == column);
1787 // if (prop == null)
1788 // throw new Exception("Substitution value is not supported " + (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value));
1789 // Type tt = !vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0].GetType() : CISObject.Jobs[0].GetType() : CISObject.JobDetails[0].GetType();
1790 // object obj = !vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0] : CISObject.Jobs[0] as object : CISObject.JobDetails[0] as object;
1791 // var propvalue = prop.GetValue(obj, null);
1792 // TextValue = TextValue.Replace(column, propvalue.ToString()).Replace("Job_Option_Details.", "").Replace("Jobs", "").Replace("Files", "").Replace("{{{", "").Replace("}}}", "");
1793 // }
1794 // else if (vars.Contains("RecordDetailsV2"))
1795 // {
1796 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else only"));
1797 // string column = vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1798 // TextValue = TextValue.Replace(column, Row[column].ToString()).ToString().Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1799 // }
1800
1801 // //string column = vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1802 // //if (String.IsNullOrEmpty(TextValue))
1803 // // TextValue = vari.value;
1804
1805 // //TextValue = TextValue.Replace(column, Row[column].ToString()).ToString().Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1806 // }
1807 // catch
1808 // {
1809
1810 // }
1811
1812 // }
1813 // //string columnname = vari.value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1814 // //TextValue = Row[columnname].ToString() as string;
1815 // }
1816 // else
1817 // {
1818 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else only"));
1819
1820 // TextValue = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "") : ((Racami.Common.variables)vari).value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1821 // }
1822 // }
1823 // }
1824 // else
1825 // {
1826 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else t: ={0}=", t)); //debugging only
1827 // TextValue = Racami.TextSubstitute.Substitute.Convert(vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value, CISObject, Row);
1828
1829 // //string ttt = t.Replace("}}}{{{", "#");
1830 // //string[] temps = ttt.Split('#');
1831 // //foreach (var vars in temps)
1832 // //{
1833 // // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("vars is ={0}=", vars.ToString())); //for debugging only
1834 // // //TextValue += " " + Row[vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "")] as string;
1835 // // //Removed space 03-18-2018, not sure what that is for. It is adding indentation in citystatezip combination\
1836 // // if (count <= 1)
1837 // // TextValue += "" + Row[vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "")].ToString() as string;
1838 // // else
1839 // // TextValue += " " + Row[vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "")].ToString() as string;
1840 // // count++;
1841 // //}
1842
1843 // }
1844 // }
1845 // }
1846 // else if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("}}}{{{") : ((Racami.Common.variables)vari).value.Contains("}}}{{{")) //regular line
1847 // {
1848 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else vari value contains }}}{{{"));
1849 // // string temppp = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Replace("}}}{{{", "#") : ((Racami.Common.variables)vari).value.Replace("}}}{{{", "#");
1850 // TextValue = Racami.TextSubstitute.Substitute.Convert(vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value, CISObject, Row);
1851 // //string[] temps = temppp.Split('#');
1852 // //foreach (var vars in temps)
1853 // //{
1854 // // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("vars is ={0}=", vars.ToString())); //for debugging only
1855 // // //TextValue += " " + Row[vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "")] as string;
1856 // // //Removed space 03-18-2018, not sure what that is for. It is adding indentation in citystatezip combination\
1857 // // if (count <= 1)
1858 // // {
1859 // // if (vars.Contains("{{{"))
1860 // // {
1861 // // int iii = vars.IndexOf("{{{");
1862 // // string ff = vars.Substring(iii);
1863 // // TextValue += vars.Substring(0, iii);
1864 // // TextValue += "" + Row[ff.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "")].ToString() as string;
1865 // // }
1866
1867
1868 // // }
1869 // // else
1870 // // TextValue += " " + Row[vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "").Replace(" ", "").Replace("nbsp;", "")].ToString() as string;
1871 // // count++;
1872 // //}
1873 // }
1874
1875 // else
1876 // {
1877
1878 // if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("{{{") : ((Racami.Common.variables)vari).value.Contains("{{{"))
1879 // {
1880 // string temppp = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Replace("{{{", "#").Replace("}}}", "#") : ((Racami.Common.variables)vari).value.Replace("{{{", "#").Replace("}}}", "#");
1881 // string[] temps = temppp.Split('#');
1882 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("new text values");
1883 // foreach (var vars in temps)
1884 // {
1885 // try
1886 // {
1887 // if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("Job_Option_Details") ||
1888 //((Racami.Common.customTexts)vari).value.Contains("Jobs") || ((Racami.Common.customTexts)vari).value.Contains("Files") : ((Racami.Common.variables)vari).value.Contains("Job_Option_Details") || ((Racami.Common.variables)vari).value.Contains("Jobs") || ((Racami.Common.variables)vari).value.Contains("Files"))
1889 // {
1890 // if (CISObject.JobDetails == null && CISObject.Jobs == null && CISObject.Files == null)
1891 // throw new Exception("The job , option or file must be populated to process the substitutions");
1892 // string column = vars.ToLower().Replace("job_option_details.", "").Replace("jobs.", "").Replace("files.", "").Replace("}}}", "");
1893
1894 // List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(!vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0].GetType().GetProperties() : CISObject.Jobs[0].GetType().GetProperties() : CISObject.JobDetails[0].GetType().GetProperties());
1895 // System.Reflection.PropertyInfo prop = info.Find(p => p.Name.ToLower() == column);
1896 // if (prop == null)
1897 // throw new Exception("Substitution value is not supported " + (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value));
1898 // Type tt = !vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0].GetType() : CISObject.Jobs[0].GetType() : CISObject.JobDetails[0].GetType();
1899 // object obj = !vars.Contains("Job_Option_Details") ? !vars.Contains("Jobs") ? CISObject.Files[0] : CISObject.Jobs[0] as object : CISObject.JobDetails[0] as object;
1900 // var propvalue = prop.GetValue(obj, null);
1901 // TextValue += vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Replace(column, propvalue.ToString()).Replace("Job_Option_Details.", "").Replace("Jobs", "").Replace("Files", "").Replace("{{{", "").Replace("}}}", "") :
1902 // ((Racami.Common.variables)vari).value.Replace(column, propvalue.ToString()).Replace("Job_Option_Details.", "").Replace("Jobs", "").Replace("Files", "").Replace("{{{", "").Replace("}}}", "");
1903 // }
1904 // else if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("RecordDetailsV2") : ((Racami.Common.variables)vari).value.Contains("RecordDetailsV2"))
1905 // {
1906 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else only"));
1907 // string column = vars.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1908 // TextValue += vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Replace(column, Row[column].ToString()).ToString().Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "") :
1909 // ((Racami.Common.variables)vari).value.Replace(column, Row[column].ToString()).ToString().Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1910 // }
1911 // else
1912 // TextValue += vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value;
1913
1914 // }
1915 // catch
1916 // {
1917 // //TextValue += vars;
1918 // }
1919
1920 // }
1921 // //string columnname = vari.value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1922 // //TextValue = Row[columnname].ToString() as string;
1923 // }
1924 // else
1925 // {
1926 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else only"));
1927
1928 // if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("Job_Option_Details") ||
1929 // ((Racami.Common.customTexts)vari).value.Contains("Jobs") || ((Racami.Common.customTexts)vari).value.Contains("Files") : ((Racami.Common.variables)vari).value.Contains("Job_Option_Details") || ((Racami.Common.variables)vari).value.Contains("Jobs") || ((Racami.Common.variables)vari).value.Contains("Files"))
1930 // {
1931 // if (CISObject.JobDetails == null && CISObject.Jobs == null && CISObject.Files == null)
1932 // throw new Exception("The job , option or file must be populated to process the substitutions");
1933 // string table = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value;
1934 // List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(!table.Contains("Job_Option_Details") ? !table.Contains("Jobs") ? CISObject.Files[0].GetType().GetProperties() : CISObject.Jobs[0].GetType().GetProperties() : CISObject.JobDetails[0].GetType().GetProperties());
1935 // System.Reflection.PropertyInfo prop = info.Find(p => p.Name.ToLower() == table.ToLower().Replace("{{{job_option_details.", "").Replace("{{{jobs.", "").Replace("{{{files.", "").Replace("}}}", ""));
1936 // if (prop == null)
1937 // throw new Exception("Substitution value is not supported " + (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value));
1938 // Type tt = !table.Contains("Job_Option_Details") ? !table.Contains("Jobs") ? CISObject.Files[0].GetType() : CISObject.Jobs[0].GetType() : CISObject.JobDetails[0].GetType();
1939 // object obj = !table.Contains("Job_Option_Details") ? !table.Contains("Jobs") ? CISObject.Files[0] : CISObject.Jobs[0] as object : CISObject.JobDetails[0] as object;
1940 // var propvalue = prop.GetValue(obj, null);
1941 // TextValue = propvalue.ToString();
1942 // }
1943 // else if (vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Contains("RecordDetailsV2") : ((Racami.Common.variables)vari).value.Contains("RecordDetailsV2"))
1944 // {
1945 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("else only"));
1946 // string columnname = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "") :
1947 // ((Racami.Common.variables)vari).value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "");
1948 // TextValue = Row[columnname].ToString() as string;
1949 // }
1950 // else
1951 // TextValue = vari.GetType() == typeof(Racami.Common.customTexts) ? ((Racami.Common.customTexts)vari).value : ((Racami.Common.variables)vari).value;
1952 // }
1953
1954 // }
1955 }
1956 catch (Exception ex)
1957 {
1958 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("ex in substitue: ={0}=", ex));
1959 TextValue = "";
1960 }
1961 #endregion
1962 return TextValue;
1963 }
1964
1965 public List<Racami.Common.variables> Substitute(List<Racami.Common.variables> variables, System.Data.DataRow Row, EngineObject.CISObjects CISObject)
1966 {
1967 List<Racami.Common.variables> retvariables = new List<Racami.Common.variables>();
1968 Racami.Common.variables[] array = new Racami.Common.variables[variables.Count];
1969 variables.CopyTo(array);
1970 List<Racami.Common.variables> varlist = new List<Racami.Common.variables>(array).OrderBy(i => i.styles.position.top).ToList();
1971 Racami.Common.variables[] tarray = new Racami.Common.variables[varlist.Count];
1972 varlist.CopyTo(tarray);
1973 List<Racami.Common.variables> varlist2 = new List<Racami.Common.variables>();
1974 //foreach (Racami.Common.variables vari in tarray)
1975 //{
1976 // if(!string.IsNullOrEmpty(vari?.barcodeType?.ToString()))
1977 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("vari barcode: ={0}=", vari?.barcodeType?.ToString()));
1978 // varlist2.Add(Clone<Common.variables>(vari));
1979 //}
1980
1981 foreach (Racami.Common.variables vari in tarray)
1982 {
1983 varlist2.Add(new Racami.Common.variables()
1984 {
1985 barcodeType = vari.barcodeType,
1986 condition = vari.condition,
1987 id = vari.id,
1988 isComment = vari.isComment,
1989 logic = vari.logic,
1990 page = vari.page,
1991 styles = vari.styles,
1992 type = vari.type,
1993 value = vari.value
1994 });//Clone<Common.customTexts>(vari));
1995 }
1996
1997
1998 int cntr = 0;
1999 foreach (Racami.Common.variables vari in varlist2)
2000 {
2001 Racami.Common.variables variable = new Racami.Common.variables()
2002 {
2003 barcodeType = vari.barcodeType,
2004 font = vari.font,
2005 model = vari.model,
2006 origin = vari.origin,
2007 styles = vari.styles,
2008 type = vari.type,
2009 value = vari.value,
2010 id = vari.id
2011 };
2012
2013 string TextValue = TextAssignment(vari, Row, CISObject);
2014
2015 try { variable.value = String.IsNullOrEmpty(TextValue) ? "" : TextValue.Trim(); }
2016 catch { }
2017
2018 //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("textvalue before empty check: ={0}=", TextValue));
2019 if (String.IsNullOrEmpty(variable.value.Trim()))
2020 {
2021 if (!string.IsNullOrEmpty(variable?.barcodeType?.ToString()))
2022 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("yyy: ={0}= {1}", variable?.barcodeType?.ToString(), String.IsNullOrEmpty(variable.value.Trim()) ? "Empty" : variable.value));
2023 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Variable is empty try to remove at position");
2024 if (cntr < varlist.Count)
2025 {
2026 int cntt = cntr + 1 > varlist2.Count - 1 ? cntr : cntr + 1;
2027
2028 //need to look at the new list
2029 varlist2[cntt].styles.position = vari.styles.position;
2030 //for (int i = cntr; i < cntt; i++)
2031 //{
2032 // cntt = i + 1 > varlist2.Count - 1 ? i : i + 1;
2033 // varlist2[i].styles.position = vari.styles.position;
2034 //}
2035
2036 }
2037
2038 }
2039 else
2040 {
2041 if (!string.IsNullOrEmpty(vari?.barcodeType?.ToString()))
2042 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("zzz: ={0}=", vari?.barcodeType?.ToString()));
2043
2044 retvariables.Add(variable);
2045 }
2046 cntr++;
2047 }
2048
2049 return retvariables;
2050 }
2051
2052 public List<Racami.Common.customTexts> SubstituteText(List<Racami.Common.customTexts> variables, System.Data.DataRow Row, EngineObject.CISObjects CISObject)
2053 {
2054 List<Racami.Common.customTexts> retvariables = new List<Racami.Common.customTexts>();
2055 Racami.Common.customTexts[] array = new Racami.Common.customTexts[variables.Count];
2056 variables.CopyTo(array);
2057 List<Racami.Common.customTexts> varlist = new List<Racami.Common.customTexts>(array).OrderBy(i => i.styles.position.top).ToList();
2058 Racami.Common.customTexts[] tarray = new Racami.Common.customTexts[varlist.Count];
2059 varlist.CopyTo(tarray);
2060 List<Racami.Common.customTexts> varlist2 = new List<Racami.Common.customTexts>();
2061 foreach (Racami.Common.customTexts vari in tarray)
2062 {
2063 varlist2.Add(new Racami.Common.customTexts()
2064 {
2065 barcodeType = vari.barcodeType,
2066 condition = vari.condition,
2067 id = vari.id,
2068 isComment = vari.isComment,
2069 logic = vari.logic,
2070 page = vari.page,
2071 styles = vari.styles,
2072 type = vari.type,
2073 value = vari.value
2074
2075 });//Clone<Common.customTexts>(vari));
2076 }
2077
2078
2079 int cntr = 0;
2080 foreach (Racami.Common.customTexts vari in varlist2)
2081 {
2082 Racami.Common.customTexts variable = new Racami.Common.customTexts()
2083 {
2084 isComment = vari.isComment,
2085
2086 styles = vari.styles,
2087 type = vari.type,
2088 value = vari.value,
2089 barcodeType = vari.barcodeType,
2090 condition = vari.condition,
2091 logic = vari.logic,
2092 id = vari.id,
2093 page = vari.page
2094 };
2095
2096 string TextValue = TextAssignment(vari, Row, CISObject);
2097
2098 if (TextValue.Contains("%RECCOUNT%"))
2099 {
2100 int cnt = (Convert.ToInt32(Row["EndPage"].ToString()) + 1 - Convert.ToInt32(Row["StartPage"].ToString()));
2101 if (Row.Table.Columns.Contains("Plex"))
2102 {
2103 if (!String.IsNullOrEmpty(Row["Plex"]?.ToString()) && Row["Plex"]?.ToString().ToUpper() == "DUPLEX")
2104 cnt = (int)Math.Ceiling(Convert.ToDouble((Convert.ToInt32(Row["EndPage"].ToString()) + 1 - Convert.ToInt32(Row["StartPage"].ToString())) / 2));
2105 }
2106 TextValue = TextValue.Replace("%RECCOUNT%", cnt.ToString());
2107 }
2108 if (TextValue.Contains("%RECSTART%"))
2109 {
2110 int cnt = Convert.ToInt32(RECSTART);
2111 if (Row.Table.Columns.Contains("Plex"))
2112 {
2113 if (!String.IsNullOrEmpty(Row["Plex"]?.ToString()) && Row["Plex"]?.ToString().ToUpper() == "DUPLEX")
2114 if (cnt != 1)
2115 if (cnt != 1)
2116 cnt = (int)Math.Ceiling(Convert.ToDouble(RECSTART) / 2);
2117 }
2118 TextValue = TextValue.Replace("%RECSTART%", cnt.ToString());
2119 }
2120
2121 if (TextValue.Contains("%DOCCOUNT%"))
2122 {
2123 int cnt = (DOCCOUNT);
2124 if (Row.Table.Columns.Contains("Plex"))
2125 {
2126 if (!String.IsNullOrEmpty(Row["Plex"]?.ToString()) && Row["Plex"]?.ToString().ToUpper() == "DUPLEX")
2127 cnt = (int)Math.Ceiling(Convert.ToDouble((DOCCOUNT)) / 2);
2128 }
2129 TextValue = TextValue.Replace("%DOCCOUNT%", cnt.ToString());
2130 }
2131 if (TextValue.Contains("%CURRENTDOC%"))
2132 {
2133 int cnt = Convert.ToInt32(CURRENTDOC);
2134 if (Row.Table.Columns.Contains("Plex"))
2135 {
2136 if (!String.IsNullOrEmpty(Row["Plex"]?.ToString()) && Row["Plex"]?.ToString().ToUpper() == "DUPLEX")
2137 if (cnt != 1)
2138 if (cnt != 1)
2139 cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
2140 }
2141 TextValue = TextValue.Replace("%CURRENTDOC%", cnt.ToString());
2142 }
2143
2144
2145 if (TextValue.Contains("%RECPAGECOUNT%"))
2146 {
2147 // //CISObject.Keys.Add("RECSTART", RECSTART);
2148 TextValue = TextValue.Replace("%RECPAGECOUNT%", (Convert.ToInt32(RECPAGECOUNT).ToString()));
2149 }
2150
2151 try { variable.value = String.IsNullOrEmpty(TextValue) ? "" : TextValue.Trim(); }
2152 catch { }
2153
2154 //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("textvalue before empty check: ={0}=", TextValue));
2155 if (String.IsNullOrEmpty(variable.value.Trim()))
2156 {
2157 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Variable is empty try to remove at position");
2158 if (cntr < varlist.Count)
2159 {
2160 int cntt = cntr + 1 > varlist2.Count - 1 ? cntr : cntr + 1;
2161
2162 //need to look at the new list
2163 varlist2[cntt].styles.position = vari.styles.position;
2164 //for (int i = cntr; i < cntt; i++)
2165 //{
2166 // cntt = i + 1 > varlist2.Count - 1 ? i : i + 1;
2167 // varlist2[i].styles.position = vari.styles.position;
2168 //}
2169
2170 }
2171
2172 }
2173 else
2174 {
2175
2176
2177 retvariables.Add(variable);
2178 }
2179 cntr++;
2180 }
2181
2182 return retvariables;
2183 }
2184 #endregion
2185
2186
2187 protected class InternalFont
2188 {
2189 public PdfFont Font { get; set; }
2190 public String FontName { get; set; }
2191 }
2192 //org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum[] regfonts = (org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum[])Enum.GetValues(typeof(org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum));
2193
2194 List<InternalFont> registeredfonts = new List<InternalFont>();
2195 #region font function
2196 PdfFont GetFont(PdfPage page,
2197 FontFamilyStage font,
2198 string fontstyle = "normal",
2199 string fontWeight = "normal")
2200 {
2201 // org.pdfclown.documents.contents.composition.PrimitiveComposer composer = new org.pdfclown.documents.contents.composition.PrimitiveComposer(page);
2202 // foreach (var item in regfonts)
2203 // {
2204 PdfFont rfont = registeredfonts.Find(f => f.FontName == (font != null ? font.FontName.ToLower() : ""))?.Font;
2205
2206 if (rfont == null)
2207 {
2208
2209
2210 // var t = this.fontDic.ToList().Find(fnt => fnt.ToString().ToLower().Replace("-Roman", "").Contains(font.FontName.Replace(" New Roman", "").Replace("-Roman", "").ToLower()));
2211 FontFamilyStage fnt = fontDic.Find((FontFamilyStage f) => f.FontName.ToLower().Contains(font != null ? font.FontName.ToLower() : ""));
2212 if (fnt == null)
2213 {
2214 rfont = page.GetDocument().GetDefaultFont();
2215 }
2216 else
2217 {
2218 rfont = PdfFontFactory.CreateFont(fontDic.Find((FontFamilyStage f) => f.FontName.ToLower().Contains(font != null ? font.FontName.ToLower() : "")).FontBytes, "CP1252", embedded: true);
2219 }
2220
2221
2222 if (registeredfonts.Find(f => f.FontName == rfont.GetFontProgram().GetFontNames().GetFontName()) == null)
2223 {
2224 registeredfonts.Add(new InternalFont() { FontName = rfont.GetFontProgram().GetFontNames().GetFontName(), Font = rfont });
2225 }
2226
2227 }
2228 //if (t != org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum.NA)
2229 //{
2230 // string fontname = t.ToString() + fontstyle + fontWeight;
2231 // if (registeredfonts.Find(rgf => rgf.FontName.Replace("-Roman", "") == fontname) != null)
2232 // {
2233 // return registeredfonts.Find(rgf => rgf.FontName.Replace("-Roman", "") == t.ToString() + fontstyle + fontWeight).Font;
2234 // }
2235 // else
2236 // {
2237 // org.pdfclown.documents.contents.fonts.Font fntt = new org.pdfclown.documents.contents.fonts.StandardType1Font(
2238 // page.Document,
2239 // t,
2240 // fontWeight == "bold" ? true : false,
2241 // fontstyle == "italic" ? true : false
2242 // );
2243 // registeredfonts.Add(new InternalFont() { Font = fntt, FontName = t.ToString() + fontstyle + fontWeight });
2244 // return fntt;
2245 // }
2246 // // return ;
2247 //}
2248 //else
2249 //{
2250 //if (registeredfonts.Find(rgf => rgf.FontName.Replace("-Roman", "").ToLower() == font.FontName.Replace(" New Roman", "").Replace("-Roman", "").ToLower()) != null)
2251 //{
2252 // return registeredfonts.Find(rgf => rgf.FontName.Replace("-Roman", "").ToLower() == font.FontName.Replace(" New Roman", "").Replace("-Roman", "").ToLower()).Font;
2253 //}
2254 //else
2255 //{
2256 // string fontDir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "fonts");
2257 // org.pdfclown.documents.contents.fonts.Font fntt = org.pdfclown.documents.contents.fonts.Font.Get(page.Document, new org.pdfclown.bytes.Stream(new System.IO.MemoryStream(font.FontBytes)));// System.IO.Path.Combine(fontDir, font.FontName + ".ttf"));
2258 // registeredfonts.Add(new InternalFont() { Font = fntt, FontName = font.FontName });
2259 // return fntt;
2260 //}
2261 // }
2262
2263 return rfont;
2264 }
2265
2266
2267 #endregion
2268 #region extended
2269
2270 public float setOffset(float fontSize)
2271 {
2272 if (fontSize > 20f)
2273 {
2274 return 5f;
2275 }
2276 if ((double)fontSize > 17.5)
2277 {
2278 return 4.25f;
2279 }
2280 if (fontSize > 15f)
2281 {
2282 return 3.5f;
2283 }
2284 if ((double)fontSize > 12.5)
2285 {
2286 return 2.75f;
2287 }
2288 if (fontSize > 10f)
2289 {
2290 return 2f;
2291 }
2292 if ((double)fontSize > 7.5)
2293 {
2294 return 1.25f;
2295 }
2296 if (fontSize > 5f)
2297 {
2298 return 0.5f;
2299 }
2300 return 0.25f;
2301 }
2302
2303 public void AddText(PdfPage page,
2304 string Text,
2305 int x,
2306 int y,
2307 int width,
2308 int height,
2309 DeviceRgb col,
2310 int fontsize,
2311 FontFamilyStage font,
2312 string fontstyle = "normal",
2313 string fontWeight = "normal",
2314 int rot = 0)
2315 {
2316 float[] rott = GetRotation(page, x, y, width, height, rot);
2317 float newx = rott[0];
2318 float newy = rott[1];
2319 float rrot = rott[2];
2320 float rotation = rott[3];
2321 PdfCanvas pdfCanvas = new PdfCanvas(page, true);// new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2322 PdfFont pdfFont = GetFont(page, font);
2323 try
2324 {
2325 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(pdfFont.GetFontProgram().GetFontNames().GetFontName() + " is currently used");
2326 if (rotation == 0)
2327 {
2328 pdfCanvas.SetLineWidth(0f);
2329 if (col == DeviceRgb.BLACK)
2330 {
2331 pdfCanvas.SetStrokeColor(new DeviceCmyk(0, 0, 0, 255));
2332 pdfCanvas.SetFillColor(new DeviceCmyk(0, 0, 0, 255));
2333 }
2334 else
2335 {
2336 pdfCanvas.SetStrokeColor(col);
2337 pdfCanvas.SetFillColor(col);
2338 }
2339
2340 pdfCanvas.FillStroke();
2341 float num = setOffset(fontsize);
2342 pdfCanvas.BeginText();
2343 pdfCanvas.SetFontAndSize(pdfFont, fontsize);
2344 pdfCanvas.MoveText(newx, newy).ShowText(Text);
2345 pdfCanvas.EndText();
2346 }
2347 else
2348 {
2349 float angle = (float)(Math.PI * 3) / 2;// angle = 4.712389f;
2350 //angle = rrot;
2351 switch (rotation)
2352 {
2353 case 90:
2354 if (rotation == 270)
2355 angle = (float)Math.PI;
2356 else if (rotation == 180)
2357 angle = (float)Math.PI * 2;
2358 else if (rotation == 90)
2359 angle = (float)Math.PI / 2f;
2360 //angle = (float)Math.PI / 2f;
2361 break;
2362 case 270:
2363 if (rotation == 0)
2364 angle = (float)Math.PI / 2;
2365 else if (rotation == 270)
2366 angle = (float)(Math.PI * 3) / 2;
2367 else if (rotation == 90)
2368 angle = (float)Math.PI;
2369 break;
2370 case 180:
2371 if (rotation == 270)
2372 angle = (float)Math.PI;
2373 else if (rotation == 180)
2374 angle = (float)Math.PI * 2;
2375 else if (rotation == 90)
2376 angle = (float)Math.PI / 2f;
2377 angle = (float)Math.PI;
2378 break;
2379 }
2380
2381 Canvas c = new Canvas(pdfCanvas, page.GetDocument(), new iText.Kernel.Geom.Rectangle(newx, newy)).SetFont(pdfFont).SetFontSize(fontsize);
2382 if (col.GetColorValue()[0] == 0 && col.GetColorValue()[1] == 0 && col.GetColorValue()[2] == 0)
2383 c.SetFontColor(new DeviceCmyk(0, 0, 0, 255));
2384 else
2385 c.SetFontColor(col);
2386
2387 c.ShowTextAligned(Text, newx, newy, TextAlignment.CENTER, VerticalAlignment.MIDDLE, angle);
2388 c.Close();
2389 //pdfCanvas2.Release();
2390 }
2391 }
2392 catch (Exception)
2393 {
2394 }
2395 pdfCanvas.Fill();
2396 pdfCanvas.Release();
2397 //page.SetRotation(Convert.ToInt32(rotation));
2398 //org.pdfclown.documents.contents.fonts.Font fonts = this.GetFont(page, font, fontstyle, fontWeight);
2399
2400 //org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2401 //stamper.Page = page;
2402
2403 //org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
2404
2405 //composer.SetFont(fonts, fontsize);
2406 //composer.SetFillColor(col);// org.pdfclown.documents.contents.colorSpaces.DeviceRGBColor.Get(System.Drawing.Color.Blue));
2407
2408 //int irot = 180;
2409 //if (rot == 90)
2410 // irot = 270;
2411 //else if (rot == 270)
2412 // irot = 90;
2413 //else if (rot == 180)
2414 // irot = 180;
2415 //else
2416 // irot = 0;
2417
2418 //composer.ShowText(Text, new System.Drawing.PointF(newx, newy),
2419 // org.pdfclown.documents.contents.composition.XAlignmentEnum.Left,
2420 // org.pdfclown.documents.contents.composition.YAlignmentEnum.Middle, irot);
2421
2422
2423 // org.pdfclown.documents.interaction.annotations.CalloutNote calloutNote = new org.pdfclown.documents.interaction.annotations.CalloutNote(
2424 //page,
2425 //new System.Drawing.Rectangle(50, 500, 100, 30),
2426 //"Caret annotation"
2427 //);
2428 // calloutNote.Justification = org.pdfclown.documents.interaction.JustificationEnum.Right;
2429 // calloutNote.Line = new org.pdfclown.documents.interaction.annotations.CalloutNote.LineObject(
2430 // page,
2431 // new System.Drawing.Point(150, 650),
2432 // new System.Drawing.Point(100, 600),
2433 // new System.Drawing.Point(50, 100)
2434 // );
2435 // // caret.SymbolType = org.pdfclown.documents.interaction.annotations.Caret.SymbolTypeEnum.NewParagraph;
2436
2437 // org.pdfclown.documents.interaction.annotations.Scribble scri = new org.pdfclown.documents.interaction.annotations.Scribble(
2438 // page,
2439 // new System.Drawing.RectangleF(50, 300, 100, 30),
2440 // Text,
2441 // new List<IList<System.Drawing.PointF>>(
2442 // new List<System.Drawing.PointF>[]
2443 // {
2444 // new List<System.Drawing.PointF>(
2445 // new System.Drawing.PointF[]
2446 // {
2447 // new System.Drawing.PointF(50,300),
2448 // new System.Drawing.PointF(70,310),
2449 // new System.Drawing.PointF(100,320)
2450 // }
2451 // )
2452 // }
2453 // )
2454 // );
2455 //scri.Name = "Title";
2456
2457
2458 //composer.Flush();
2459 //stamper.Flush();
2460 }
2461
2462
2463 float[] GetRotation(PdfPage page, int x,
2464 int y,
2465 int width,
2466 int height, int rot)
2467 {
2468
2469 float newx = x;
2470 float newy = y;
2471 float radrot = 4.712389f;
2472 float rotation = rot;
2473
2474
2475 try
2476 {
2477
2478 /*
2479 case 90:
2480 angle = (float)Math.PI / 2f;
2481 break;
2482 case 270:
2483 angle = (float)Math.PI*2;
2484 break;
2485 case 180:
2486 angle = (float)Math.PI;
2487 */
2488 page.SetIgnorePageRotationForContent(true);
2489 switch (page.GetRotation())//Rotation)
2490 {
2491 case 0:
2492 newx = x;
2493 newy = y;
2494 rotation = rot;
2495 break;
2496 case 180:
2497 newx = x;
2498 newy = y;
2499 if (rotation != 0)
2500 rotation = rot + 90;
2501 radrot = (float)Math.PI;
2502 break;
2503 case 270:
2504 newx = x;
2505 newy = y;// (int)page.GetPageSizeWithRotation().GetHeight() - (((int)page.GetPageSizeWithRotation().GetWidth() - x));//page.SetRotation(0);
2506 // newx = ((int)page.GetPageSizeWithRotation().GetHeight() - y)- height;
2507 //newy = y;// ((int)page.GetPageSizeWithRotation().GetHeight() - x) - 42;
2508 radrot = (float)Math.PI * 2;
2509 if (rotation != 0)
2510 rotation = rot + 180;
2511 break;
2512 //case org.pdfclown.documents.contents.RotationEnum.Upward:
2513 // newx = x;
2514 // newy = y;
2515 // break;
2516 case 90:
2517 newx = x;
2518 newy = y;
2519 // page.SetRotation(0);
2520 // newx = ((int)page.GetPageSizeWithRotation().GetWidth() - y) - 42;
2521
2522 radrot = (float)Math.PI / 2f;
2523 if (rotation != 0)
2524 rotation = rot + 270;
2525 break;
2526 default:
2527 newx = x;
2528 newy = y;
2529
2530 break;
2531 }
2532 }
2533 catch
2534 {
2535
2536 }
2537
2538 return new float[] { newx, newy, radrot, rotation };
2539 }
2540 public void AddRectangle(PdfPage page,
2541
2542 int x,
2543 int y,
2544 int width,
2545 int height, DeviceRgb col)
2546 {
2547 int rot = 0;
2548 float[] rott = GetRotation(page, x, y, width, height, rot);
2549 float newx = rott[0];
2550 float newy = rott[1];
2551 float rrot = rott[2];
2552 float pagerot = rott[3];
2553
2554 PdfCanvas canvas = new PdfCanvas(page, true);// new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2555 // Color borderColor
2556 canvas.SetLineWidth(0);
2557 canvas.SetStrokeColor(col);
2558 canvas.SetFillColor(col);
2559 // if (pagerot == 270)
2560 canvas.Rectangle(newx, newy, width, height);
2561 // else
2562 // canvas.Rectangle(newx, newy, width, height);
2563 canvas.FillStroke();
2564 canvas.SetStrokeColor(col);
2565 canvas.Fill();
2566 canvas.Release();
2567 //org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2568 //stamper.Page = page;
2569
2570 //org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
2571
2572 //composer.SetFillColor(col);
2573 //composer.DrawRectangle(
2574 // new System.Drawing.RectangleF(
2575 // newx, newy, width, height
2576 // )
2577 // );
2578 //composer.Fill();
2579 //stamper.Flush();
2580
2581 }
2582
2583
2584 public void AddHyperLink(PdfPage page,
2585
2586 int x,
2587 int y,
2588 int width,
2589 int height, DeviceRgb col, string url, bool addtext = false, Document doc = null)
2590 {
2591 int rot = 0;
2592 float[] rott = GetRotation(page, x, y, width, height, rot);
2593 float newx = rott[0];
2594 float newy = rott[1];
2595 float rotation = rott[2];
2596 // Document doc = new Document(page.GetDocument());
2597 PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2598 if (addtext)
2599 {
2600 PdfFont font = PdfFontFactory.CreateFont("Helvetica");
2601 Link link = new Link(url, PdfAction.CreateURI(url));
2602 link.SetFont(font);
2603 link.SetUnderline();
2604 Paragraph paragraph = new Paragraph();
2605 paragraph.Add(link);
2606 doc.ShowTextAligned(paragraph, x, y, TextAlignment.LEFT);
2607 }
2608 else
2609 {
2610 PdfAnnotation annotation = new PdfLinkAnnotation(new iText.Kernel.Geom.Rectangle(newx, newy, width, height))
2611 .SetHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT)
2612 .SetAction(PdfAction.CreateURI(url)).SetBorder(new PdfArray(new int[3]
2613 {
2614 0,
2615 0,
2616 1
2617 }));
2618 page.AddAnnotation(annotation);
2619 }
2620 // org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2621 // stamper.Page = page;
2622
2623 // org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
2624 // composer.SetFillColor(col);
2625
2626 // if (addtext)
2627 // {
2628 // composer.ShowText(
2629 // url,
2630 // new System.Drawing.PointF(newx, newy),
2631 // org.pdfclown.documents.contents.composition.XAlignmentEnum.Left,
2632 // org.pdfclown.documents.contents.composition.YAlignmentEnum.Bottom,
2633 // -90,
2634 // new org.pdfclown.documents.interaction.actions.GoToURI(
2635 // page.Document,
2636 // new Uri(url)
2637 // )
2638 // );
2639 // }
2640 // else
2641 // {
2642 // Link link = new Link(
2643 // page,
2644 // new System.Drawing.RectangleF(newx, newy, width, height),
2645 //url,
2646 // new org.pdfclown.documents.interaction.actions.GoToURI(
2647 // page.Document,
2648 // new Uri(url)
2649 // )
2650 // );
2651 // }
2652
2653 // //composer.DrawRectangle(
2654 // // new System.Drawing.RectangleF(
2655 // // x, y, width, height
2656 // // )
2657 // // );
2658 // composer.Fill();
2659 // composer.Flush(); //composer.End();
2660
2661
2662 }
2663
2664
2665
2666 //public void AddIMBFont(PdfPage page,
2667 // string Text,
2668 // int x,
2669 // int y,
2670 // int width,
2671 // int height,
2672 // DeviceRgb col,
2673 // int fontsize,
2674 // FontFamilyStage font,
2675 // string fontstyle = "normal",
2676 // string fontWeight = "normal",
2677 // int rot = 0)
2678 //{
2679
2680 // org.pdfclown.documents.contents.fonts.Font fonts = this.GetFont(page, font, fontstyle, fontWeight);
2681
2682 // org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2683 // stamper.Page = page;
2684 // System.IO.MemoryStream stream = new System.IO.MemoryStream();
2685 // org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
2686 // ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter();
2687 // writer.Format = ZXing.BarcodeFormat.IMB;
2688 // writer.Options = new ZXing.Common.EncodingOptions() { PureBarcode = true, Height = height, Width = width };
2689 // writer.Write(Text).Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
2690 // Image image = Image.Get(stream);
2691 // org.pdfclown.documents.contents.xObjects.XObject imageXObject = image.ToXObject(page.Document);
2692
2693
2694 // System.Drawing.SizeF pageSize = page.Size;
2695 // // org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2696 // // stamper.Page = page;
2697 // PrimitiveComposer composers = stamper.Foreground;
2698 // {
2699 // BlockComposer blockComposers = new BlockComposer(composers);
2700 // blockComposers.Hyphenation = true;
2701 // blockComposers.Begin(
2702 // new System.Drawing.RectangleF(
2703 // x,
2704 // y,
2705 // (float)width * 4,
2706 // (float)height * 2
2707 // ),
2708 // XAlignmentEnum.Justify,
2709 // YAlignmentEnum.Top
2710 // );
2711 // org.pdfclown.documents.contents.fonts.StandardType1Font bodyFont = new org.pdfclown.documents.contents.fonts.StandardType1Font(
2712 // page.Document,
2713 // org.pdfclown.documents.contents.fonts.StandardType1Font.FamilyEnum.Courier,
2714 // true,
2715 // false
2716 // );
2717 // composers.SetFont(bodyFont, fontsize);
2718 // blockComposers.ShowText(Text);
2719 // blockComposers.End();
2720
2721 // composers.Flush();
2722 // }
2723
2724
2725
2726
2727 // stamper.Flush();
2728 //}
2729
2730
2731 public void AddIMB(string bars, PdfPage page, int x,
2732 int y,
2733 int width,
2734 int height, int rot = 0, int fontsize = 6)
2735 {
2736 float[] rott = GetRotation(page, x, y, width, height, rot);
2737 float newx = rott[0];
2738 float newy = rott[1];
2739 float rrot = rott[2];
2740
2741 string imbchars = "ADFT";
2742 for (int i = 0; i < bars.Length; i++)
2743 {
2744 if (imbchars.IndexOf(bars[i]) == -1)
2745 {
2746 throw new Exception("Invalid Character/s found in IMB Barcode.");
2747 }
2748 }
2749
2750 if (bars.Any(char.IsDigit))
2751 throw new Exception("IMB Barcode value contains number.");
2752
2753 if (!bars.Length.Equals(65))
2754 throw new Exception("IMB Barcode length should be 65 characters, your barcode count is : " + bars.Length.ToString());
2755
2756 float Margin = 36;
2757 PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2758 // org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2759 // stamper.Page = page;
2760 // System.IO.MemoryStream stream = new System.IO.MemoryStream();
2761 // org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
2762
2763 //IMB.IMBBarcode barcode = new IMB.IMBBarcode(pdfCanvas);
2764 //barcode.X = newx;
2765 //barcode.Y = newy;
2766 //barcode.Codebars = bars;
2767 //barcode.Width = width;
2768 //barcode.Height = height;
2769 //barcode.Apply();
2770
2771 // composer.Flush();
2772 //stream.Dispose();
2773 //stamper.Flush();
2774
2775 //PdfFontFactory.CreateFont(System.IO.Path.Combine(path2, fnt2.FontName + ".ttf"), "CP1252", embedded: true);
2776 PdfFont pdfFont = PdfFontFactory.CreateFont(fontDic.Find((FontFamilyStage f) => f.FontName.ToLower().Contains("imb")).FontBytes, "CP1252", embedded: true);
2777 try
2778 {
2779 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(pdfFont.GetFontProgram().GetFontNames().GetFontName() + " is currently used");
2780 if (rot == 0)
2781 {
2782 pdfCanvas.SetLineWidth(0f);
2783 pdfCanvas.SetStrokeColor(DeviceRgb.BLACK);
2784 pdfCanvas.SetFillColor(DeviceRgb.BLACK);
2785 pdfCanvas.FillStroke();
2786 float num = setOffset(fontsize);
2787 pdfCanvas.BeginText();
2788 pdfCanvas.SetFontAndSize(pdfFont, fontsize);
2789 pdfCanvas.MoveText(newx, newy).ShowText(bars);
2790 pdfCanvas.EndText();
2791 }
2792 else
2793 {
2794 float angle = 4.712389f;
2795 switch (rot)
2796 {
2797 case 90:
2798 angle = (float)Math.PI / 2f;
2799 break;
2800 case 180:
2801 angle = (float)Math.PI;
2802 break;
2803 }
2804 PdfCanvas pdfCanvas2 = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2805 new Canvas(pdfCanvas2, page.GetDocument(), new iText.Kernel.Geom.Rectangle(newx, newy)).SetFont(pdfFont).SetFontSize(fontsize).SetFontColor(DeviceRgb.BLACK)
2806 .ShowTextAligned(bars, newx, newy, TextAlignment.CENTER, VerticalAlignment.MIDDLE, angle)
2807 .Close();
2808 }
2809 }
2810 catch (Exception)
2811 {
2812 }
2813 pdfCanvas.Fill();
2814 pdfCanvas.Release();
2815
2816 }
2817
2818 public void Add128(string Data, PdfPage page, int x,
2819 int y,
2820 int width,
2821 int height, DeviceRgb col, int rot = 0, int fontsize = 6)
2822 {
2823 float[] rott = GetRotation(page, x, y, width, height, rot);
2824 float newx = rott[0];
2825 float newy = rott[1];
2826 float rrot = rott[2];
2827
2828
2829 PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2830 Barcode1D barcode1D = new Barcode128(page.GetDocument());
2831 barcode1D.SetCodeType(1);
2832 barcode1D.SetSize(fontsize);
2833 barcode1D.SetFont(null);
2834 barcode1D.SetCode(Data);
2835 pdfCanvas.AddXObject(barcode1D.CreateFormXObject(col, col, page.GetDocument()), newx, newy);
2836 //float Margin = 36;
2837 //org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2838 //stamper.Page = page;
2839 //System.IO.MemoryStream stream = new System.IO.MemoryStream();
2840 //org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
2841 //ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter();
2842 //writer.Format = ZXing.BarcodeFormat.CODE_128;
2843 //writer.Options = new ZXing.Common.EncodingOptions() { PureBarcode = true, Height = height * 2, Width = width * 2 };
2844 //writer.Write(Data).Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
2845 //// System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(stream);
2846 ////bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
2847 //Image image = Image.Get(stream);
2848 //org.pdfclown.documents.contents.xObjects.XObject imageXObject = image.ToXObject(page.Document);
2849 //composer.ShowXObject(
2850 // imageXObject,
2851 // new System.Drawing.PointF(newx, newy)
2852
2853 // );
2854
2855 ///*
2856 // ,
2857 // org.pdfclown.util.math.geom.GeomUtils.Scale(imageXObject.Size, new System.Drawing.SizeF(fontsize, 0)),
2858 // org.pdfclown.documents.contents.composition.XAlignmentEnum.Right,
2859 // org.pdfclown.documents.contents.composition.YAlignmentEnum.Bottom,
2860 // rot
2861 // */
2862 //composer.Flush();
2863 //stream.Dispose();
2864 //stamper.Flush();
2865 }
2866
2867 public void Add3of9(string Data, PdfPage page, int x,
2868 int y,
2869 int width,
2870 int height, DeviceRgb col, int rot = 0, int fontsize = 6)
2871 {
2872 float[] rott = GetRotation(page, x, y, width, height, rot);
2873 float newx = rott[0];
2874 float newy = rott[1];
2875 float rrot = rott[2];
2876
2877 PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2878 Barcode1D barcode1D = new Barcode39(page.GetDocument());
2879 barcode1D.SetCode(Data);
2880 barcode1D.SetTextAlignment(1);
2881 if (rrot != 0)
2882 {
2883 Document document = new Document(page.GetDocument());
2884 iText.Kernel.Geom.Rectangle barcodeSize = barcode1D.GetBarcodeSize();
2885 PdfFormXObject xObject = new PdfFormXObject(new iText.Kernel.Geom.Rectangle(barcodeSize.GetWidth(), barcodeSize.GetHeight() + 10f));
2886 barcode1D.PlaceBarcode(pdfCanvas, col, col);
2887 iText.Layout.Element.Image image = new iText.Layout.Element.Image(xObject);
2888 //float num = 4.712389f;
2889 //switch (rot)
2890 //{
2891 // case 90:
2892 // num = (float)Math.PI / 2f;
2893 // break;
2894 // case 180:
2895 // num = (float)Math.PI;
2896 // break;
2897 //}
2898 image.SetRotationAngle(rrot);
2899 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"measurements: height ={height}=, width ={width}=");
2900 document.Add(image);
2901 }
2902 else
2903 {
2904 pdfCanvas.AddXObject(barcode1D.CreateFormXObject(col, col, page.GetDocument()), newx, newy);
2905 }
2906 //float Margin = 36;
2907 //org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
2908 //stamper.Page = page;
2909 //System.IO.MemoryStream stream = new System.IO.MemoryStream();
2910 //org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
2911 //ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter();
2912 //writer.Format = ZXing.BarcodeFormat.CODE_39;
2913 //writer.Options = new ZXing.Common.EncodingOptions() { PureBarcode = true, Width = width * 2, Height = height * 2 };
2914 //writer.Write(Data.ToUpper()).Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
2915 //Image image = Image.Get(stream);
2916 //org.pdfclown.documents.contents.xObjects.XObject imageXObject = image.ToXObject(page.Document);
2917 //composer.ShowXObject(
2918 // imageXObject,
2919 // new System.Drawing.PointF(newx, newy)
2920
2921 // );
2922 //composer.Flush();
2923 //stream.Dispose();
2924 //stamper.Flush();
2925 }
2926
2927
2928 private System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, System.Drawing.Size size)
2929 {
2930 int sourceWidth = imgToResize.Width;
2931 int sourceHeight = imgToResize.Height;
2932
2933 float nPercent = 0;
2934 float nPercentW = 0;
2935 float nPercentH = 0;
2936
2937 nPercentW = ((float)size.Width / (float)sourceWidth);
2938 nPercentH = ((float)size.Height / (float)sourceHeight);
2939
2940 if (nPercentH < nPercentW)
2941 nPercent = nPercentH;
2942 else
2943 nPercent = nPercentW;
2944
2945 int destWidth = (int)(sourceWidth * nPercent);
2946 int destHeight = (int)(sourceHeight * nPercent);
2947
2948 System.Drawing.Bitmap b = new System.Drawing.Bitmap(destWidth, destHeight);
2949 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage((System.Drawing.Image)b);
2950 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
2951
2952 g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
2953 g.Dispose();
2954
2955 return (System.Drawing.Image)b;
2956 }
2957
2958 public void AddDataMatrix(string Data, PdfPage page, int x,
2959 int y,
2960 int width,
2961 int height, DeviceRgb col, int rot = 0, int fontsize = 6)
2962 {
2963 float[] rott = GetRotation(page, x, y, width, height, rot);
2964 float newx = rott[0];
2965 float newy = rott[1];
2966 float rrot = rott[2];
2967 float rotation = rott[3];
2968
2969 float Margin = 36;
2970 if (String.IsNullOrEmpty(Data))
2971 return;
2972
2973 if (page == null)
2974 {
2975 throw new Exception("page object was null this is fatal");
2976 }
2977 PdfCanvas pdfCanvas = new PdfCanvas(page, true);// new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
2978 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("New canvas created == " + ((pdfCanvas == null) ? "false" : "true"));
2979 BarcodeDataMatrix barcodeDataMatrix = new BarcodeDataMatrix();
2980 barcodeDataMatrix.SetOptions(BarcodeDataMatrix.DM_AUTO);
2981
2982 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("New barcode object created == " + ((barcodeDataMatrix == null) ? "false" : "true"));
2983 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"height is {height}");
2984 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"width is {width}");
2985
2986 if (string.IsNullOrEmpty(Data))
2987 {
2988 throw new Exception("Data object was null this is fatal");
2989 }
2990
2991 int[] barcodeDimensions = { 10, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44, 48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
2992
2993 if ((Data.Length - fontsize) > 9)
2994 throw new Exception("Data matrix barcode value cannot be larger than 9 characters from the font size.");
2995
2996 if (!barcodeDimensions.Contains(fontsize))
2997 throw new Exception("Font size not supported.");
2998
2999 bool generate = false;
3000 for (int generateCount = 0; generateCount < barcodeDimensions.Length; generateCount++)
3001 {
3002 barcodeDataMatrix.SetWidth(barcodeDimensions[generateCount]);
3003 barcodeDataMatrix.SetHeight(barcodeDimensions[generateCount]);
3004 int returnResult = barcodeDataMatrix.SetCode(Data);
3005 if (returnResult == BarcodeDataMatrix.DM_NO_ERROR)
3006 {
3007 generate = true;
3008 break;
3009 }
3010 }
3011
3012 if (generate)
3013 {
3014 barcodeDataMatrix.SetCode(Data);
3015
3016 pdfCanvas.AddXObject(barcodeDataMatrix.CreateFormXObject(new DeviceCmyk(0, 0, 0, 255), page.GetDocument()), newx, newy);
3017
3018 }
3019
3020 pdfCanvas.Fill();
3021 pdfCanvas.Release();
3022 // page.SetRotation(Convert.ToInt32(rotation));
3023 //org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
3024 //stamper.Page = page;
3025
3026 //// IronBarCode.GeneratedBarcode generatedBarcode= IronBarCode.BarcodeWriter.CreateBarcode(Data, IronBarCode.BarcodeEncoding.DataMatrix, fontsize, fontsize);
3027 //System.IO.MemoryStream stream = new System.IO.MemoryStream();
3028 //org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
3029 //ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter();
3030 //writer.Options = new ZXing.Datamatrix.DatamatrixEncodingOptions
3031 //{
3032 // SymbolShape = ZXing.Datamatrix.Encoder.SymbolShapeHint.FORCE_SQUARE,
3033 // PureBarcode = true,
3034 // Margin = 0
3035
3036 //}; //
3037
3038 //// writer.Options = new ZXing.Common.EncodingOptions() { PureBarcode = true, Height = height, Width = width };
3039 //writer.Format = ZXing.BarcodeFormat.DATA_MATRIX;
3040
3041 //ZXing.Common.BitMatrix bitMatrix = writer.Encode(Data);
3042 //int[] barcodeDimensions = { 10, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44, 48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
3043 //bool generate = false;
3044 //int resize = 6;
3045
3046 //if ((Data.Length - fontsize) > 9)
3047 // throw new Exception("Data matrix barcode value cannot be larger than 9 characters from the font size.");
3048
3049 //if(!barcodeDimensions.Contains(fontsize))
3050 // throw new Exception("Font size not supported.");
3051
3052 //for (int generateCount = 0; generateCount < barcodeDimensions.Length; generateCount++)
3053 //{
3054 // if (Data.Length <= barcodeDimensions[generateCount] && Data.Length <= barcodeDimensions[generateCount])
3055 // {
3056 // resize = fontsize < 10 ? 10 : fontsize <= barcodeDimensions[generateCount] ? fontsize : barcodeDimensions[generateCount] + (fontsize - barcodeDimensions[generateCount]);
3057 // int size = barcodeDimensions[generateCount];// ? barcodeDimensions[generateCount] : barcodeDimensions[generateCount] + (fontsize - barcodeDimensions[generateCount]);
3058 // writer.Options.Height = resize;
3059 // writer.Options.Width = resize;
3060 // ((ZXing.Datamatrix.DatamatrixEncodingOptions)writer.Options).MinSize = new ZXing.Dimension(resize, resize);
3061 // ((ZXing.Datamatrix.DatamatrixEncodingOptions)writer.Options).MaxSize = new ZXing.Dimension(resize, resize);
3062 // ZXing.Common.BitMatrix bitm = writer.Encode(Data);
3063 // break;
3064 // }
3065
3066 //}
3067
3068
3069 //writer.Write(Data).Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
3070 //stream.Seek(0, System.IO.SeekOrigin.Begin);
3071 //Image image = Image.Get(stream);
3072 //org.pdfclown.documents.contents.xObjects.XObject imageXObject = image.ToXObject(page.Document);
3073 //composer.ShowXObject(
3074 // imageXObject,
3075 // new System.Drawing.PointF(newx, newy)
3076
3077 // );
3078 //composer.Flush();
3079 //stream.Dispose();
3080 //stamper.Flush();
3081
3082
3083
3084
3085 }
3086
3087
3088 public void AddEAN(string Data, PdfPage page, int x, int y, int width, int height, DeviceRgb col, int rot = 0)
3089 {
3090 PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
3091 Barcode1D barcode1D = new Barcode128(page.GetDocument());
3092 barcode1D.SetCodeType(1);
3093 barcode1D.SetCode(Data);
3094 barcode1D.SetTextAlignment(1);
3095 pdfCanvas.AddXObject(barcode1D.CreateFormXObject(col, col, page.GetDocument()), new iText.Kernel.Geom.Rectangle(x, y, width, height));
3096 }
3097
3098 public void AddPDF417(string Data, PdfPage page, int x,
3099 int y,
3100 int width,
3101 int height, DeviceRgb col, int rot = 0, int fontsize = 6)
3102 {
3103 float[] rott = GetRotation(page, x, y, width, height, rot);
3104 float newx = rott[0];
3105 float newy = rott[1];
3106 float rrot = rott[2];
3107
3108
3109 PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
3110 BarcodePDF417 barcodePDF = new BarcodePDF417();
3111 barcodePDF.SetCode(Data);
3112 barcodePDF.SetYHeight(height);
3113 pdfCanvas.AddXObject(barcodePDF.CreateFormXObject(col, page.GetDocument()), newx, newy);
3114 }
3115
3116
3117 public void AddQRCODE(string Data, PdfPage page, int x,
3118 int y,
3119 int width,
3120 int height, DeviceRgb col, int rot = 0, int fontsize = 6)
3121 {
3122 float[] rott = GetRotation(page, x, y, width, height, rot);
3123 float newx = rott[0];
3124 float newy = rott[1];
3125 float rrot = rott[2];
3126
3127 float Margin = 36;
3128 //org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
3129 //stamper.Page = page;
3130 //System.IO.MemoryStream stream = new System.IO.MemoryStream();
3131 //org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
3132 //ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter();
3133 //writer.Options = new ZXing.Common.EncodingOptions() { PureBarcode = true, Height = height * 2, Width = height * 2 };
3134 //writer.Format = ZXing.BarcodeFormat.QR_CODE;
3135 //System.Drawing.Bitmap dm = writer.Write(Data);
3136 //// dm.
3137 //// dm.Save(@"C:\Racami\work\engineering\BMS\dm.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
3138 //dm.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
3139
3140 //Image image = Image.Get(stream);
3141 //org.pdfclown.documents.contents.xObjects.XObject imageXObject = image.ToXObject(page.Document);
3142 //composer.ShowXObject(
3143 // imageXObject,
3144 // new System.Drawing.PointF(newx, newy)
3145
3146 // );
3147 //composer.Flush();
3148 //stream.Dispose();
3149 //stamper.Flush();
3150 }
3151
3152 List<String> activecommands = new List<string>() { "MediaType", "MediaWeight", "MediaPosition", "Duplex", "MediaColor", "Jog" };
3153 public void AddAnnots(PdfPage page,
3154 string Text,
3155 int x,
3156 int y, int width, int height)
3157 {
3158
3159 if (Text.Equals(""))
3160 return;
3161
3162 PdfTextAnnotation pdfTextAnnotation = new PdfTextAnnotation(new iText.Kernel.Geom.Rectangle(x, y, 10f, 10f));
3163 string header = Text.Substring(0, Text.Length);
3164 if (!header.Contains("USESSPDE"))
3165 {
3166 if (Text.Contains("X::PDF(F)") || Text.Contains("Page control annotation") || Text.Contains("A::PCA"))
3167 {
3168
3169 Text = Text.Replace("X::PDF(F)\n", "").Replace("Page control annotation\n", "").Replace("A::PCA\n", "");
3170 pdfTextAnnotation.SetTitle(new PdfString("Page control annotation"));
3171 string[] array = Text.Split('\n');
3172 string text = "";
3173 string[] array2 = array;
3174 foreach (string cmd in array2)
3175 {
3176 if (cmd.Contains("MT("))
3177 {
3178 text = text + cmd.Replace("MT(", "MediaType=").Replace(")", "") + "\n";
3179 }
3180 if (cmd.Contains("Media Type"))
3181 {
3182 text = text + cmd.Replace("Media Type", "MediaType=").Replace(")", "") + "\n";
3183 }
3184 if (cmd.Contains("Media Weight"))
3185 {
3186 text = text + cmd.Replace("Media Weight", "MediaWeight=").Replace(")", "") + "\n";
3187 }
3188 if (cmd.Contains("MP("))
3189 {
3190 text = text + cmd.Replace("MP(", "MediaPosition=").Replace(")", "") + "\n";
3191 }
3192 if (cmd.Contains("Media Position"))
3193 {
3194 text = text + cmd.Replace("Media Position", "MediaPosition=").Replace(")", "") + "\n";
3195 }
3196 if (cmd.Contains("Media Color"))
3197 {
3198 text = text + cmd.Replace("Media Color", "MediaColor=").Replace(")", "") + "\n";
3199 }
3200 if (cmd.Contains("MW("))
3201 {
3202 text = text + cmd.Replace("MW(", "MediaWeight=").Replace(")", "") + "\n";
3203 }
3204 if (cmd.Contains("MC("))
3205 {
3206 text = text + cmd.Replace("MC(", "MediaColor=").Replace(")", "") + "\n";
3207 }
3208 if (cmd.Contains("JO("))
3209 {
3210 text = text + cmd.Replace("JO(", "Jog=").Replace(")", "") + "\n";
3211 }
3212 if (cmd.Contains("PX("))
3213 {
3214 text = text + cmd.Replace("S", "false").Replace("D", "true").Replace("PX(", "Duplex=")
3215 .Replace(")", "") + "\n";
3216 }
3217 if (cmd.Contains("Plex="))
3218 {
3219 text = text + cmd.Replace("S", "false").Replace("D", "true").Replace("Plex=", "Duplex=")
3220 .Replace(")", "") + "\n";
3221 }
3222 else if (cmd.LastIndexOf("=") != -1 && activecommands?.Find((string acmd) => acmd == cmd?.Remove(cmd.LastIndexOf("="))) != null)
3223 {
3224 text = text + cmd + "\n";
3225 }
3226 }
3227 Text = text;
3228 }
3229 }
3230 else
3231 Text = Text.Replace("USESSPDE\n", "").Replace("USESSPDE", "");
3232
3233
3234 pdfTextAnnotation.SetContents(new PdfString(Text));
3235 PdfPopupAnnotation pdfPopupAnnotation = new PdfPopupAnnotation(new iText.Kernel.Geom.Rectangle(x, y, 10f, 10f));
3236 pdfPopupAnnotation.SetOpen(open: true);
3237 pdfTextAnnotation.SetPopup(pdfPopupAnnotation);
3238 pdfPopupAnnotation.SetParent(pdfTextAnnotation);
3239 page.AddAnnotation(pdfTextAnnotation);
3240 page.AddAnnotation(pdfPopupAnnotation);
3241
3242 // string Title = "";
3243 // string header = Text.Substring(0, 8);
3244 // if (!header.Contains("USESSPDE"))
3245 // {
3246 // if (Text.Contains("X::PDF(F)") || Text.Contains("Page control annotation") || Text.Contains("A::PCA"))
3247 // {
3248 // Text = Text.Replace("X::PDF(F)\n", "").Replace("Page control annotation\n", "").Replace("A::PCA\n", "");
3249 // Title = "Page control annotation";
3250 // String[] finishing = Text.Split('\n');
3251 // string finish = "";
3252 // foreach (string cmd in finishing)
3253 // {
3254 // if (cmd.Contains("MT("))
3255 // finish += cmd.Replace("MT(", "MediaType=").Replace(")", "") + "\n";
3256 // if (cmd.Contains("Media Type"))
3257 // finish += cmd.Replace("Media Type", "MediaType=").Replace(")", "") + "\n";
3258 // if (cmd.Contains("Media Weight"))
3259 // finish += cmd.Replace("Media Weight", "MediaWeight=").Replace(")", "") + "\n";
3260 // if (cmd.Contains("MP("))
3261 // finish += cmd.Replace("MP(", "MediaPosition=").Replace(")", "") + "\n";
3262 // if (cmd.Contains("Media Position"))
3263 // finish += cmd.Replace("Media Position", "MediaPosition=").Replace(")", "") + "\n";
3264 // if (cmd.Contains("Media Color"))
3265 // finish += cmd.Replace("Media Color", "MediaColor=").Replace(")", "") + "\n";
3266 // if (cmd.Contains("MW("))
3267 // finish += cmd.Replace("MW(", "MediaWeight=").Replace(")", "") + "\n";
3268 // if (cmd.Contains("MC("))
3269 // finish += cmd.Replace("MC(", "MediaColor=").Replace(")", "") + "\n";
3270 // if (cmd.Contains("JO("))
3271 // finish += cmd.Replace("JO(", "Jog=").Replace(")", "") + "\n";
3272 // if (cmd.Contains("PX("))
3273 // {
3274 // finish += cmd.Replace("S", "false").Replace("D", "true").Replace("PX(", "Duplex=").Replace(")", "") + "\n";
3275 // //finish += finish.Replace("S", "false").Replace("D", "true") + "\n";
3276 // }
3277 // if (cmd.Contains("Plex="))
3278 // finish += cmd.Replace("S", "false").Replace("D", "true").Replace("Plex=", "Duplex=").Replace(")", "") + "\n";
3279 // else if (cmd.LastIndexOf("=") != -1 && activecommands?.Find(acmd => acmd == cmd?.Remove(cmd.LastIndexOf("="))) != null)
3280 // finish += cmd + "\n";
3281 // //if (cmd.Contains("Duplex="))
3282 // // finish += cmd.Replace("S", "false").Replace("D", "true") + "\n";
3283
3284 // }
3285 // Text = finish;
3286 // }
3287 // }
3288 // else
3289 // Text = Text.Replace("USESSPDE\n", "").Replace("USESSPDE", "");
3290
3291 // int[] RGB = new int[3] { 255, 255, 255 };
3292 // org.pdfclown.documents.contents.colorSpaces.DeviceRGBColor Color = new org.pdfclown.documents.contents.colorSpaces.DeviceRGBColor(RGB[0] / 255d, RGB[1] / 255d, RGB[2] / 255d);
3293
3294 // //org.pdfclown.documents.interaction.annotations.Scribble scri = new org.pdfclown.documents.interaction.annotations.Scribble(
3295 // // page,
3296
3297 // // new List<IList<System.Drawing.PointF>>(
3298 // // new List<System.Drawing.PointF>[]
3299 // // {
3300 // // new List<System.Drawing.PointF>(
3301 // // new System.Drawing.PointF[]
3302 // // {
3303 // // new System.Drawing.PointF(50,300),
3304 // // new System.Drawing.PointF(70,310),
3305 // // new System.Drawing.PointF(100,320)
3306 // // }
3307 // // )
3308 // // }
3309 // // ), Text , Color
3310 // // );
3311 // //scri.Title = Title;
3312 // //scri.Visible = true;
3313
3314 // org.pdfclown.documents.interaction.annotations.StickyNote calloutNote = new StickyNote(
3315 //page,
3316 //new System.Drawing.PointF(x, y),
3317 //Text
3318 //);
3319 // if (!String.IsNullOrEmpty(Title))
3320 // calloutNote.Title = Title;
3321
3322 }
3323 #endregion
3324
3325 public void DoLinkWork(List<Racami.Common.links> plinks, PdfPage page, EngineerConfig config, EngineObject.CISObjects CISObject)
3326 {
3327 float x;
3328 float y;
3329 #region links
3330 if (plinks != null)
3331 {
3332 List<Racami.Common.links> links = plinks;
3333 links.ForEach(link =>
3334 {
3335 #region links
3336 //added new exception thrown on failure
3337 try
3338 {
3339 string TextValue = link.url;
3340 x = (float)Convert.ToDouble(link.styles.position.left) / (float)((config.scale == 0) ? 1 : config.scale);//(float)Convert.ToDouble(((Racami.Common.links)link).styles.position.left) / (config.scale == 0 ? 1 : config.scale);
3341 //(page.Size.Height) -
3342 y = page.GetPageSize().GetHeight() - (float)Convert.ToDouble(link.styles.position.top) / (float)((config.scale == 0) ? 1 : config.scale) - (float)Convert.ToDouble(link.styles.size.height) / (float)((config.scale == 0) ? 1 : config.scale);//(
3343 // ((float)Convert.ToDouble(((Racami.Common.links)link).styles.position.top) / (config.scale == 0 ? 1 : config.scale)) -
3344 //((float)Convert.ToDouble(((Racami.Common.links)link).styles.size.height) / (config.scale == 0 ? 1 : config.scale)));
3345
3346 float width = (float)Convert.ToDouble((float)Convert.ToDouble(link.styles.size.width) / (float)((config.scale == 0) ? 1 : config.scale));//(float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.links)link).styles.size.width) / (config.scale == 0 ? 1 : config.scale));
3347 float height = (float)Convert.ToDouble((float)Convert.ToDouble(link.styles.size.height) / (float)((config.scale == 0) ? 1 : config.scale));//(float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.links)link).styles.size.height) / (config.scale == 0 ? 1 : config.scale));
3348 int[] RGB = GetRGB(((Racami.Common.links)link).styles.background.color.GetType() == typeof(string) ? ((Racami.Common.links)link).styles.background.color as string : ((List<String>)((Racami.Common.links)link).styles.background.color)[0]);
3349 DeviceRgb col = new DeviceRgb(RGB[0], RGB[1], RGB[2]);
3350 //now add the information to add the box and the hyperlink
3351 this.AddHyperLink(page, (int)x, (int)y, (int)width, (int)height, col, TextValue);
3352
3353 }
3354 catch (Exception ex)
3355 {
3356 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(ex.Message);
3357 throw ex;
3358 }
3359
3360 #endregion
3361 });
3362 }
3363 #endregion
3364
3365
3366 }
3367
3368 public void DoMaskWork(List<Racami.Common.masks> masks, PdfPage page, EngineerConfig config, EngineObject.CISObjects CISObject)
3369 {
3370 //float x;
3371 //float y;
3372 //process masks first so if it is a cover up or a redaction it will not be overwrite text being placed there
3373 #region masks
3374
3375
3376 // System.Threading.Tasks.Parallel.ForEach(masks, (mask)=>
3377 masks?.ForEach(mask =>
3378 {
3379
3380 TextPositions textpos = textpositions.Find(txp => txp.Name == mask.id) == null ? null : textpositions.Find(txp => txp.Name == mask.id);
3381
3382 if (textpos == null)
3383 {
3384 textpos = new TextPositions();
3385 textpos.Name = mask.id;
3386 textpos.X = (float)Convert.ToDouble(mask.styles.position.left) / (float)((config.scale == 0) ? 1 : config.scale); // (float)Convert.ToDouble(((Racami.Common.masks)mask).styles.position.left) / (config.scale == 0 ? 1 : config.scale);
3387 //(page.Size.Height) -
3388 textpos.Y = (page.GetPageSizeWithRotation().GetHeight() - (float)Convert.ToDouble(mask.styles.position.top) / (float)((config.scale == 0) ? 1 : config.scale) - (float)Convert.ToDouble(mask.styles.size.height) / (float)((config.scale == 0) ? 1 : config.scale));
3389 //((float)Convert.ToDouble(((Racami.Common.masks)mask).styles.position.top) / (config.scale == 0 ? 1 : config.scale)));// -
3390 // ((float)Convert.ToDouble(((Racami.Common.masks)mask).styles.size.height) / (config.scale == 0 ? 1 : config.scale)));
3391
3392 textpos.Width = (float)Convert.ToDouble((float)Convert.ToDouble(mask.styles.size.width) / (float)((config.scale == 0) ? 1 : config.scale));// (float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.masks)mask).styles.size.width) / (config.scale == 0 ? 1 : config.scale));
3393 textpos.Height = (float)Convert.ToDouble((float)Convert.ToDouble(mask.styles.size.height) / (float)((config.scale == 0) ? 1 : config.scale));// (float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.masks)mask).styles.size.height) / (config.scale == 0 ? 1 : config.scale));
3394
3395 var rr = ((Racami.Common.masks)mask).styles.background.color.GetType() == typeof(Newtonsoft.Json.Linq.JArray) ? ((Newtonsoft.Json.Linq.JArray)((Racami.Common.masks)mask).styles.background.color).ToObject<List<String>>() : null;
3396
3397
3398 int[] RGB = GetRGB(rr == null ? ((Racami.Common.masks)mask).styles.background.color as string : rr[0]);
3399 textpos.Color = new DeviceRgb(RGB[0], RGB[1], RGB[2]);
3400 //org.pdfclown.tools.PageStamper stamper = new org.pdfclown.tools.PageStamper();
3401 //stamper.Page = page;
3402
3403 //org.pdfclown.documents.contents.composition.PrimitiveComposer composer = stamper.Foreground;
3404 textpositions.Add(textpos);
3405 }
3406 if (mask?.condition?.ToUpper() == "CONDITION")
3407 {
3408 if (!String.IsNullOrEmpty(mask.logic))
3409 {
3410
3411 //if (mask.logic.ToUpper().Contains("INSERTIMAGE("))
3412 //{
3413 // float[] rott = GetRotation(page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height);
3414 // float newx = rott[0];
3415 // float newy = rott[1];
3416 // float rrot = rott[2];
3417
3418
3419 // PdfCanvas canvas = new PdfCanvas(page.NewContentStreamAfter(), page.GetResources(), page.GetDocument());
3420 // iText.Layout.Element.Image image = new iText.Layout.Element.Image(xObject);
3421 // new Canvas(canvas, page.GetDocument(), new Rectangle((float)textpos.X, (float)textpos.Y, (float)textpos.Width, (float)textpos.Height).
3422 //}
3423 //now we need to look at the custom logic to see what we want to execute
3424 //TextValue = Docustomlogic(custom.logic.Contains(TextValue) ? custom.logic.Replace(TextValue, "") : custom.logic, CISObject, spaage, page);
3425 // var newvalue = TextAssignment(custom.logic, spaage, CISObject);
3426 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Did custom work for this");
3427 }
3428 }
3429 else
3430 this.AddRectangle(page,
3431 (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Color);
3432 // stamper.Flush();
3433
3434 });
3435
3436 #endregion
3437 }
3438
3439 public string ConvertL(String ValuetoCheck, EngineObject.CISObjects CISObject, System.Data.DataRow Row)
3440 {
3441 if (CISObject == null)
3442 throw new Exception("The CISObject must be populated to process the substitutions");
3443
3444 if (ValuetoCheck.Contains("&quot;"))
3445 ValuetoCheck = ValuetoCheck.Replace("&quot;", "\"");
3446 if (ValuetoCheck.Contains("""))
3447 ValuetoCheck = ValuetoCheck.Replace(""", "\"");
3448
3449 string retstring = "";
3450 if (ValuetoCheck.Contains("{{{") && ValuetoCheck.Contains("}}}"))
3451 {
3452 int index = ValuetoCheck.IndexOf('{');
3453 while (index != -1)
3454 {
3455 int bbrace = ValuetoCheck.IndexOf('}') + 3;
3456 string value = "";
3457 for (int i = index; i < bbrace; i++)
3458 {
3459 value += ValuetoCheck[i];
3460 }
3461 //EngineObject.CISObjects.MasterLog.Info(value);
3462 //now check to see if the value is in any of the other objects
3463 if (value.ToUpper() == "{{{ASSETPATH}}}")
3464 {
3465 ValuetoCheck = ValuetoCheck.Replace(value, System.IO.Path.GetDirectoryName(CISObject.FilePath));
3466 }
3467 else if (value.ToUpper() == "{{{FILENAME}}}")
3468 {
3469 ValuetoCheck = ValuetoCheck.Replace(value, System.IO.Path.GetFileName(CISObject.FilePath));
3470 }
3471 else if (value.ToUpper() == "{{{FILENAMEWOEXT}}}")
3472 {
3473 ValuetoCheck = ValuetoCheck.Replace(value, System.IO.Path.GetFileNameWithoutExtension(CISObject.FilePath));
3474 }
3475 else if (value.ToUpper() == "{{{FILEPATH}}}")
3476 {
3477 ValuetoCheck = ValuetoCheck.Replace(value, CISObject.FilePath);
3478 }
3479 else if (value.Contains("RecordDetailsV2"))
3480 {
3481 ValuetoCheck = ValuetoCheck.Replace(value, Row[value.Replace("RecordDetailsV2.", "").Replace("{{{", "").Replace("}}}", "")].ToString());
3482 }
3483 else if (value.Contains("XmlData"))
3484 {
3485 String xml = Row["XmlData"] as string;
3486 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
3487 doc.LoadXml(xml);
3488 var ff = doc.DocumentElement.SelectSingleNode(value.Replace("XmlData.", "").Replace(".", "/").Replace("{{{", "").Replace("}}}", ""));
3489 ValuetoCheck = ValuetoCheck.Replace(value, ff.Value);
3490
3491 }
3492 else if (value.Contains("Job_Option_Details"))
3493 {
3494 if (CISObject.JobDetails == null || CISObject.JobDetails.Count == 0)
3495 throw new Exception("The option must be populated to process the substitutions");
3496 string column = value.ToLower().Replace("{{{job_option_details.", "").Replace("{{{jobs.", "").Replace("{{{files.", "").Replace("}}}", "");
3497
3498 List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(CISObject.JobDetails[0].GetType().GetProperties());
3499 System.Reflection.PropertyInfo prop = info.Find(p => p.Name.ToLower() == column);
3500 if (prop == null)
3501 throw new Exception("Substitution value is not supported " + value);
3502 Type tt = CISObject.JobDetails[0].GetType();
3503 object obj = CISObject.JobDetails[0] as object;
3504 var propvalue = prop.GetValue(obj, null);
3505 ValuetoCheck = ValuetoCheck.Replace(value, propvalue.ToString()).Replace("Job_Option_Details.", "");
3506 }
3507 else if (value.Contains("Jobs"))
3508 {
3509
3510 if (CISObject.Jobs == null)
3511 throw new Exception("The job must be populated to process the substitutions");
3512 string column = value.ToLower().Replace("{{{job_option_details.", "").Replace("{{{jobs.", "").Replace("{{{files.", "").Replace("}}}", "");
3513
3514 List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(CISObject.Jobs[0].GetType().GetProperties());
3515 System.Reflection.PropertyInfo prop = info.Find(p => p.Name.ToLower() == column);
3516 if (prop == null)
3517 throw new Exception("Substitution value is not supported " + value);
3518 Type tt = CISObject.Jobs[0].GetType();
3519 object obj = CISObject.Jobs[0] as object;
3520 var propvalue = prop.GetValue(obj, null);
3521 ValuetoCheck = ValuetoCheck.Replace(value, propvalue.ToString()).Replace("Jobs", "");
3522 info.Clear();
3523 }
3524 else if (value.Contains("Files"))
3525 {
3526 if (CISObject.Files == null)
3527 throw new Exception("The File must be populated to process the substitutions");
3528
3529 string column = value.ToLower().Replace("{{{job_option_details.", "").Replace("{{{jobs.", "").Replace("{{{files.", "").Replace("}}}", "");
3530
3531 List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(CISObject.Files[0].GetType().GetProperties());
3532 System.Reflection.PropertyInfo prop = info.Find(p => p.Name.ToLower() == column);
3533 if (prop == null)
3534 throw new Exception("Substitution value is not supported " + value);
3535 Type tt = CISObject.Files[0].GetType();
3536 object obj = CISObject.Files[0] as object;
3537 var propvalue = prop.GetValue(obj, null);
3538 ValuetoCheck = ValuetoCheck.Replace(value, propvalue.ToString()).Replace("Files", "");
3539 info.Clear();
3540 }
3541 else
3542 {
3543 if (CISObject.Options == null && CISObject.Job == null && CISObject.File == null)
3544 throw new Exception("The job , option or file must be populated to process the substitutions");
3545
3546 List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>(CISObject.Options == null ? CISObject.Job == null ? CISObject.File[0].GetType().GetProperties() : CISObject.Job[0].GetType().GetProperties() : CISObject.Options[0].GetType().GetProperties());
3547 System.Reflection.PropertyInfo prop = info.Find(p => p.Name == value.Replace("{{{", "").Replace("}}}", ""));
3548 if (prop == null)
3549 throw new Exception("Substitution value is not supported " + value);
3550 Type tt = CISObject.Options == null ? CISObject.Job == null ? CISObject.File[0].GetType() : CISObject.Job[0].GetType() : CISObject.Options[0].GetType();
3551 object obj = CISObject.Options == null ? CISObject.Job == null ? CISObject.File[0] : CISObject.Job[0] as object : CISObject.Options[0] as object;
3552 var propvalue = prop.GetValue(obj, null);
3553 ValuetoCheck = ValuetoCheck.Replace(value, propvalue.ToString());
3554 info.Clear();
3555 }
3556 index = ValuetoCheck.IndexOf('{');
3557 }
3558 retstring = ValuetoCheck;
3559 }
3560
3561 else
3562 {
3563
3564 retstring = ValuetoCheck;
3565 }
3566
3567 return retstring.Replace("}}}", "");
3568 }
3569
3570 string Docustomlogic(string evalstring, EngineObject.CISObjects CISObject, System.Data.DataRow row, PdfPage page)
3571 {
3572
3573 // return "tt";
3574
3575 string returnstring = "";
3576 //substitute all phrases first
3577 string newvalue = this.ConvertL(evalstring, CISObject, row).Replace(";", "\n");
3578
3579 //now look to see if there is a csv list to pull from
3580 if (newvalue.Contains("Keys.CustomCSVList"))
3581 if (CISObject.Keys.Keys.Contains("CustomCSVList"))
3582 newvalue = newvalue.Replace("Keys.CustomCSVList", CISObject.Keys["CustomCSVList"] as string);
3583 //now look to see if there is a pipe list to pull from
3584 if (newvalue.Contains("Keys.CustomPipeList"))
3585 if (CISObject.Keys.Keys.Contains("CustomPipeList"))
3586 newvalue = newvalue.Replace("Keys.CustomPipeList", CISObject.Keys["CustomPipeList"].ToString().Replace("|", ",") as string);
3587
3588
3589 //now we need to look for key words in the custom logic and perform those actions
3590 //now look for Padleft and Padright
3591 string f = "";
3592 int index = newvalue.ToUpper().IndexOf("PADLEFT", 0);
3593 if (index > -1)
3594 {
3595 #region padleft
3596 do
3597 {
3598 int endchar = newvalue.IndexOf(')', index);
3599 string evalsstring = "";
3600 for (int i = index; i < endchar; i++)
3601 {
3602 evalsstring += newvalue[i];
3603 }
3604 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("GGGGG");
3605 string[] command = evalsstring.Split(',');
3606 string padchar = command[1];
3607 string numbertopad = command[0].Replace("PADLEFT(", "");
3608 string nevalsstring = "";
3609 if (command[2].Contains("%RECORDS%"))
3610 {
3611 int cnt = (Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString()));
3612
3613 nevalsstring = command[2].Replace("%RECORDS%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3614 }
3615 else if (command[2].Contains("%RECORDCURRENT%"))
3616 {
3617 int cnt = Convert.ToInt32(RECSTART);
3618
3619 nevalsstring = command[2].Replace("%RECORDCURRENT%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3620 }
3621
3622 else if (command[2].Contains("%RECCOUNT%"))
3623 {
3624 int cnt = (Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString()));
3625 if (row.Table.Columns.Contains("Plex"))
3626 {
3627 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3628 cnt = (int)Math.Ceiling(Convert.ToDouble((Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString())) / 2));
3629 }
3630 nevalsstring = command[2].Replace("%RECCOUNT%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3631 }
3632 else if (command[2].Contains("%RECSTART%"))
3633 {
3634 int cnt = Convert.ToInt32(RECSTART);
3635 if (row.Table.Columns.Contains("Plex"))
3636 {
3637 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3638 if (cnt != 1)
3639 cnt = (int)Math.Ceiling(Convert.ToDouble(RECSTART) / 2);
3640 }
3641 nevalsstring = command[2].Replace("%RECSTART%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3642 }
3643 else if (command[2].Contains("%CURRENTDOC%"))
3644 {
3645 int cnt = Convert.ToInt32(CURRENTDOC);
3646 if (row.Table.Columns.Contains("Plex"))
3647 {
3648 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3649 if (cnt != 1)
3650 if (cnt != 1)
3651 cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3652 }
3653 nevalsstring = command[2].Replace("%CURRENTDOC%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3654 }
3655 else if (command[2].Contains("%HOUSEHOLDALL%"))
3656 {
3657 int cnt = Convert.ToInt32(HOUSEHOLDPAGE) - 1;
3658
3659 nevalsstring = command[2].Replace("%HOUSEHOLDALL%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3660 }
3661 else if (command[2].Contains("%HOUSEHOLDODD%"))
3662 {
3663 int cnt = Convert.ToInt32(HOUSEHOLDODDPAGE);
3664 //if (row.Table.Columns.Contains("Plex"))
3665 //{
3666 // if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3667 // if (cnt != 1)
3668 // if (cnt != 1)
3669 // cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3670 //}
3671 nevalsstring = command[2].Replace("%HOUSEHOLDODD%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3672 }
3673 else if (command[2].Contains("%HOUSEHOLDEVEN%"))
3674 {
3675 int cnt = Convert.ToInt32(HOUSEHOLDEVENPAGE);
3676 //if (row.Table.Columns.Contains("Plex"))
3677 //{
3678 // if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3679 // if (cnt != 1)
3680 // if (cnt != 1)
3681 // cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3682 //}
3683 nevalsstring = command[2].Replace("%HOUSEHOLDEVEN%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3684 }
3685
3686 else if (command[2].Contains("%DOCCOUNT%"))
3687 {
3688 int cnt = Convert.ToInt32(DOCCOUNT);
3689 if (row.Table.Columns.Contains("Plex"))
3690 {
3691 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3692 if (cnt != 1)
3693 if (cnt != 1)
3694 cnt = (int)Math.Ceiling(Convert.ToDouble(DOCCOUNT) / 2);
3695 }
3696 nevalsstring = command[2].Replace("%DOCCOUNT%", cnt.ToString());
3697 }
3698 else if (newvalue.Contains("%CURRENTPAGE%"))
3699 {
3700 nevalsstring = command[2].Replace("%CURRENTPAGE%", (page.GetDocument().GetPageNumber(page)).ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3701 }
3702
3703 else
3704 nevalsstring = command[2].PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3705
3706
3707
3708 newvalue = newvalue.Replace(evalsstring + ")", nevalsstring);
3709 }
3710 while ((index = newvalue.ToUpper().IndexOf("PADLEFT", index)) != -1);
3711 #endregion
3712
3713 }
3714 #region padright
3715 index = newvalue.ToUpper().IndexOf("PADRIGHT", 0);
3716 if (index > -1)
3717 {
3718 do
3719 {
3720 int endchar = newvalue.IndexOf(')', index);
3721 string evalsstring = "";
3722 for (int i = index; i < endchar; i++)
3723 {
3724 evalsstring += newvalue[i];
3725 }
3726 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info("GGGGG");
3727 string[] command = evalsstring.Split(',');
3728 string padchar = command[1];
3729 string numbertopad = command[0].Replace("PADRIGHT(", "");
3730 string nevalsstring = "";
3731 if (command[2].Contains("%RECORDS%"))
3732 {
3733 int cnt = (Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString()));
3734
3735 nevalsstring = command[2].Replace("%RECORDS%", cnt.ToString()).PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3736 }
3737 else if (command[2].Contains("%RECORDCURRENT%"))
3738 {
3739 int cnt = Convert.ToInt32(RECSTART);
3740
3741 nevalsstring = command[2].Replace("%RECORDCURRENT%", cnt.ToString()).PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3742 }
3743 else if (command[2].Contains("%RECCOUNT%"))
3744 {
3745 int cnt = (Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString()));
3746 if (row.Table.Columns.Contains("Plex"))
3747 {
3748 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3749 cnt = (int)Math.Ceiling(Convert.ToDouble((Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString())) / 2));
3750 }
3751 nevalsstring = command[2].Replace("%RECCOUNT%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3752 }
3753 else if (command[2].Contains("%RECSTART%"))
3754 {
3755 int cnt = Convert.ToInt32(RECSTART);
3756 if (row.Table.Columns.Contains("Plex"))
3757 {
3758 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3759 if (cnt != 1)
3760 if (cnt != 1)
3761 cnt = (int)Math.Ceiling(Convert.ToDouble(RECSTART) / 2);
3762 }
3763 nevalsstring = command[2].Replace("%RECSTART%", cnt.ToString()).PadLeft(Convert.ToInt32(numbertopad), padchar[0]);
3764 }
3765 else if (command[2].Contains("%CURRENTDOC%"))
3766 {
3767 int cnt = Convert.ToInt32(CURRENTDOC);
3768 if (row.Table.Columns.Contains("Plex"))
3769 {
3770 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3771 if (cnt != 1)
3772 if (cnt != 1)
3773 cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3774 }
3775 nevalsstring = command[2].Replace("%CURRENTDOC%", cnt.ToString()).PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3776 }
3777 else if (command[2].Contains("%HOUSEHOLDALL%"))
3778 {
3779 int cnt = Convert.ToInt32(HOUSEHOLDPAGE);
3780 //if (row.Table.Columns.Contains("Plex"))
3781 //{
3782 // if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3783 // if (cnt != 1)
3784 // if (cnt != 1)
3785 // cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3786 //}
3787 nevalsstring = command[2].Replace("%HOUSEHOLDALL%", cnt.ToString()).PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3788 }
3789 else if (command[2].Contains("%HOUSEHOLDODD%"))
3790 {
3791 int cnt = Convert.ToInt32(HOUSEHOLDODDPAGE);
3792 //if (row.Table.Columns.Contains("Plex"))
3793 //{
3794 // if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3795 // if (cnt != 1)
3796 // if (cnt != 1)
3797 // cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3798 //}
3799 nevalsstring = command[2].Replace("%HOUSEHOLDODD%", cnt.ToString()).PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3800 }
3801 else if (command[2].Contains("%HOUSEHOLDEVEN%"))
3802 {
3803 int cnt = Convert.ToInt32(HOUSEHOLDEVENPAGE);
3804 //if (row.Table.Columns.Contains("Plex"))
3805 //{
3806 // if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3807 // if (cnt != 1)
3808 // if (cnt != 1)
3809 // cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3810 //}
3811 nevalsstring = command[2].Replace("%HOUSEHOLDEVEN%", cnt.ToString()).PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3812 }
3813 else if (command[2].Contains("%DOCCOUNT%"))
3814 {
3815 int cnt = Convert.ToInt32(DOCCOUNT);
3816 if (row.Table.Columns.Contains("Plex"))
3817 {
3818 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3819 if (cnt != 1)
3820 if (cnt != 1)
3821 cnt = (int)Math.Ceiling(Convert.ToDouble(DOCCOUNT) / 2);
3822 }
3823 nevalsstring = command[2].Replace("%DOCCOUNT%", cnt.ToString());
3824 }
3825 else if (newvalue.Contains("%CURRENTPAGE%"))
3826 {
3827 nevalsstring = command[2].Replace("%CURRENTPAGE%", (page.GetDocument().GetPageNumber(page)).ToString()).PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3828 }
3829
3830 else
3831 nevalsstring = command[2].PadRight(Convert.ToInt32(numbertopad), padchar[0]);
3832
3833
3834
3835 newvalue = newvalue.Replace(evalsstring + ")", nevalsstring);
3836 }
3837 while ((index = newvalue.ToUpper().IndexOf("PADRIGHT", index)) != -1);
3838
3839 }
3840
3841 #endregion
3842 #region all other substitution
3843
3844 if (newvalue.Contains("%RECCOUNT%"))
3845 {
3846 int cnt = (Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString()));
3847 if (row.Table.Columns.Contains("Plex"))
3848 {
3849 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3850 cnt = (int)Math.Ceiling(Convert.ToDouble((Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString())) / 2));
3851 }
3852 newvalue = newvalue.Replace("%RECCOUNT%", cnt.ToString());
3853 }
3854 if (newvalue.Contains("%RECSTART%"))
3855 {
3856 int cnt = Convert.ToInt32(RECSTART);
3857 if (row.Table.Columns.Contains("Plex"))
3858 {
3859 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3860 if (cnt != 1)
3861 if (cnt != 1)
3862 cnt = (int)Math.Ceiling(Convert.ToDouble(RECSTART) / 2);
3863 }
3864 newvalue = newvalue.Replace("%RECSTART%", cnt.ToString());
3865 }
3866
3867
3868
3869 if (newvalue.Contains("%RECORDS%"))
3870 {
3871 int cnt = (Convert.ToInt32(row["EndPage"].ToString()) + 1 - Convert.ToInt32(row["StartPage"].ToString()));
3872
3873 newvalue = newvalue.Replace("%RECORDS%", cnt.ToString());
3874 }
3875 if (newvalue.Contains("%RECORDCURRENT%"))
3876 {
3877 int cnt = Convert.ToInt32(RECSTART);
3878
3879 newvalue = newvalue.Replace("%RECORDCURRENT%", cnt.ToString());
3880 }
3881
3882
3883 if (newvalue.Contains("%CURRENTDOC%"))
3884 {
3885 int cnt = Convert.ToInt32(CURRENTDOC);
3886 if (row.Table.Columns.Contains("Plex"))
3887 {
3888 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3889 if (cnt != 1)
3890 if (cnt != 1)
3891 cnt = (int)Math.Ceiling(Convert.ToDouble(CURRENTDOC) / 2);
3892 }
3893 newvalue = newvalue.Replace("%CURRENTDOC%", cnt.ToString());
3894 }
3895
3896 if (newvalue.Contains("%CURRENTPAGE%"))
3897 {
3898 newvalue = newvalue.Replace("%CURRENTPAGE%", (page.GetDocument().GetPageNumber(page)).ToString());
3899 }
3900
3901 if (newvalue.Contains("%HOUSEHOLDALL%"))
3902 {
3903 int cnt = Convert.ToInt32(HOUSEHOLDPAGE);
3904
3905 newvalue = newvalue.Replace("%HOUSEHOLDALL%", cnt.ToString());
3906 }
3907 if (newvalue.Contains("%HOUSEHOLDODD%"))
3908 {
3909 int cnt = Convert.ToInt32(HOUSEHOLDODDPAGE);
3910
3911 newvalue = newvalue.Replace("%HOUSEHOLDODD%", cnt.ToString());
3912 }
3913 if (newvalue.Contains("%HOUSEHOLDEVEN%"))
3914 {
3915 int cnt = Convert.ToInt32(HOUSEHOLDEVENPAGE);
3916
3917 newvalue = newvalue.Replace("%HOUSEHOLDEVEN%", cnt.ToString());
3918 }
3919 if (newvalue.Contains("%HOUSEHOLDPAGE%"))
3920 {
3921 newvalue = newvalue.Replace("%HOUSEHOLDPAGE%", (page.GetDocument().GetPageNumber(page)).ToString());
3922 }
3923
3924
3925 if (newvalue.Contains("%DOCCOUNT%"))
3926 {
3927 int cnt = Convert.ToInt32(DOCCOUNT);
3928 if (row.Table.Columns.Contains("Plex"))
3929 {
3930 if (!String.IsNullOrEmpty(row["Plex"]?.ToString()) && row["Plex"]?.ToString().ToUpper() == "DUPLEX")
3931 if (cnt != 1)
3932 if (cnt != 1)
3933 cnt = (int)Math.Ceiling(Convert.ToDouble(DOCCOUNT) / 2);
3934 }
3935 newvalue = newvalue.Replace("%DOCCOUNT%", cnt.ToString());
3936 }
3937
3938 #endregion
3939
3940 #region initial if check
3941 Dictionary<String, object> commanddict = new Dictionary<string, object>();
3942 List<string> commands = new List<String>(newvalue.Trim().Replace(";", "\n").Split('\n'));
3943
3944 // commands.AddRange(new List<String>(newvalue.Split(';')));
3945
3946 commands.FindAll(cmd => String.IsNullOrEmpty(cmd)).ForEach(forcmd => { commands.Remove(forcmd); });
3947 //remove all applyto
3948 commands.FindAll(cmd => cmd.ToUpper().Contains("APPLYTO=")).ForEach(forcmd => { commands.Remove(forcmd); newvalue = newvalue.Replace(forcmd, ""); });
3949
3950 if (commands.Count > 0)
3951 {
3952 for (int i = 0; i < commands.Count; i++)
3953 {
3954 if (commands[i].StartsWith("var"))
3955 {
3956 string command = "";
3957 int vars = commands[i].ToUpper().IndexOf("VAR");
3958 for (int eq = vars + "var".Length; eq < commands[i].Length; eq++)
3959 {
3960 if (commands[i][eq] == '=')
3961 break;
3962 command += new String(commands[i][eq], 1);
3963
3964 }
3965
3966 if (!commanddict.ContainsKey(command.Trim()))
3967 commanddict.Add(command.Trim(), command.Trim());
3968 SubInStatements sub = new SubInStatements();
3969 if (commands[i].Contains("="))
3970 {
3971 if (commands[i].Contains("=="))
3972 {
3973 commands[i] = commands[i].Replace("==", "Equals");
3974 sub.EvalType = "Equals";
3975 newvalue = newvalue.Replace("==", "Equals");
3976 }
3977 if (commands[i].Contains("!="))
3978 {
3979 commands[i] = commands[i].Replace("!=", "NOTEquals");
3980 sub.EvalType = "NOTEquals";
3981 newvalue = newvalue.Replace("!=", "NOTEquals");
3982 }
3983 //GrtrEquals
3984 if (commands[i].Contains(">="))
3985 {
3986 commands[i] = commands[i].Replace(">=", "GrtrEquals");
3987 sub.EvalType = "GrtrEquals";
3988 newvalue = newvalue.Replace(">=", "GrtrEquals");
3989 }
3990
3991 if (commands[i].Contains("<="))
3992 {
3993 commands[i] = commands[i].Replace("<=", "LessEquals");
3994 sub.EvalType = "LessEquals";
3995 newvalue = newvalue.Replace("<=", "LessEquals");
3996 }
3997
3998 if (commands[i].Contains("Contains"))
3999 {
4000 // commands[i] = commands[i].Replace("Contains", "Cont");
4001 sub.EvalType = "Contains";
4002 // newvalue = newvalue.Replace("<=", "LessEquals");
4003 }
4004 if (commands[i].Contains("?"))
4005 {
4006 commands[i] = commands[i].Replace("?", "Then");
4007 newvalue = newvalue.Replace("?", "Then");
4008 }
4009 if (commands[i].Contains(":"))
4010 {
4011 commands[i] = commands[i].Replace(":", "Else");
4012 newvalue = newvalue.Replace(":", "Else");
4013 }
4014
4015 String[] subs = commands[i].Split('=');
4016
4017 int equals = subs[1].ToUpper().IndexOf("EQUALS");
4018 for (int eq = 0; eq < equals; eq++)
4019 sub.EvalVar += new String(subs[1][eq], 1);
4020
4021
4022 int thens = subs[1].ToUpper().IndexOf("THEN");
4023 for (int eq = equals + "EQUALS".Length; eq < thens; eq++)
4024 sub.ResultVar += new String(subs[1][eq], 1);
4025
4026 int elser = subs[1].ToUpper().IndexOf("ELSE");
4027 for (int eq = thens + "THEN".Length; eq < elser; eq++)
4028 sub.ThenResult += new String(subs[1][eq], 1);
4029
4030
4031 for (int eq = elser + "ELSE".Length; eq < subs[1].Length; eq++)
4032 sub.ElseResult += new String(subs[1][eq], 1);
4033
4034 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Get ready for eval");
4035 object reto = sub.DoEval();
4036 commanddict[command.Trim()] = reto == null ? "" : reto as string;
4037
4038 newvalue = newvalue.Replace(commands[i], "");
4039 // commands.Remove();
4040 //sub.EvalVar
4041 }
4042 else if (commands[i].Contains("Contains"))
4043 {
4044 if (commands[i].Contains("?"))
4045 {
4046 commands[i] = commands[i].Replace("?", "Then");
4047 newvalue = newvalue.Replace("?", "Then");
4048 }
4049 if (commands[i].Contains(":"))
4050 {
4051 commands[i] = commands[i].Replace(":", "Else");
4052 newvalue = newvalue.Replace(":", "Else");
4053 }
4054 String[] subs = commands[i].Replace("Contains", "!").Split('!');
4055
4056 int equals = subs[1].ToUpper().IndexOf("EQUALS");
4057 for (int eq = 0; eq < equals; eq++)
4058 sub.EvalVar += new String(subs[1][eq], 1);
4059
4060 int thens = subs[1].ToUpper().IndexOf("THEN");
4061 for (int eq = equals + "EQUALS".Length; eq < thens; eq++)
4062 sub.ResultVar += new String(subs[1][eq], 1);
4063
4064 int elser = subs[1].ToUpper().IndexOf("ELSE");
4065 for (int eq = thens + "THEN".Length; eq < elser; eq++)
4066 sub.ThenResult += new String(subs[1][eq], 1);
4067
4068
4069 for (int eq = elser + "ELSE".Length; eq < subs[1].Length; eq++)
4070 sub.ElseResult += new String(subs[1][eq], 1);
4071
4072 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Get ready for eval");
4073 object reto = sub.DoEval();
4074 commanddict[command.Trim()] = reto == null ? "" : reto as string;
4075
4076 newvalue = newvalue.Replace(commands[i], "");
4077 }
4078 }
4079 }
4080 }
4081
4082 //let's get rid of all new line characters
4083 newvalue = newvalue.Replace("\n", "").Replace("=", "").Trim();
4084
4085 commands.FindAll(cmd => cmd.StartsWith("%")).ForEach(forcmd => { commands.Remove(forcmd); });
4086 foreach (var item in commanddict.Keys)
4087 newvalue = newvalue.Replace(item, commanddict[item].ToString().Trim());
4088
4089
4090 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Data after eval {newvalue}");
4091 #endregion
4092 commanddict.Clear();
4093 commands.Clear();
4094 return newvalue.Replace("return", "").Trim();
4095 }
4096
4097 internal class SubInStatements
4098 {
4099 public object EvalVar { get; set; }
4100 public object ResultVar { get; set; }
4101 public object EvalType { get; set; }
4102
4103 public object ReturnResult { get; set; }
4104
4105 public object ThenResult { get; set; }
4106 public object ElseResult { get; set; }
4107
4108 public object DoEval()
4109 {
4110 object ret = null;
4111 if (EvalType != null ? EvalType.ToString() == "Equals" ? true : false : false)
4112 {
4113 String nEval = EvalVar.ToString().Replace("(", "").Replace(")", "");
4114 if (ResultVar.ToString().Contains(","))
4115 {
4116 if (new List<string>(ResultVar.ToString().Split(',')).Find(e => e.Contains(EvalVar.ToString())) == null)
4117 ret = ThenResult;
4118 else
4119 ret = ElseResult;
4120 }
4121 //compute if the plus or minus sign is there
4122 //if (EvalVar.ToString().Contains("+") || EvalVar.ToString().Contains("-"))
4123 //{
4124 System.Data.DataTable dt = new System.Data.DataTable();
4125 // object retv = dt.Compute(EvalVar.ToString().Trim(),null);
4126 // }
4127 object eval = EvalVar.ToString().Contains("COMPUTE") ? dt.Compute(EvalVar.ToString().Replace("COMPUTE", "").Replace("(", "").Replace(")", "").Trim(), null) : EvalVar.ToString().Trim();
4128 object result = ResultVar.ToString().Contains("COMPUTE") ? dt.Compute(ResultVar.ToString().Replace("COMPUTE", "").Replace("(", "").Replace(")", "").Trim(), null) : ResultVar.ToString().Trim();
4129 if ((eval.Equals(result)))
4130 ret = ThenResult;
4131 else
4132 ret = ElseResult;
4133 }
4134 else
4135 {
4136 if (EvalType != null ? EvalType.ToString() == "Equals" ? EvalVar.Equals(ResultVar) :
4137 EvalType.ToString() == "LessEquals" ? Convert.ToInt32(EvalVar.ToString()) <= Convert.ToInt32(ResultVar.ToString()) ?
4138 EvalType.ToString() == "GrtrEquals" ? Convert.ToInt32(EvalVar.ToString()) >= Convert.ToInt32(ResultVar.ToString()) ?
4139 EvalType.ToString() == "NOTEquals" ? EvalVar.ToString() != ResultVar.ToString() : false : false : false : false : false : false)
4140 ret = ThenResult;
4141 else
4142 ret = ElseResult;
4143 }
4144
4145
4146 return ret;
4147 }
4148
4149
4150 }
4151 public void DoCustomTextWork(List<Racami.Common.customTexts> pcustomTexts, PdfPage page, EngineerConfig config, List<FontFamilyStage> fontDic, System.Data.DataRow spaage, EngineObject.CISObjects CISObject)
4152 {
4153
4154 //float x;
4155 //float y;
4156 #region customtexts
4157 if (pcustomTexts != null)
4158 {
4159 Racami.Common.customTexts[] variablearray = new Racami.Common.customTexts[(int)pcustomTexts.Count];
4160
4161 pcustomTexts.CopyTo(variablearray);
4162
4163 List<Racami.Common.customTexts> customtexts = SubstituteText(new List<Racami.Common.customTexts>(variablearray), spaage, CISObject);
4164 // System.Threading.Tasks.Parallel.ForEach(SubstituteText(new List<Racami.Common.customTexts>(variablearray), spaage, CISObject), (custom) =>
4165 customtexts.ForEach(custom =>
4166 {
4167 #region custom Texts
4168 try
4169 {
4170 string TextValue = custom?.value;
4171
4172 TextPositions textpos = textpositions.Find(txp => txp.Name == custom?.id) == null ? null : textpositions.Find(txp => txp.Name == custom?.id);
4173
4174 if (textpos == null)
4175 {
4176 textpos = new TextPositions();
4177 textpos.Name = custom.id;
4178
4179 textpos.X = (float)Convert.ToDouble(custom.styles.position.left) / (float)((config.scale == 0) ? 1 : config.scale);//(float)Convert.ToDouble(((Racami.Common.customTexts)custom).styles.position.left) / (config.scale == 0 ? 1 : config.scale);
4180 //(page.Size.Height) -
4181 textpos.Y = page.GetPageSizeWithRotation().GetHeight() - (float)Convert.ToDouble(custom.styles.position.top) / (float)((config.scale == 0) ? 1 : config.scale) - (float)Convert.ToDouble((custom.styles.size.height.ToString() == "auto") ? custom.styles.font.size : custom.styles.size.height.ToString()) / (float)((config.scale == 0) ? 1 : config.scale);//(
4182 // ((float)Convert.ToDouble(((Racami.Common.customTexts)custom).styles.position.top) / (config.scale == 0 ? 1 : config.scale)) -
4183 // ((float)Convert.ToDouble(((Racami.Common.customTexts)custom).styles.size.height.ToString() == "auto" ? ((Racami.Common.customTexts)custom).styles.font.size : ((Racami.Common.customTexts)custom).styles.size.height.ToString()) / (config.scale == 0 ? 1 : config.scale)));
4184 textpos.Width = (float)Convert.ToDouble((float)Convert.ToDouble((!(custom.styles.size.width.ToString() == "auto")) ? custom.styles.size.width.ToString() : (string.IsNullOrEmpty(TextValue) ? "".Length.ToString() : TextValue.Length.ToString())) / (float)((config.scale == 0) ? 1 : config.scale));//(float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.customTexts)custom).styles.size.width.ToString() == "auto" ? String.IsNullOrEmpty(TextValue) ? "".Length.ToString() : TextValue.Length.ToString() : ((Racami.Common.customTexts)custom).styles.size.width.ToString()) / (config.scale == 0 ? 1 : config.scale));
4185 textpos.Height = (float)Convert.ToDouble((float)Convert.ToDouble((custom.styles.size.height.ToString() == "auto") ? custom.styles.font.size : custom.styles.size.height.ToString()) / (float)((config.scale == 0) ? 1 : config.scale));//(float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.customTexts)custom).styles.size.height.ToString() == "auto" ? ((Racami.Common.customTexts)custom).styles.font.size :
4186 // ((Racami.Common.customTexts)custom).styles.size.height.ToString()) / (config.scale == 0 ? 1 : config.scale));
4187
4188 int[] RGB = GetRGB(((Racami.Common.customTexts)custom).styles.font.color);
4189 textpos.Color = new DeviceRgb(RGB[0], RGB[1], RGB[2]);
4190
4191 textpos.fontstyle = ((Racami.Common.customTexts)custom).styles.font.style;
4192 textpos.fontweight = ((Racami.Common.customTexts)custom).styles.font.weight;
4193
4194 Type var = ((Racami.Common.customTexts)custom).styles.font.family.GetType();
4195 var rr = ((Racami.Common.customTexts)custom).styles.font.family.GetType() == typeof(Newtonsoft.Json.Linq.JArray) ?
4196 ((Newtonsoft.Json.Linq.JArray)((Racami.Common.customTexts)custom).styles.font.family).ToObject<List<String>>() :
4197 null;
4198
4199 // if (!custom.isComment && String.IsNullOrEmpty(custom.barcodeType))
4200 // {
4201 string fontFamily = rr?.Count == 0 ?
4202 ((String)((Racami.Common.customTexts)custom).styles.font.family).ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "") :
4203 rr[0].ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "");
4204 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Got font family {fontFamily}");
4205
4206 //now we need to do a lookup and get the values from the record details to substitute
4207 textpos.Fonts = fontDic.FindAll(f => f.FamilyName.ToLower().Contains(fontFamily.ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(", monospace", "").Replace(", monospace_italic", "").Replace(", monospace_bold", "")));
4208 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info($"Got font");
4209
4210 textpos.Rotation = ((Racami.Common.customTexts)custom).styles.rotate;
4211 textpositions.Add(textpos);
4212 }
4213 //else
4214 //{
4215 // textpos.Width = (float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.customTexts)custom).styles.size.width.ToString() == "auto" ? String.IsNullOrEmpty(TextValue) ? "".Length.ToString() : TextValue.Length.ToString() : ((Racami.Common.customTexts)custom).styles.size.width.ToString()) / (config.scale == 0 ? 1 : config.scale));
4216 // textpos.Height = (float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.customTexts)custom).styles.size.height.ToString() == "auto" ? ((Racami.Common.customTexts)custom).styles.font.size :
4217 // ((Racami.Common.customTexts)custom).styles.size.height.ToString()) / (config.scale == 0 ? 1 : config.scale));
4218 //}
4219
4220 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("text: ={0}=, x: ={1}=, y: ={2}=, font={3}=", TextValue, textpos.X, textpos.Y, textpos.Fonts?.Count != 0 ? textpos.Fonts[0].FamilyName : "no font"));
4221
4222
4223 if (custom.condition == "CUSTOM")
4224 {
4225 if (!String.IsNullOrEmpty(custom.logic))
4226 {
4227 //now we need to look at the custom logic to see what we want to execute
4228 TextValue = Docustomlogic(custom.logic.Contains(TextValue) ? custom.logic.Replace(TextValue, "") : custom.logic, CISObject, spaage, page);
4229 // var newvalue = TextAssignment(custom.logic, spaage, CISObject);
4230 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Did custom work for this");
4231 }
4232 }
4233 if (!custom.isComment && String.IsNullOrEmpty(custom.barcodeType))
4234 {
4235 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Add Text");
4236 this.AddText(page, String.IsNullOrEmpty(TextValue) ? "" : TextValue, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height,
4237 textpos.Color,
4238 Convert.ToInt32(((Racami.Common.customTexts)custom).styles.font.size), textpos.Fonts?.Count != 0 ? textpos.Fonts[0] : null, textpos.fontstyle, textpos.fontweight, textpos.Rotation);
4239 }
4240 else if (!String.IsNullOrEmpty(custom.barcodeType))
4241 {
4242 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Barcodes");
4243 #region barcodes
4244 try
4245 {
4246 //now we determine what barcode it is and load appropriately.
4247 if (custom?.barcodeType == "IMB")
4248 {
4249 textpos.Fonts = fontDic.FindAll(f => f.FamilyName.ToLower().Contains("imb"));
4250
4251 //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("bars value: ={0}=", vari.value));
4252 String bars = String.IsNullOrEmpty(TextValue) ? "" : TextValue;//
4253 string numers = Racami.Common.OneCode.OneCODE.OneCodeDecode(String.IsNullOrEmpty(TextValue) ? "" : TextValue);
4254 if (!String.IsNullOrEmpty(bars))
4255 this.AddIMB(bars, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width + 100, (int)textpos.Height, textpos.Rotation, Convert.ToInt32(((Racami.Common.customTexts)custom).styles.font.size));
4256 //this.AddIMBFont(page, String.IsNullOrEmpty(bars) ? "" : bars, (int)textpos.X, (int)textpos.Y, (int)textpos.Width+100, (int)textpos.Height, textpos.Color, Convert.ToInt32(((Racami.Common.customTexts)custom).styles.font.size), textpos.Fonts[0], textpos.fontstyle, textpos.fontweight, textpos.Rotation);
4257 }
4258 else if (custom?.barcodeType == "128" || custom?.barcodeType == "128 No Text")
4259 {
4260 this.Add128(String.IsNullOrEmpty(TextValue) ? "" : TextValue, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Color, textpos.Rotation, Convert.ToInt32(((Racami.Common.customTexts)custom).styles.font.size));
4261 }
4262 else if (custom?.barcodeType == "3of9")
4263 {
4264 this.Add3of9(String.IsNullOrEmpty(TextValue) ? "" : TextValue, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Color);
4265 }
4266 else if (custom?.barcodeType == "2D")
4267 {
4268
4269 // if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("The text value is " + TextValue); else Console.WriteLine("The text value is " + TextValue);
4270 this.AddDataMatrix(String.IsNullOrEmpty(TextValue) ? "" : TextValue, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Color, textpos.Rotation, Convert.ToInt32(((Racami.Common.customTexts)custom).styles.font.size));
4271 }
4272 }
4273 catch (Exception ex)
4274 {
4275
4276 string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
4277 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Barcode errors around " + message);
4278 throw new Exception($"{message}");
4279 }
4280 #endregion
4281 }
4282 else
4283 this.AddAnnots(page, String.IsNullOrEmpty(TextValue) ? "" : TextValue, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height);
4284
4285
4286 }
4287 catch (Exception ex)
4288 {
4289 string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
4290 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(message);
4291 throw new Exception($"There was a fatal error in engineering and it was forced to stop. {message}");
4292 }
4293 #endregion
4294 });
4295
4296 customtexts.Clear();
4297 }
4298 #endregion
4299
4300
4301
4302 }
4303
4304 public void DoVariableWork(List<Racami.Common.variables> pvariables, PdfPage page, EngineerConfig config, List<FontFamilyStage> fontDic, System.Data.DataRow spaage, EngineObject.CISObjects CISObject)
4305 {
4306 float x;
4307 float y;
4308 #region variables
4309 int? variableCount = pvariables?.Count;
4310 if (variableCount > 0)
4311 {
4312 Racami.Common.variables[] variablearray = new Racami.Common.variables[(int)variableCount];
4313
4314 pvariables.CopyTo(variablearray);
4315
4316 List<Racami.Common.variables> variables = Substitute(CombineSameline(new List<Racami.Common.variables>(variablearray)), spaage, CISObject);
4317 // System.Threading.Tasks.Parallel.ForEach(variables, (custom)=>
4318 variables.ForEach(custom =>
4319 {
4320 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Variables done..");
4321 #region variables
4322 try
4323 {
4324 string TextValue = custom.value;
4325
4326 TextPositions textpos = textpositions.Find(txp => txp.Name == custom.id) == null ? null : textpositions.Find(txp => txp.Name == custom.id);
4327
4328 if (textpos == null)
4329 {
4330 textpos = new TextPositions();
4331 textpos.Name = custom.id;
4332
4333 textpos.X = (float)Convert.ToDouble(custom.styles.position.left) / (float)((config.scale == 0) ? 1 : config.scale); //(float)Convert.ToDouble(((Racami.Common.variables)custom).styles.position.left) / (config.scale == 0 ? 1 : config.scale);
4334 //(page.Size.Height) -
4335 textpos.Y = (page.GetPageSize().GetHeight() - (float)Convert.ToDouble(custom.styles.position.top) / (float)((config.scale == 0) ? 1 : config.scale) - (float)Convert.ToDouble((custom.styles.size.height.ToString() == "auto") ? custom.styles.font.size : custom.styles.size.height.ToString()) / (float)((config.scale == 0) ? 1 : config.scale));
4336 // ((float)Convert.ToDouble(((Racami.Common.variables)custom).styles.position.top) / (config.scale == 0 ? 1 : config.scale)) -
4337 // ((float)Convert.ToDouble(((Racami.Common.variables)custom).styles.size.height.ToString() == "auto" ? ((Racami.Common.variables)custom).styles.font.size : ((Racami.Common.variables)custom).styles.size.height.ToString()) / (config.scale == 0 ? 1 : config.scale)));
4338 textpos.Width = (float)Convert.ToDouble((float)Convert.ToDouble((!(custom.styles.size.width.ToString() == "auto")) ? custom.styles.size.width.ToString() : (string.IsNullOrEmpty(TextValue) ? "".Length.ToString() : TextValue.Length.ToString())) / (float)((config.scale == 0) ? 1 : config.scale));//(float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.variables)custom).styles.size.width.ToString() == "auto" ? String.IsNullOrEmpty(TextValue) ? "".Length.ToString() : TextValue.Length.ToString() : ((Racami.Common.variables)custom).styles.size.width.ToString()) / (config.scale == 0 ? 1 : config.scale));
4339 textpos.Height = (float)Convert.ToDouble((float)Convert.ToDouble((custom.styles.size.height.ToString() == "auto") ? custom.styles.font.size : custom.styles.size.height.ToString()) / (float)((config.scale == 0) ? 1 : config.scale));//(float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.variables)custom).styles.size.height.ToString() == "auto" ? ((Racami.Common.variables)custom).styles.font.size :
4340 //((Racami.Common.variables)custom).styles.size.height.ToString()) / (config.scale == 0 ? 1 : config.scale));
4341
4342 int[] RGB = GetRGB(((Racami.Common.variables)custom).styles.font.color);
4343 textpos.Color = new DeviceRgb(RGB[0], RGB[1], RGB[2]);
4344
4345 textpos.fontstyle = ((Racami.Common.variables)custom).styles.font.style;
4346 textpos.fontweight = ((Racami.Common.variables)custom).styles.font.weight;
4347
4348 Type var = ((Racami.Common.variables)custom).styles.font.family.GetType();
4349 var rr = ((Racami.Common.variables)custom).styles.font.family.GetType() == typeof(Newtonsoft.Json.Linq.JArray) ? ((Newtonsoft.Json.Linq.JArray)((Racami.Common.variables)custom).styles.font.family).ToObject<List<String>>() : null;
4350
4351 string fontFamily = rr == null ?
4352 ((String)((Racami.Common.variables)custom).styles.font.family).ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "") :
4353 rr[0].ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "");
4354 //now we need to do a lookup and get the values from the record details to substitute
4355 textpos.Fonts = fontDic.FindAll(f => f.FamilyName.ToLower().Contains(fontFamily.ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(", monospace", "").Replace(", monospace_italic", "").Replace(", monospace_bold", "")));
4356 textpos.Rotation = ((Racami.Common.variables)custom).styles.rotate;
4357 textpositions.Add(textpos);
4358 }
4359
4360
4361 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(string.Format("text: ={0}=, x: ={1}=, y: ={2}=, font={3}=", TextValue, textpos.X, textpos.Y, textpos.Fonts[0].FamilyName));
4362
4363 //x = (float)Convert.ToDouble(((Racami.Common.variables)vari).styles.position.left) / (config.scale == 0 ? 1 : config.scale);
4364 ////(page.Size.Height) -
4365
4366 //y = (
4367 // ((float)Convert.ToDouble(((Racami.Common.variables)vari).styles.position.top) / (config.scale == 0 ? 1 : config.scale)) -
4368 // ((float)Convert.ToDouble(((Racami.Common.variables)vari).styles.size.height.ToString() == "auto" ? ((Racami.Common.variables)vari).styles.font.size : ((Racami.Common.variables)vari).styles.size.height.ToString()) / (config.scale == 0 ? 1 : config.scale)));
4369 //float width = (float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.variables)vari).styles.size.width.ToString() == "auto" ? String.IsNullOrEmpty(TextValue) ? "".Length.ToString() : TextValue.Length.ToString() : ((Racami.Common.variables)vari).styles.size.width.ToString()) / (config.scale == 0 ? 1 : config.scale));
4370 //float height = (float)Convert.ToDouble((float)Convert.ToDouble(((Racami.Common.variables)vari).styles.size.height.ToString() == "auto" ? ((Racami.Common.variables)vari).styles.font.size :
4371 // ((Racami.Common.variables)vari).styles.size.height.ToString()) / (config.scale == 0 ? 1 : config.scale));
4372
4373 ////only for debugging purposes
4374 //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("text: ={0}=, x: ={1}=, y: ={2}=", TextValue, x, y));
4375
4376 //int[] RGB = GetRGB(((Racami.Common.variables)vari).styles.font.color);
4377 //org.pdfclown.documents.contents.colorSpaces.DeviceRGBColor col = new org.pdfclown.documents.contents.colorSpaces.DeviceRGBColor(RGB[0] / 255d, RGB[1] / 255d, RGB[2] / 255d);
4378
4379 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info("Color set now move on");
4380 // int rot = 0;
4381 // try
4382 // {
4383 // rot = ((Racami.Common.variables)vari).styles.rotate;
4384 // }
4385 // catch
4386 // {
4387 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info("No rotation was selected so default to 0");
4388 // }
4389
4390
4391 // string fontstyle = ((Racami.Common.variables)vari).styles.font.style;
4392 // string fontweight = ((Racami.Common.variables)vari).styles.font.weight;
4393
4394 // Type var = ((Racami.Common.variables)vari).styles.font.family.GetType();
4395 // var rr = ((Racami.Common.variables)vari).styles.font.family.GetType() == typeof(Newtonsoft.Json.Linq.JArray) ? ((Newtonsoft.Json.Linq.JArray)((Racami.Common.variables)vari).styles.font.family).ToObject<List<String>>() : null;
4396
4397
4398 // string fontFamily = rr == null ?
4399 //((String)((Racami.Common.variables)vari).styles.font.family).ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "") :
4400 // rr[0].ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "");
4401
4402 // string fontFamily = ((Racami.Common.variables)vari).styles.font.family.GetType() == typeof(String) ?
4403 // ((String)((Racami.Common.variables)vari).styles.font.family).ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "") :
4404 //((List<String>)((Racami.Common.variables)vari).styles.font.family)[0].ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "");
4405
4406
4407 // ((Racami.Common.variables)vari).styles.font.family.ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" new, monospace", "").Replace(" new, monospace_italic", "").Replace(" new, monospace_bold", "");
4408 //now we need to do a lookup and get the values from the record details to substitute
4409 // List<FontFamilyStage> fnt = fontDic.FindAll(f => f.FamilyName.ToLower().Contains(fontFamily.ToLower().Replace(", sans-serif", "").Replace(", serif", "").Replace(" New, monospace", "").Replace(" New, monospace_italic", "").Replace(" New, monospace_bold", "")));
4410
4411
4412 //now we need to do a lookup and get the values from the record details to substitute
4413 //if (String.IsNullOrEmpty(custom.barcodeType))
4414 //{
4415
4416
4417 // if (!custom.isComment)
4418 // this.AddText(page, String.IsNullOrEmpty(TextValue) ? "" : TextValue, (int)x, (int)y, (int)width, (int)height,
4419 // col,
4420 // Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size), fnt[0], fontstyle, fontweight, rot);
4421 // else
4422 // this.AddAnnots(page, String.IsNullOrEmpty(TextValue) ? "" : TextValue, (int)x, (int)y, (int)width, (int)height);
4423
4424
4425 //}
4426 //else
4427 //{
4428 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info("Barcodes");
4429 // #region barcodes
4430 // try
4431 // {
4432 // //now we determine what barcode it is and load appropriately.
4433 // if (custom?.barcodeType == "IMB")
4434 // {
4435 // fnt = fontDic.FindAll(f => f.FamilyName.ToLower().Contains("imb"));
4436
4437 // //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("bars value: ={0}=", vari.value));
4438 // String bars = custom.value;// Racami.Common.OneCode.OneCODE.OneCodeDecode(vari.value);
4439 // if (!String.IsNullOrEmpty(bars))
4440 // //this.AddIMB(bars, page, (int)x, (int)y, (int)width, (int)height,rot, Convert.ToInt32(((Racami.Common.customTexts)custom).styles.font.size));
4441 // this.AddText(page, String.IsNullOrEmpty(bars) ? "" : bars, (int)x, (int)y, (int)width, (int)height, col, Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size), fnt[0], fontstyle, fontweight, rot);
4442
4443 // ////if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("bars value: ={0}=", vari.value));
4444 // //String bars = Racami.Common.OneCode.OneCODE.OneCodeDecode(vari.value);
4445 // //if (!String.IsNullOrEmpty(bars))
4446 // // this.AddIMB(bars, page, (int)x, (int)y, (int)width, (int)height,rot, Convert.ToInt32(((Racami.Common.variables)vari).styles.font.size));
4447 // }
4448 // else if (custom?.barcodeType == "128")
4449 // {
4450 // this.Add128(custom.value, page, (int)x, (int)y, (int)width, (int)height, col, rot, Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size));
4451 // }
4452 // else if (custom?.barcodeType == "3of9")
4453 // {
4454 // this.Add3of9(custom.value, page, (int)x, (int)y, (int)width, (int)height, col);
4455 // }
4456 // else if (custom?.barcodeType == "2D")
4457 // {
4458
4459 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info("The text value is " + custom.value);
4460 // this.AddDataMatrix(custom.value, page, (int)x, (int)y, (int)width, (int)height, col, rot, Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size));
4461 // }
4462 // }
4463 // catch (Exception ex)
4464 // {
4465 // if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info("Barcode errors around " + ex.Message);
4466 // }
4467 // #endregion
4468
4469 //}
4470
4471 if (custom.condition == "CUSTOM")
4472 {
4473 if (!String.IsNullOrEmpty(custom.logic))
4474 {
4475 //now we need to look at the custom logic to see what we want to execute
4476 TextValue = Docustomlogic(custom.logic.Contains(TextValue) ? custom.logic.Replace(TextValue, "") : custom.logic, CISObject, spaage, page);
4477 // var newvalue = TextAssignment(custom.logic, spaage, CISObject);
4478 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Did custom work for this");
4479 }
4480 }
4481 if (!custom.isComment && String.IsNullOrEmpty(custom.barcodeType))
4482 this.AddText(page, String.IsNullOrEmpty(TextValue) ? "" : TextValue, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height,
4483 textpos.Color,
4484 Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size), textpos.Fonts[0], textpos.fontstyle, textpos.fontweight, textpos.Rotation);
4485 else if (!String.IsNullOrEmpty(custom.barcodeType))
4486 {
4487 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Barcodes");
4488 #region barcodes
4489 try
4490 {
4491 //now we determine what barcode it is and load appropriately.
4492 if (custom?.barcodeType == "IMB")
4493 {
4494 textpos.Fonts = fontDic.FindAll(f => f.FamilyName.ToLower().Contains("imb"));
4495
4496 //if(EngineObject.CISObjects.MasterLog !=null) EngineObject.CISObjects.MasterLog.Info(string.Format("bars value: ={0}=", vari.value));
4497 String bars = String.IsNullOrEmpty(TextValue) ? "" : TextValue;// Racami.Common.OneCode.OneCODE.OneCodeDecode(custom.value);
4498 if (!String.IsNullOrEmpty(bars))
4499 //this.AddIMB(bars, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Rotation, Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size));
4500 this.AddText(page, String.IsNullOrEmpty(bars) ? "" : bars, (int)textpos.X, (int)textpos.Y, (int)textpos.Width + 100, (int)textpos.Height, textpos.Color, Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size), textpos.Fonts[0], textpos.fontstyle, textpos.fontweight, textpos.Rotation);
4501 }
4502 else if (custom?.barcodeType == "128" || custom?.barcodeType == "128 No Text")
4503 {
4504 this.Add128(String.IsNullOrEmpty(TextValue) ? "" : TextValue, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Color, textpos.Rotation, Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size));
4505 }
4506 else if (custom?.barcodeType == "3of9")
4507 {
4508 this.Add3of9(String.IsNullOrEmpty(TextValue) ? "" : TextValue, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Color);
4509 }
4510 else if (custom?.barcodeType == "2D")
4511 {
4512
4513 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("The text value is " + custom.value);
4514 this.AddDataMatrix(String.IsNullOrEmpty(TextValue) ? "" : TextValue, page, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height, textpos.Color, textpos.Rotation, Convert.ToInt32(((Racami.Common.variables)custom).styles.font.size));
4515 }
4516 }
4517 catch (Exception ex)
4518 {
4519 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("Barcode errors around " + ex.Message);
4520 }
4521 #endregion
4522 }
4523 else
4524 this.AddAnnots(page, String.IsNullOrEmpty(TextValue) ? "" : TextValue, (int)textpos.X, (int)textpos.Y, (int)textpos.Width, (int)textpos.Height);
4525
4526 }
4527 catch (Exception ex)
4528 {
4529 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info(ex.Message);
4530 }
4531 #endregion });
4532 });
4533
4534 variables.Clear();
4535 }
4536 #endregion
4537
4538 }
4539 #endregion
4540
4541
4542 public void Engineer(System.Xml.XmlNode pdfitem, EngineObject.CISObjects CISObject)
4543 {
4544 System.Data.DataTable dt = CISObject.NewRecordDetails;
4545 Racami.Common.Globals glob = new Racami.Common.Globals();
4546 String filepath = CISObject.FilePath;
4547
4548 if (!System.IO.File.Exists(filepath))
4549 throw new Exception(String.Format("{0} did not exist this is a fatal process for this step!!", filepath));
4550
4551
4552 string pathofjson = pdfitem?.Attributes["json"] != null ? pdfitem?.Attributes["json"]?.Value.Replace(@"\\", @"\") : pdfitem?.SelectSingleNode("fields")?.Attributes["json"]?.Value;
4553 string overridetoggle = pdfitem?.Attributes["template_overide"] != null ? pdfitem?.Attributes["template_override"]?.Value.Replace(@"\\", @"\") : pdfitem?.SelectSingleNode("fields")?.Attributes["template_override"]?.Value;
4554
4555 if (overridetoggle == "true")
4556 {
4557 pathofjson = pdfitem?.Attributes["json"] != null ? pdfitem?.Attributes["json"]?.Value.Replace(@"\\", @"\") : pdfitem?.SelectSingleNode("fields")?.Attributes["json"]?.Value;
4558 }
4559 else
4560 {
4561
4562
4563 if (!CISObject.Keys.Keys.Contains("AlchemePDFEngineeringTemplate"))
4564 {
4565 //check to see if it is in the optional fields.. if so use it.
4566 try
4567 {
4568 glob.ConnectionString = CISObject.ConnectionString;
4569 glob.Init();
4570
4571 Jobs jo = (from jobs in CISObject.AlchemeDBConnection.Jobs where jobs.File_id == CISObject.Files[0].File_id select jobs)?.FirstOrDefault();
4572 if (CISObject.job != null)
4573 CISObject?.Jobs?.Clear();
4574 else
4575 CISObject.Jobs = new List<Jobs>();
4576
4577 CISObject?.Jobs?.Add(jo);
4578
4579 if (CISObject.JobDetails == null)
4580 CISObject.JobDetails = new List<Job_option_details>(from jobs in CISObject.AlchemeDBConnection.Job_option_details where jobs.Job_id == jo.Job_id select jobs);
4581
4582 string productss = (from products in CISObject.AlchemeDBConnection.Products where products.Product_id == jo.Product_id && products.Client_id == jo.Client_id select products).FirstOrDefault().Product_num;
4583
4584 pathofjson = glob.GetProductCustomFieldValues("AlchemePDFEngineeringTemplate", productss);
4585 if (String.IsNullOrEmpty(pathofjson))
4586 pathofjson = pdfitem?.Attributes["json"] != null ? pdfitem?.Attributes["json"]?.Value.Replace(@"\\", @"\") : pdfitem?.SelectSingleNode("fields")?.Attributes["json"]?.Value;
4587 }
4588 catch (Exception ex)
4589 {
4590
4591 if (EngineObject.CISObjects.MasterLog != null) EngineObject.CISObjects.MasterLog.Info("AlchemePDFEngineeringTemplate was not present so the template for optional field is not present");
4592 //do nothing here
4593 pathofjson = pdfitem?.Attributes["json"] != null ? pdfitem?.Attributes["json"]?.Value.Replace(@"\\", @"\") : pdfitem?.SelectSingleNode("fields")?.Attributes["json"]?.Value;
4594 }
4595 }
4596 else
4597 pathofjson = String.IsNullOrEmpty(CISObject.Keys["AlchemePDFEngineeringTemplate"].ToString()) ? CISObject.Keys["AlchemePDFEngineeringTemplate"] as string : pdfitem?.Attributes["json"] != null ? pdfitem?.Attributes["json"]?.Value.Replace(@"\\", @"\") : pdfitem?.SelectSingleNode("fields")?.Attributes["json"]?.Value;
4598
4599 }
4600 DoEngineering(dt, filepath, pathofjson, CISObject.joblevel == true ? "Job" : "Details", CISObject.ConnectionString, CISObject);
4601 }
4602 }
4603}