summaryrefslogtreecommitdiffstats
path: root/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfReportHandler.java
blob: c27ba0c5656dc44fcff1129b07361ef11a51bdb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
/*-
 * ================================================================================
 * eCOMP Portal SDK
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ================================================================================
 */

/* ===========================================================================================
 * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I> 
 * Raptor : This tool is used to generate different kinds of reports with lot of utilities
 * ===========================================================================================
 *
 * -------------------------------------------------------------------------------------------
 * PdfReportHandler.java - This class is used to generate reports in PDF using iText 
 * -------------------------------------------------------------------------------------------
 *
 *
 * Changes
 * -------
 * 14-Jul-2009 : Version 8.4 (Sundar); <UL> 
 *                                     <LI> Dashboard reports can be downloaded with each report occupying separate page including its charts. </LI>
 *                                     </UL>   
 *
 */
package org.openecomp.portalsdk.analytics.model.pdf;

import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.openecomp.portalsdk.analytics.error.RaptorException;
import org.openecomp.portalsdk.analytics.error.ReportSQLException;
import org.openecomp.portalsdk.analytics.model.ReportHandler;
import org.openecomp.portalsdk.analytics.model.ReportLoader;
import org.openecomp.portalsdk.analytics.model.base.IdNameValue;
import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition;
import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime;
import org.openecomp.portalsdk.analytics.system.AppUtils;
import org.openecomp.portalsdk.analytics.system.ConnectionUtils;
import org.openecomp.portalsdk.analytics.system.Globals;
import org.openecomp.portalsdk.analytics.util.AppConstants;
import org.openecomp.portalsdk.analytics.util.DataSet;
import org.openecomp.portalsdk.analytics.util.HtmlStripper;
import org.openecomp.portalsdk.analytics.util.Utils;
import org.openecomp.portalsdk.analytics.view.ColumnHeader;
import org.openecomp.portalsdk.analytics.view.ColumnHeaderRow;
import org.openecomp.portalsdk.analytics.view.DataRow;
import org.openecomp.portalsdk.analytics.view.DataValue;
import org.openecomp.portalsdk.analytics.view.HtmlFormatter;
import org.openecomp.portalsdk.analytics.view.ReportData;
import org.openecomp.portalsdk.analytics.view.RowHeader;
import org.openecomp.portalsdk.analytics.view.RowHeaderCol;
import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType;
import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.ElementTags;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

/**
 * @author mwliu and sundar
 *
 */
public class PdfReportHandler extends org.openecomp.portalsdk.analytics.RaptorObject{

	/**
	 * 
	 */
	private PdfBean pb;
	private HtmlStripper strip = new HtmlStripper();
	private static final int RetryCreateNewImage = 3;
	private int retryCreateNewImageCount=0;
	EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PdfReportHandler.class);

	private String FONT_FAMILY = "Arial";
	private int FONT_SIZE = 9;
	
	public PdfReportHandler() {	}

	public void createPdfFileContent(HttpServletRequest request, HttpServletResponse response, int type) throws IOException, RaptorException {

		Document document = new Document();
		ReportHandler rh = new ReportHandler();
        String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date());
		String pdfFName = "";
		String user_id = AppUtils.getUserID(request);
		response.reset();
		response.setContentType("application/pdf");
		OutputStream outStream = response.getOutputStream();
        
        String formattedReportName = "";
        PdfWriter writer = null;
        ReportRuntime firstReportRuntimeObj = null;
        int returnValue = 0;

        ReportRuntime rr = null;
        if(rr==null) rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
        
        boolean isDashboard = false;
        if ((request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) && ( ((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())) ) {
        	isDashboard = true;
        }
		if(isDashboard) {
			try {
					String reportID = (String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID);
					ReportRuntime rrDash = rh.loadReportRuntime(request, reportID, true, 1);
					pb = preparePdfBean(request,rrDash);
		
					// Setting pb Values
			        document.setPageSize(PageSize.getRectangle(pb.getPagesize()));
					if(!pb.isPortrait()) // get this from properties file
						document.setPageSize(document.getPageSize().rotate());
			        
			        //			
					writer = PdfWriter.getInstance(document, response.getOutputStream());
					writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark
					document.open();

					formattedReportName = new HtmlStripper().stripSpecialCharacters(rrDash.getReportName());
			        if(pb.isAttachmentOfEmail())
			        	response.setHeader("Content-disposition", "inline");
			        else
			        	response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf");
					
					pdfFName = "dashboard"+formattedReportName+formattedDate+user_id+".pdf";
					Map reportRuntimeMap = null;
					Map reportDataMap = null;
					Map reportDisplayTypeMap = null;

					reportRuntimeMap 			= (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
					reportDataMap 				= (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
					reportDisplayTypeMap 		= (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);

					if(reportRuntimeMap!=null) {
						//ServletOutputStream sos = response.getOutputStream();
						Set setReportRuntime 		= reportRuntimeMap.entrySet();
						Set setReportDataMap 		= reportDataMap.entrySet();
						Set setReportDisplayTypeMap = reportDisplayTypeMap.entrySet();
						
						Iterator iter2 = setReportDataMap.iterator();
						Iterator iter3 = setReportDisplayTypeMap.iterator();
		                int count = 0;
						for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) {
							count++;
							Map.Entry entryData 		= (Entry) iter2.next();
							Map.Entry entry 			= (Entry) iter.next();
							Map.Entry entryCheckChart	= (Entry) iter3.next();
							//String rep_id 				= (String) entry.getKey();
							ReportRuntime rrDashRep 	= (ReportRuntime) entry.getValue();
							
							if(count == 1)  { 
								firstReportRuntimeObj = (ReportRuntime) entry.getValue();
								if(pb.isCoverPageIncluded()) {
									document = paintDashboardCoverPage(document, rrDash, firstReportRuntimeObj, request);
								}
							}
							ReportData rdDashRep 		= (ReportData) entryData.getValue();
					        int col = 0;
					        //pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart());
							if( ((rrDashRep.getChartType()).trim().length()>0 && rrDashRep.getDisplayChart()) && entryCheckChart.getValue().toString().equals("c")) {
								document.newPage();
								pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName());
								paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+  pb.getUserId()+"_"+request.getSession().getId()+"_"+rrDashRep.getReportID()+".png", rrDashRep);
							} else {
								document.newPage();
								pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName());
								paintPdfData(request, document,rdDashRep,rrDashRep, "");
							}
						}
					
				}
			} catch (DocumentException dex) {dex.printStackTrace();}
			catch (RaptorException rex) {rex.printStackTrace();}
		} else {

			//ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
			//ReportData    rd = (ReportData)    request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
			rr = null;
			ReportData    rd = null;
			String parent = "";
			int parentFlag = 0;
			if(!nvl(request.getParameter("parent"), "").equals("N")) parent = nvl(request.getParameter("parent"), "");
			if(parent.startsWith("parent_")) parentFlag = 1;
			if(parentFlag == 1) {
				rr = (ReportRuntime) request.getSession().getAttribute(parent+"_rr");
				rd = (ReportData) request.getSession().getAttribute(parent+"_rd");
			}
			if(rr==null) rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
			if(rd==null) rd = (ReportData)    request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
			
			pb = preparePdfBean(request,rr);
			FONT_FAMILY = rr.getPDFFont();
			FONT_SIZE = rr.getPDFFontSize();
			//System.out.println(pb);
					
			formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName());
			
			
			
	        response.setContentType("application/pdf");
	        if(pb.isAttachmentOfEmail())
	        	response.setHeader("Content-disposition", "inline");
	        else
	        	response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf");
		        
			document.setPageSize(PageSize.getRectangle(pb.getPagesize()));
			
			if(!pb.isPortrait()) // get this from properties file
				document.setPageSize(document.getPageSize().rotate());
	
			try {
				
				writer = PdfWriter.getInstance(document, outStream);
				writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark
				document.open();
				
				//System.out.println("Document 1 " + document);
				if(pb.isCoverPageIncluded()) {
					document = paintCoverPage(document, rr, request);
				}
				
				//boolean isImageRotate = false;
				//System.out.println("Document 2 " + document);
	
				if(pb.isDisplayChart()) {
					paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+  pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+".png", rr);
				}
				//System.out.println("Document 4" + document);
	
				document.newPage();
		        if(type == 3 && rr.getSemaphoreList()==null && !(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) ) { //type = 3 is whole
			        String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE);
			        returnValue = paintPdfData(request, document, rd, rr, sql_whole);
		        } else if(type == 2) {
		        	returnValue = paintPdfData(request, document, rd, rr, "");
		        } else {
			        //String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE);
					int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
					String action = request.getParameter(AppConstants.RI_ACTION);

					if(!(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) && !action.endsWith("session"))
						rd 		= rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, false /*download*/);
					if(rr.getSemaphoreList()!=null) {
						rd   =  rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, true);
						returnValue = paintPdfData(request, document, rd, rr, "");
					} else {
						returnValue = paintPdfData(request, document, rd, rr, rr.getWholeSQL());
					}
					
					
		        }
		        
				
				//paintPdfData(document,rd,rr);
		        
			
			} catch (DocumentException de) {
	            de.printStackTrace();
	            //System.err.println("document: " + de.getMessage());
	        }
			
		}
		document.close();
    	int mb = 1024*1024;
    	Runtime runtime = Runtime.getRuntime();		
    	logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####"));
    	logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:"
    			+ (runtime.maxMemory() - runtime.freeMemory()) / mb));
    	logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:"
    			+ runtime.freeMemory() / mb));
    	logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb));
    	logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb));

	}
	
	private Document paintCoverPage(Document doc, ReportRuntime rr, HttpServletRequest request) throws IOException, DocumentException {
		
		//System.out.println("PDFREPORTHANDLER STARTED ... " );
		if(nvl(rr.getPdfImg()).length()>0) {
			Image image1 = Image.getInstance(AppUtils.getExcelTemplatePath()+"../../"+AppUtils.getImgFolderURL()+rr.getPdfImg());
			image1.scalePercent(20f, 20f);
			doc.add(image1);
		}
		float firstColumnSize = Globals.getCoverPageFirstColumnSize();
		float[] relativeWidths = {firstColumnSize,1f-firstColumnSize};
		PdfPTable table = new PdfPTable(relativeWidths);
		table.getDefaultCell().setBorderWidth(0);
		addEmptyRows(table,6);
		HTMLWorker worker = new HTMLWorker(doc);
    	StyleSheet style = new StyleSheet();
    	style.loadTagStyle("body", "leading", "16,0");
    	StringBuffer reportDescrBuf = new StringBuffer("");
    	ArrayList descr = HTMLWorker.parseToList(new StringReader(nvl(rr.getReportDescr())), style);
    	ArrayList paraList = null;
    	   if(nvl(rr.getReportTitle()).length()>0) {
   			add2Cells(table,"Report Title 	: ",nvl(rr.getReportTitle()));
   			if(nvl(rr.getReportSubTitle()).length()>0) {
   				add2Cells(table,"Report Sub-Title 	: ",nvl(rr.getReportSubTitle()));
   				System.out.println("Adding the report sub-title ");
   			}
   			
    	   } else {
			add2Cells(table,"Report Name 	: ",nvl(rr.getReportName()));
    	   }
			if((descr!=null && descr.size()>0)) {
				paraList = (com.lowagie.text.Paragraph)descr.get(0);
				for (int i=0 ; i<paraList.size(); i++) {
					reportDescrBuf.append(paraList.get(i));
				}
				
			}
			add2Cells(table,"Description 	: ",reportDescrBuf.toString());
		if(Globals.getSessionInfoForTheCoverPage().length()>0) {
			String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(",");
				String name=nameValue[0];
				String value=nameValue[1];
				add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value))));
		}
		
		if(Globals.isCreatedOwnerInfoNeeded()) {
			add2Cells(table,"Created By 	: ",nvl(AppUtils.getUserName(rr.getCreateID())));
			add2Cells(table,"Owner 			: ",nvl(AppUtils.getUserName(rr.getOwnerID())));
		}
		if(Globals.displayLoginIdForDownloadedBy())
			add2Cells(table,"Downloaded by 	: ",nvl(AppUtils.getUserBackdoorLoginId(request)));
		else
			add2Cells(table,"Downloaded by 	: ",nvl(AppUtils.getUserName(AppUtils.getUserID(request))));
		
		addEmptyRows(table,1);

		boolean isFirstRow = true;
        ArrayList al = rr.getParamNameValuePairsforPDFExcel(request, 1);
        if(al.size()<=0) {
        	al = (ArrayList) request.getSession().getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
        }

		Iterator it = al.iterator();
		addEmptyRows(table,1);
		//if(!Globals.customizeFormFieldInfo()) {
		if(rr.getFormFieldComments(request).length()<=0) {
			while(it.hasNext()) {
		
				if(isFirstRow) {
			add2Cells(table, "Run-time Criteria : ", " ");
					isFirstRow = false;
				}
					
				IdNameValue value = (IdNameValue)it.next();
				if(!value.getId().trim().equals("BLANK"))
					//System.out.println("PDFREPORTHANDLER " + value.getId()+" : "+value.getName());
					add2Cells(table, value.getId()+" : ",value.getName().replaceAll("~",","));
					//add2Cells(table, rr.getFormFieldComments(request), " ");
			}
			addEmptyRows(table,1);
			doc.add(table);
			
		} else {
	        it = al.iterator();
	        if(it.hasNext()) {
	        	//add2Cells(table, "Run-time Criteria : ", " ");
	        	addEmptyRows(table,1);	        	
	        	doc.add(table);
	        	//com.lowagie.text.html.HtmlParser.parse(doc, new StringReader(rr.getFormFieldComments(request)));
	        	ArrayList p = HTMLWorker.parseToList(new StringReader(rr.getFormFieldComments(request).replaceAll("~",",")), style);
	        	
	        	 for (int k = 0; k < p.size(); ++k){
	        	    doc.add((com.lowagie.text.Element)p.get(k));
	        	 }
	        }
		} 
		
		return doc;		
	}
	

	private Document paintDashboardCoverPage(Document doc, ReportRuntime rrDashRep, ReportRuntime firstReportRuntimeObj, HttpServletRequest request) throws IOException, DocumentException {
		
		//System.out.println("PDFREPORTHANDLER STARTED ... " );
		float firstColumnSize = Globals.getCoverPageFirstColumnSize();
		float[] relativeWidths = {firstColumnSize,1f-firstColumnSize};
		PdfPTable table = new PdfPTable(relativeWidths);
		table.getDefaultCell().setBorderWidth(0);
		addEmptyRows(table,6);

		add2Cells(table,"Report Name : ",rrDashRep.getReportName());
		add2Cells(table,"Description : ",rrDashRep.getReportDescr());
		if(Globals.getSessionInfoForTheCoverPage().length()>0) {
			String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(",");
				String name=nameValue[0];
				String value=nameValue[1];
				add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value))));
		}
		
		if(Globals.isCreatedOwnerInfoNeeded()) {
			add2Cells(table,"Created By : ",AppUtils.getUserName(rrDashRep.getCreateID()));
			add2Cells(table,"Owner : ",AppUtils.getUserName(rrDashRep.getOwnerID()));
		}
		if(Globals.displayLoginIdForDownloadedBy())
			add2Cells(table,"Downloaded by : ",AppUtils.getUserBackdoorLoginId(request));
		else
			add2Cells(table,"Downloaded by : ",AppUtils.getUserName(request));
		
		addEmptyRows(table,1);

		boolean isFirstRow = true;
		ArrayList al = firstReportRuntimeObj.getParamNameValuePairsforPDFExcel(request, 2);
		Iterator it = al.iterator();
		addEmptyRows(table,1);
		//if(!Globals.customizeFormFieldInfo()) {
		if(firstReportRuntimeObj.getFormFieldComments(request).length()<=0) {
			while(it.hasNext()) {
		
				if(isFirstRow) {
					add2Cells(table, "Run-time Criteria : ", " ");
					isFirstRow = false;
				}
					
				IdNameValue value = (IdNameValue)it.next();
				if(!value.getId().trim().equals("BLANK"))
					//System.out.println("PDFREPORTHANDLER " + value.getId()+" : "+value.getName());
					add2Cells(table, value.getId()+" : ",value.getName());
					//add2Cells(table, rr.getFormFieldComments(request), " ");
			}
			addEmptyRows(table,1);
			doc.add(table);
			
		} else {
	        it = al.iterator();
	        if(it.hasNext()) {
	        	//add2Cells(table, "Run-time Criteria : ", " ");
	        	addEmptyRows(table,1);	        	
	        	doc.add(table);
	        	//com.lowagie.text.html.HtmlParser.parse(doc, new StringReader(rr.getFormFieldComments(request)));
	        	HTMLWorker worker = new HTMLWorker(doc);
	        	StyleSheet style = new StyleSheet();
	        	style.loadTagStyle("body", "leading", "16,0");
	        	ArrayList p = HTMLWorker.parseToList(new StringReader(firstReportRuntimeObj.getFormFieldComments(request)), style);
	        	
	        	 for (int k = 0; k < p.size(); ++k){
	        	    doc.add((com.lowagie.text.Element)p.get(k));
	        	 }
	        }
		} 
		
		return doc;		
	}
	
	
	public static void addEmptyRows(PdfPTable table, int rows) throws DocumentException {
		for (int i=0; i<rows; i++) 
			for(int j=0;j<table.getAbsoluteWidths().length;j++)
				table.addCell(new Paragraph(" "));
		
	}
	
	private void add2Cells(PdfPTable table, String key, String value) {
		
		PdfPCell cell;
		cell = new PdfPCell(new Paragraph(key));
		cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
		cell.setBorderWidth(0f);
		table.addCell(cell);
		
		cell = new PdfPCell(new Paragraph(value));
		cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
		cell.setBorderWidth(0f);
		table.addCell(cell);
	}

	private void paintPdfImage(HttpServletRequest request, Document document, String fileName, ReportRuntime rr) 
				throws DocumentException
	{
		
		ArrayList images = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false, rr);
		//Image image = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false);
		PdfPTable table =  null;
		PdfPCell cellValue = null;
		if(images!=null) {
			
	        for (int i = 0; i < images.size(); i++) {
	        	table = new PdfPTable(1);
	        	cellValue = new PdfPCell();
	        	cellValue.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
                Image image = (Image) images.get(i);				
    			image.setAlignment(Image.ALIGN_CENTER);
    			//System.out.println("Document 3 " + document + " i-" + i);
    			if(i%2 ==0)
    			document.newPage();
    			//System.out.println("Document 31 " + document);
    			cellValue.setImage(image);
    			//table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
    			table.addCell(cellValue);
    			//System.out.println("Document 32 " + document + "table  " + table);
    			document.add(table);
       			//System.out.println("Document 33 " + document);    			
			}
		}
	}
	
	private ArrayList getImage(HttpServletRequest request, String fileName, boolean isGenerateNewImage, ReportRuntime rr) {
		ArrayList images = new ArrayList();
		if(!isGenerateNewImage) {
			try {
				Image image = Image.getInstance(fileName);
				images.add(image);
				return images;
			} 
			catch (MalformedURLException e) {
				isGenerateNewImage = true;
				//e.printStackTrace();			
			} 
			catch (BadElementException e) {
				isGenerateNewImage = true;
				//e.printStackTrace();

			} catch (FileNotFoundException e) {
				isGenerateNewImage = true;
				//e.printStackTrace();
			} catch (IOException e) {
				isGenerateNewImage = true;
				//e.printStackTrace();
		    }			
		}
		
		if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){
			retryCreateNewImageCount++;
			return generateNewImage(request, rr);
			//return getImage(request,fileName, false);
		}
		
		return null;
			
	}

	private ArrayList generateNewImage(HttpServletRequest request, ReportRuntime rr) {
		ArrayList images = new ArrayList();
		try {
			//ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
			DataSet ds = null;
			if(request.getSession().getAttribute(AppConstants.RI_CHART_DATA)!=null) {
				ds = (DataSet) request.getSession().getAttribute(AppConstants.RI_CHART_DATA);
			} else {
				ds = rr.loadChartData(pb.getUserId(),request);
			}
		    String downloadFileName = "";
			HashMap additionalChartOptionsMap = new HashMap();
			String chartType = nvl(rr.getChartType());
			if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
				additionalChartOptionsMap.put("multiplePieOrderRow", new Boolean((AppUtils.getRequestNvlValue(request, "multiplePieOrder").length()>0?AppUtils.getRequestNvlValue(request, "multiplePieOrder").equals("row"):rr.isMultiplePieOrderByRow())) );
				additionalChartOptionsMap.put("multiplePieLabelDisplay", AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay").length()>0? AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay"):rr.getMultiplePieLabelDisplay());
				additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
			} else if (chartType.equals(AppConstants.GT_BAR_3D)) {
				additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
				additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
				additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
				additionalChartOptionsMap.put("lastSeriesALineChart", new Boolean(rr.isLastSeriesALineChart()));		
			} else if (chartType.equals(AppConstants.GT_LINE)) {
				additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
				//additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
				additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
				additionalChartOptionsMap.put("lastSeriesABarChart", new Boolean(rr.isLastSeriesABarChart()));
			} else if (chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) {
				additionalChartOptionsMap.put("intervalFromDate",AppUtils.getRequestNvlValue(request, "intervalFromDate").length()>0?AppUtils.getRequestNvlValue(request, "intervalFromDate"):rr.getIntervalFromdate());
				additionalChartOptionsMap.put("intervalToDate", AppUtils.getRequestNvlValue(request, "intervalToDate").length()>0? AppUtils.getRequestNvlValue(request, "intervalToDate"):rr.getIntervalTodate());
				additionalChartOptionsMap.put("intervalLabel", AppUtils.getRequestNvlValue(request, "intervalLabel").length()>0? AppUtils.getRequestNvlValue(request, "intervalLabel"):rr.getIntervalLabel());
			} else if (chartType.equals(AppConstants.GT_REGRESSION)) {
				additionalChartOptionsMap.put("regressionType",AppUtils.getRequestNvlValue(request, "regressionType").length()>0?AppUtils.getRequestNvlValue(request, "regressionType"):rr.getLinearRegression());
				additionalChartOptionsMap.put("linearRegressionColor",nvl(rr.getLinearRegressionColor()));
				additionalChartOptionsMap.put("expRegressionColor",nvl(rr.getExponentialRegressionColor()));
				additionalChartOptionsMap.put("maxRegression",nvl(rr.getCustomizedRegressionPoint()));
			} else if (chartType.equals(AppConstants.GT_STACK_BAR) ||chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES)
		           || chartType.equals(AppConstants.GT_STACKED_VERT_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES) 	
	    		) {
				additionalChartOptionsMap.put("overlayItemValue",new Boolean(nvl(rr.getOverlayItemValueOnStackBar()).equals("Y")));
			}
			additionalChartOptionsMap.put("legendPosition", nvl(rr.getLegendPosition()));
			additionalChartOptionsMap.put("hideToolTips", new Boolean(rr.hideChartToolTips()));
			additionalChartOptionsMap.put("hideLegend", new Boolean(AppUtils.getRequestNvlValue(request, "hideLegend").length()>0? AppUtils.getRequestNvlValue(request, "hideLegend").equals("Y"):rr.hideChartLegend()));
			additionalChartOptionsMap.put("labelAngle", nvl(rr.getLegendLabelAngle()));
			additionalChartOptionsMap.put("maxLabelsInDomainAxis", nvl(rr.getMaxLabelsInDomainAxis()));
			additionalChartOptionsMap.put("rangeAxisLowerLimit", nvl(rr.getRangeAxisLowerLimit()));
			additionalChartOptionsMap.put("rangeAxisUpperLimit", nvl(rr.getRangeAxisUpperLimit()));
			
		    
			boolean totalOnChart = false;
			totalOnChart = AppUtils.getRequestNvlValue(request, "totalOnChart").equals("Y");
			String filename  = null;
			ArrayList graphURL  = new ArrayList();
			ArrayList chartNames = new ArrayList();
			ArrayList fileNames = new ArrayList(); 
		    List l = rr.getAllColumns();
		    List lGroups = rr.getAllChartGroups();
		    HashMap mapYAxis = rr.getAllChartYAxis(rr.getReportParamValues());
		    String chartLeftAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartLeftAxisLabel()));
    		String chartRightAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartRightAxisLabel()));
		    int displayTotalOnChart = 0;
		    HashMap formValues = Globals.getRequestParamtersMap(request, false);

		    for (Iterator iterC = l.iterator(); iterC.hasNext();) {
				DataColumnType dc = (DataColumnType) iterC.next();
				if(nvl(dc.getColName()).equals(AppConstants.RI_CHART_TOTAL_COL)) {
					displayTotalOnChart = 1;
				}
			}
		    
		    String legendColumnName = (rr.getChartLegendColumn()!=null)?rr.getChartLegendColumn().getDisplayName():"Legend Column";
		    
		    
		    
			if(ds!=null)
			{
				   if(rr.hasSeriesColumn() && chartType.equals(AppConstants.GT_TIME_SERIES) && (lGroups==null || lGroups.size() <= 0)) { /** Check whether Report has only category  columns if so then all the columns will open in seperate chart - sundar**/
		                for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).size();i++) {
		                String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
		                chartTitle = rr.getFormFieldFilled(chartTitle);
						downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
						filename = null;/*(String) ChartGen.generateChart(  chartType,
													request.getSession(),
													ds,
													legendColumnName, 
													chartLeftAxisLabel,
													chartRightAxisLabel,
													rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1), 
													rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1), 
													rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1), 
													"",
													chartTitle,
													null,
													rr.getChartWidthAsInt(),
													rr.getChartHeightAsInt(),
								                    rr.getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i,i+1),
								                    rr.hasSeriesColumn(),
								                    //rr.isChartMultiSeries(),
								                    rr.isMultiSeries(),
								                    rr.getAllColumns(),
					                                downloadFileName,
					                                totalOnChart, 
					                                AppConstants.WEB_VERSION deviceType,
					                                additionalChartOptionsMap,
					                                true
					                );*/
					        	try {
				        			Image image = Image.getInstance(downloadFileName);
			                        images.add(image);
				        		} catch (MalformedURLException e) {
				    				e.printStackTrace();			
				    			} 
				    			catch (BadElementException e) {
				    				e.printStackTrace();

				    			} catch (FileNotFoundException e) {
				    				e.printStackTrace();
				    			} catch (IOException e) {
				    				e.printStackTrace();
				    		    }	
				}
					   
				   } else { /** first check the columns to be opened in new charts and loop around in ChartGen generate chart function  - sundar**/
	                    String tempChartGroupPrev = "";
				        String tempChartGroupCurrent = "";
		                for (int i=0; i<lGroups.size();i++) {
		                	String chartGroupOrg = (String) lGroups.get(i);
		                	String chartYAxis = (String) mapYAxis.get(chartGroupOrg);
		                	//System.out.println("chartGroupOrg " + chartGroupOrg);
		                	if(nvl(chartGroupOrg).length()>0)
		                		tempChartGroupCurrent = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|"));
		                	if(i>0) tempChartGroupPrev = ((String) lGroups.get(i-1)).substring(0,((String) lGroups.get(i-1)).lastIndexOf("|"));
		                	//System.out.println("TEMPCHARTGROUP " + tempChartGroupCurrent + " " + tempChartGroupPrev);
		                	if(tempChartGroupCurrent.equals(tempChartGroupPrev)) continue;
		                	//System.out.println("CHARTGROUPORG " + chartGroupOrg + " " + lGroups) ;
		                	//String chartGroup = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|"));
		                	String chartGroup = chartGroupOrg;
		                	
		                	//System.out.println("$$$$CHARTGROUP in JSP  " +chartGroup+ " "+ chartGroupOrg );
			  				   //System.out.println(" rr.getChartGroupDisplayNamesList(chartGroup) " + rr.getChartGroupDisplayNamesList(chartGroup));
			 				   //System.out.println(" rr.getChartGroupColumnColorsList(chartGroup) " + rr.getChartGroupColumnColorsList(chartGroup));
			 				   //System.out.println(" rr.getChartGroupColumnAxisList(chartGroup) " + rr.getChartGroupColumnAxisList(chartGroup));
			 				   //System.out.println(" rr.getChartGroupValueColumnAxisList(chartGroupOrg) " + rr.getChartGroupValueColumnAxisList(chartGroupOrg));
		                	
							downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
							String chartTitle = (Globals.getDisplayChartTitle()? (chartGroup!=null && chartGroup.indexOf("|") > 0 ?chartGroup.substring(0,chartGroup.lastIndexOf("|")):rr.getReportName()):"");
							chartTitle = rr.getFormFieldFilled(chartTitle);
							String leftAxisLabel = "";
							//if(!rr.isChartMultiSeries()) {
							  if(!rr.isMultiSeries()) {
								leftAxisLabel = ((chartYAxis!=null && chartYAxis.indexOf("|") > 0) ? chartYAxis.substring(0,chartYAxis.lastIndexOf("|")): chartLeftAxisLabel );
							} else {
								leftAxisLabel = chartLeftAxisLabel;
							}

				   	    	filename = null;/*(String) ChartGen.generateChart(  chartType,
																request.getSession(),
																ds,
																legendColumnName,  
																leftAxisLabel,
																chartRightAxisLabel,
																((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupDisplayNamesList(chartGroup, formValues)), 
																((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupColumnColorsList(chartGroup, formValues)), 
																((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupValueColumnAxisList(chartGroupOrg, formValues)), 
																"",
																chartTitle,
																null,
																rr.getChartWidthAsInt(),
																rr.getChartHeightAsInt(),
																((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues):rr.getChartGroupValueColumnAxisList(chartGroupOrg, formValues)),
											                    rr.hasSeriesColumn(),
											                    //rr.isChartMultiSeries(),
											                    rr.isMultiSeries(),
											                    rr.getAllColumns(),
								                                downloadFileName,
								                                totalOnChart, 
								                                AppConstants.WEB_VERSION deviceType, 
								                                additionalChartOptionsMap,
								                                true
								  );*/
					        	try {
				        			Image image = Image.getInstance(downloadFileName);
			                        images.add(image);
				        		} catch (MalformedURLException e) {
				    				e.printStackTrace();			
				    			} 
				    			catch (BadElementException e) {
				    				e.printStackTrace();

				    			} catch (FileNotFoundException e) {
				    				e.printStackTrace();
				    			} catch (IOException e) {
				    				e.printStackTrace();
				    		    }	
						}
					   
		            if(!chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {    
	                for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) { 
	  				   //System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1));
	 				   //System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1));
	 				   //System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1) " + rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1));

						downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
		                String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
		                chartTitle = rr.getFormFieldFilled(chartTitle);

	   	    	filename = null; /*(String) ChartGen.generateChart(  chartType,
													request.getSession(),
													ds,
													legendColumnName, 
													chartLeftAxisLabel,
													chartRightAxisLabel,
													(chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1), 
													(chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartColumnColorsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1), 
													(chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1), 
													"",
													chartTitle,
													null,
													rr.getChartWidthAsInt(),
													rr.getChartHeightAsInt(),
					                                rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i,i+1),
								                    rr.hasSeriesColumn(),
								                    //rr.isChartMultiSeries(),
								                    rr.isMultiSeries(),
								                    rr.getAllColumns(),
					                                downloadFileName,
					                                totalOnChart, 
					                                AppConstants.WEB_VERSION, 
					                                additionalChartOptionsMap,
					                                true
					  );*/
					        	try {
				        			Image image = Image.getInstance(downloadFileName);
			                        images.add(image);
				        		} catch (MalformedURLException e) {
				    				e.printStackTrace();			
				    			} 
				    			catch (BadElementException e) {
				    				e.printStackTrace();

				    			} catch (FileNotFoundException e) {
				    				e.printStackTrace();
				    			} catch (IOException e) {
				    				e.printStackTrace();
				    		    }	
						}
		            }
	                /** second rest of the columns are merged to one single chart  - sundar**/
	  				  // System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
	 				  // System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
	 				  // System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));

	 				  if((!(lGroups!=null && lGroups.size() > 0))) {
	 					  
	 				   if(/*chartType.equals(AppConstants.GT_TIME_SERIES) && */rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues)!=null && rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues).size()>0) {
	            	downloadFileName = AppUtils.getTempFolderPath()+"cr_"+  pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_All.png";
	                String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
	                chartTitle = rr.getFormFieldFilled(chartTitle);

			filename = null; /*(String) ChartGen.generateChart(  chartType,
													request.getSession(),
													ds,
													legendColumnName, 
													chartLeftAxisLabel,
													chartRightAxisLabel,
													rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), 
													rr.getChartColumnColorsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), 
													rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), 
													"",
													chartTitle,
													null,
													rr.getChartWidthAsInt(),
													rr.getChartHeightAsInt(),
					                                rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues),
								                    rr.hasSeriesColumn(),
								                  //rr.isChartMultiSeries(),
								                    rr.isMultiSeries(),
								                    rr.getAllColumns(),
					                                downloadFileName,
					                                totalOnChart, 
					                                AppConstants.WEB_VERSION, 
					                                additionalChartOptionsMap,
					                                true
					  );*/
					        	try {
				        			Image image = Image.getInstance(downloadFileName);
			                        images.add(image);
				        		} catch (MalformedURLException e) {
				    				e.printStackTrace();			
				    			} 
				    			catch (BadElementException e) {
				    				e.printStackTrace();

				    			} catch (FileNotFoundException e) {
				    				e.printStackTrace();
				    			} catch (IOException e) {
				    				e.printStackTrace();
				    		    }					  
	 			     }
	 				  } // Stacked Chart Check   
				   } // else no Series Column

			}// if(ds!=null)
			
		}catch (Exception e) {
				e.printStackTrace();
		}
//		System.out.println("Total Images " + images.size());
		return images.size()>0?images:null;
		
	}

/*
	private boolean isImageRotate(Document doc, Image image) {
		
		System.out.println("image size="+image.getWidthPercentage()+ " "+ image.scaledWidth()+ 
							" "+image.scaledHeight()+" "+image.getXYRatio());
		System.out.println("page size = "+ doc.getPageSize().width() + " " +doc.getPageSize().height() +" "+ 
				   doc.topMargin() + " " +doc.bottomMargin() + " " +   doc.leftMargin() + " " +
				   doc.rightMargin());
		System.out.println(image.scaledWidth()/image.scaledHeight());
		System.out.println((PageEvent.getPageWidth(doc)/PageEvent.getPageHeight(doc)));
//		System.out.println(doc.getPageSize().getRotation());
		
		float image_w = image.scaledWidth();
		float image_h = image.scaledHeight();
		float image_ratio = image_w/image_h;
		
		float page_w = PageEvent.getPageWidth(doc);
		float page_h = PageEvent.getPageHeight(doc);
		float page_ratio = page_w/page_h;
		
		return  (image_w > page_w && image_ratio > page_ratio) ||
				(image_h > page_h && image_ratio < page_ratio);

	}
	
*/
	private final int DEFAULT_PDF_DISPLAY_WIDTH = 10;
	private int paintPdfData(HttpServletRequest request, Document document, ReportData rd, ReportRuntime rr, String sql_whole) throws DocumentException, RaptorException, IOException  {
		
    	int mb = 1024*1024;
    	Runtime runtime = Runtime.getRuntime();
    	int returnValue = 0;
    	//sql_whole = rr.getWholeSQL();
        //if(rd.getDataRowCount() >= rr.getReportDataSize()) {
        	//sql_whole="";
        //}
    	float f[] = getRelativeWidths(rd, rr.getReportType().equals(AppConstants.RT_CROSSTAB));
		PdfPTable table = new PdfPTable(f);
		table.setWidthPercentage(100f);
		table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
		table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
		
		ReportDefinition rdef = (new ReportHandler()).loadReportDefinition(request, rr.getReportID());
		
		List allColumns = rdef.getAllColumns();
		
		float[] repotWidths = new float[rdef.getVisibleColumnCount()];
		int columnIdx = 0;
		float pdfDisplayWidth = 0;
		for(Iterator iter = allColumns.iterator(); iter.hasNext();){
			DataColumnType dct = (DataColumnType) iter.next();
			if(dct.isVisible()) {
			
			if(dct.getPdfDisplayWidthInPxls() == null || dct.getPdfDisplayWidthInPxls().equals("") || dct.getPdfDisplayWidthInPxls().startsWith("null"))
				pdfDisplayWidth = DEFAULT_PDF_DISPLAY_WIDTH;
			else
				pdfDisplayWidth = Float.parseFloat(dct.getPdfDisplayWidthInPxls());
			
			repotWidths [columnIdx++] = pdfDisplayWidth;
			}
		}		
		
		table.setWidths(repotWidths);
		
		//table.setH
		
		//TODO: check title and subtitle
		HttpSession session = request.getSession();
		String drilldown_index = (String) session.getAttribute("drilldown_index");
		int index = 0;
		try {
		 index = Integer.parseInt(drilldown_index);
		} catch (NumberFormatException ex) {
			index = 0;
		}		
		String titleRep = (String) session.getAttribute("TITLE_"+index);
		String subtitle = (String) session.getAttribute("SUBTITLE_"+index);
		
		if(nvl(titleRep).length()>0 && nvl(subtitle).length()>0)
			table.setHeaderRows(3);
		else if (nvl(titleRep).length()>0)
			table.setHeaderRows(2);
		else
			table.setHeaderRows(1);
		table = paintPdfReportHeader(request, document, table, rr, f);
		paintPdfTableHeader(document, rd, table);
		
		int idx = 0;
		int fragmentsize = 30; //for memory management
		
		ResultSet rs = null;
        Connection conn = null;
        Statement st = null;
        ResultSetMetaData rsmd = null;
        rd.reportDataRows.resetNext();
        DataRow dr = rd.reportDataRows.getNext();
			
 		//addRowHeader(table,dr,idx,rd);

 			//addRowColumns(table,dr,idx);
 	    	if(nvl(sql_whole).length() >0 && rr.getReportType().equals(AppConstants.RT_LINEAR)) {
 	           try {
 	   	        	conn = ConnectionUtils.getConnection(rr.getDbInfo());
 	   	        	st = conn.createStatement();
 	   	            logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************"));
 	   	            logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole));
 	   	            logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************"));
 	   	        	rs = st.executeQuery(sql_whole);
 	   	        	rsmd = rs.getMetaData();
 	   	            int numberOfColumns = rsmd.getColumnCount();
 	   	            HashMap colHash = new HashMap();
 	   	            dr = null;
 	   	            int j = 0;
 	   	            int rowCount = 0;
 	   	            String title = "";
 	   	       		while(rs.next()) {
 	   	       			
/* 		       			if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { 
 		       				returnValue = 1;
 		       				String cellValue = Globals.getUserDefinedMessageForMemoryLimitReached() + " "+ rowCount +" records out of " + rr.getReportDataSize() + " were downloaded to PDF.";
 		       				Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), 
 		       													Globals.getDataFontSize(),
 		       													Font.NORMAL, Color.BLACK);
 		       				PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
 		       				table.addCell(cell);
 		       				document.add(table);
 		       				return returnValue;
 		       			}
*/ 		       			rowCount++;
 		    			colHash = new HashMap();
 		    			for (int i = 1; i <= numberOfColumns; i++) {
 		    				colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i));
 		    			}
 		    			rd.reportDataRows.resetNext();
 		    			
 		    			dr = rd.reportDataRows.getNext();
 		    			
 		    			j = 0;
 		    			/*if(rd.reportTotalRowHeaderCols!=null) {
 		    			
	    					HtmlFormatter rfmt = dr.getRowFormatter();

	    					Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), 
	    														Globals.getDataFontSize(),
	    														Font.NORMAL, Color.BLACK);
	    					if(rfmt != null) {
	    						cellFormatterFont(rfmt,cellFont);
	    					}
	    					
	    					String cellValue = new Integer(rowCount).toString();
	    					PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
	    					
	    					//row background color can be overwritten by cell background color
	    					cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
	    					
    						cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
	    					
    						if(rfmt != null) {
	    						formatterCell(rfmt,cell);
	    					}
	    					table.addCell(cell);
 		    			}*/
 		    			
 		    			for (dr.resetNext(); dr.hasNext();j++) {
			    				DataValue dv = dr.getNext();
		    					/*if(j == 0) {
 			    					HtmlFormatter cfmt = dv.getCellFormatter();
 			    					HtmlFormatter rfmt = dv.getRowFormatter();

 			    					Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), 
 			    														Globals.getDataFontSize(),
 			    														Font.NORMAL, Color.BLACK);
 			    					if(cfmt!= null) {
 			    						cellFormatterFont(cfmt,cellFont);
 			    					}
 			    					else if(rfmt != null) {
 			    						cellFormatterFont(rfmt,cellFont);
 			    					}
 			    					else {
 			    						if(dv.isBold()) {
 			    							cellFont.setStyle(Font.BOLD);
 			    						}
 			    					}
 			    					
 			    					//String cellValue = strip.stripHtml(value.trim());
 			    					PdfPCell cell = new PdfPCell(new Paragraph(rowCount+"",cellFont));
 			    					
 			    					//row background color can be overwritten by cell background color
 			    					cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
 			    					
 			    					if(nvl(dv.getAlignment()).trim().length()>0)
 			    						cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
 			    					else
 			    						cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
 			    					
 			    					if(cfmt!= null) {
 			    						formatterCell(cfmt,cell);
 			    					}
 			    					else if(rfmt != null) {
 			    						formatterCell(rfmt,cell);
 			    					}
 			    					table.addCell(cell);
			    				}*/
 		    				
 			    			//for (chr.resetNext(); chr.hasNext();) {
 			    				//ColumnHeader ch = chr.getNext();
 			    				String value = nvl((String)colHash.get(dv.getColId().toUpperCase()));
 			    				if(dv.isVisible()) {
 			    					
 			    					HtmlFormatter cfmt = dv.getCellFormatter();
 			    					HtmlFormatter rfmt = dv.getRowFormatter();

 			    					Font cellFont = FontFactory.getFont(FONT_FAMILY, 
 			    														FONT_SIZE,
 			    														Font.NORMAL, Color.BLACK);
 			    					if(cfmt!= null) {
 			    						cellFormatterFont(cfmt,cellFont);
 			    					}
 			    					else if(rfmt != null) {
 			    						cellFormatterFont(rfmt,cellFont);
 			    					}
 			    					else {
 			    						if(dv.isBold()) {
 			    							cellFont.setStyle(Font.BOLD);
 			    						}
 			    					}
 			    					
 			    					String cellValue = strip.stripHtml(value.trim());
 			    					PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
 			    					
 			    					//row background color can be overwritten by cell background color
 			    					cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
 			    					
 			    					if(nvl(dv.getAlignment()).trim().length()>0)
 			    						cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
 			    					else
 			    						cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
 			    					
 			    					if(cfmt!= null) {
 			    						formatterCell(cfmt,cell);
 			    					}
 			    					else if(rfmt != null) {
 			    						formatterCell(rfmt,cell);
 			    					}
 			    					
 			    					
 			    					
 			    					table.addCell(cell);
 			    				
 			    				}//if isVisible()
 			    				
 			    				
 		    			}
 		    			
 	   	       		}
 		       		if(rd.reportDataTotalRow!=null) {
 						for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();idx++) {
 							dr = rd.reportDataTotalRow.getNext();
 							table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
 							Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY, 
 									FONT_SIZE,
 									Font.NORMAL, Color.BLACK);
 							rowHeaderFont.setStyle(Font.BOLD);
 							rowHeaderFont.setSize(FONT_SIZE+1f);
 							table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
 								table.addCell(new Paragraph("Total",rowHeaderFont));
 						

 			 	 			addTotalRowColumns(table,dr,idx);
 			 				if (idx % fragmentsize == fragmentsize - 1) {
 			 					document.add(table);
 			 					table.deleteBodyRows();
 			 					table.setSkipFirstHeader(true);
 			 				}
 			
 						}
 		    		} 	   	       		
 			    } catch (SQLException ex) { 
 			    	throw new RaptorException(ex);
 			    } catch (ReportSQLException ex) { 
 			    	throw new RaptorException(ex);
 			    } catch (Exception ex) {
 			    	if(!(ex.getCause() instanceof java.net.SocketException) )
 			    		throw new RaptorException (ex);
 			    } finally {
 		        	try {
 		        		if(conn!=null)
 		        			conn.close();
 		        		if(st!=null)
 		        			st.close();
 		        		if(rs!=null)
 		        			rs.close();
 		        	} catch (SQLException ex) {
 		        		throw new RaptorException(ex);
 		        	}
 		        }
 			
 			
//			if (idx % fragmentsize == fragmentsize - 1) {
//				document.add(table);
//				table.deleteBodyRows();
//				table.setSkipFirstHeader(true);
//			}
 
        //document.add(table);
 	    } else {
 	    	 if(rr.getReportType().equals(AppConstants.RT_LINEAR)) {
 	    	int rowCount = 0;
 			for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();idx++)
 			{	
	       		rowCount++;
	       		
	       		/*if(rd.reportTotalRowHeaderCols!=null) { 
					HtmlFormatter rfmt = dr.getRowFormatter();
	
					Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), 
														Globals.getDataFontSize(),
														Font.NORMAL, Color.BLACK);
					if(rfmt != null) {
						cellFormatterFont(rfmt,cellFont);
					}
					
					//String cellValue = new Integer(rowCount).toString();
					//PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
					
					//row background color can be overwritten by cell background color
					//cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
					
					//cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
					
					//if(rfmt != null) {
						//formatterCell(rfmt,cell);
					//}
					//table.addCell(cell);
	       		}*/
	       		
	       		
	       		
 				if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { 
		       				returnValue = 1;
		       			}
 				
 	 			dr = rd.reportDataRows.getNext();
 				
 	 			addRowHeader(table,dr,idx,rd);

 	 			addRowColumns(table,dr,idx);
 	 			
 				if (idx % fragmentsize == fragmentsize - 1) {
 					document.add(table);
 					table.deleteBodyRows();
 					table.setSkipFirstHeader(true);
 				}
 			}
 			
	       		if(rd.reportDataTotalRow!=null) {
					for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();idx++) {
						dr = rd.reportDataTotalRow.getNext();
						table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
						Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY, 
								FONT_SIZE,
								Font.NORMAL, Color.BLACK);
						rowHeaderFont.setStyle(Font.BOLD);
						rowHeaderFont.setSize(FONT_SIZE+1f);
						table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
							table.addCell(new Paragraph("Total",rowHeaderFont));
					

		 	 			addTotalRowColumns(table,dr,idx);
		 				if (idx % fragmentsize == fragmentsize - 1) {
		 					document.add(table);
		 					table.deleteBodyRows();
		 					table.setSkipFirstHeader(true);
		 				}
		
					}
	    		} 	   	       		

 	    	 } else if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) {
       		    int rowCount = 0;
     		    List l = rd.getReportDataList();
     		    boolean first = true;
       			for (int dataRow = 0; dataRow < l.size(); dataRow++) {
       				first = true;
       		       		rowCount++;
       		       		dr = (DataRow) l.get(dataRow);
          				Vector<DataValue> rowNames = dr.getRowValues();
          				for(dr.resetNext(); dr.hasNext(); ) {
          					
          				if(first) {
       						HtmlFormatter rfmt = dr.getRowFormatter();
       			       		
       						Font cellFont = FontFactory.getFont(FONT_FAMILY, 
       															FONT_SIZE,
       															Font.NORMAL, Color.BLACK);
       						if(rfmt != null) {
       							cellFormatterFont(rfmt,cellFont);
       						}
       						String cellValue = "";
       						PdfPCell cell = null;
       						//String cellValue = new Integer(rowCount).toString();
       						//PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
       					//row background color can be overwritten by cell background color
       						//cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
       						
       						//cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
       						
       						//if(rfmt != null) {
       							//formatterCell(rfmt,cell);
       					//	}
       						//table.addCell(cell);
    	                    if(rowNames!=null) {
    	                        for(int i=0; i<rowNames.size(); i++) {
    	                        	DataValue dv = rowNames.get(i);
    	       						rfmt = dr.getRowFormatter();
    	       			       		
    	       						cellFont = FontFactory.getFont(FONT_FAMILY, 
    	       															FONT_SIZE,
    	       															Font.NORMAL, Color.BLACK);
    	       						if(rfmt != null) {
    	       							cellFormatterFont(rfmt,cellFont);
    	       						}
    	       						cellValue = dv.getDisplayValue();
    	    	    				if(cellValue.indexOf("|#")!=-1)
    	    	    					cellValue = cellValue.substring(0,cellValue.indexOf("|"));
    	    	    				
    	       						cell = new PdfPCell(new Paragraph(cellValue,cellFont));
    	       					//row background color can be overwritten by cell background color
    	       						cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
    	       						
    	       						cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
    	       						
    	       						if(rfmt != null) {
    	       							formatterCell(rfmt,cell);
    	       						}
    	       						table.addCell(cell);
    	                        }
    	                        }
    	                   }
    					first = false;
       		       		
       	 				if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { 
       			       				returnValue = 1;
       			       			}
       	 				
       	 	 			//addRowHeader(table,dr,idx,rd);

       	 	 			addRowColumns(table,dr,idx);
       	 	 			
       	 				if (idx % fragmentsize == fragmentsize - 1) {
       	 					document.add(table);
       	 					table.deleteBodyRows();
       	 					table.setSkipFirstHeader(true);
       	 				}
       	 			}

       			}
 	    	 }
 	    
				//document.add(table);

 	    }
 	    	
 	    document.add(table);
 	    paintPdfReportFooter(request, document, rr, f);
 	    
 	    return returnValue;	
	}
	
	private void addRowHeader(PdfPTable table, DataRow dr, int idx, ReportData rd) {
		
		table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);	

		for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
			RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
			if(idx==0) 
				rhc.resetNext();
			RowHeader rh = rhc.getNext();
			//System.out.println(" =============== RowHeader\n "+rh);
			
			Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY, 
													FONT_SIZE,
													Font.NORMAL, Color.BLACK);
			if(rh.isBold()) {
				rowHeaderFont.setStyle(Font.BOLD);
				rowHeaderFont.setSize(FONT_SIZE+1f);
			}
			
			if(rh.getColSpan()>0) {
				table.getDefaultCell().setColspan(rh.getColSpan());
				table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
				table.addCell(new Paragraph(strip.stripHtml(rh.getRowTitle()),rowHeaderFont));
			}
		}		
	}

	private void addRowColumns(PdfPTable table, DataRow dr, int idx) {
			
		table.getDefaultCell().setColspan(1);
			
		for(dr.resetNext();dr.hasNext();)
		{
			DataValue dv = dr.getNext();
			//System.out.println(columnCount +" --> "+dv);
			if(dv.isVisible()) {
				HtmlFormatter cfmt = dv.getCellFormatter();
				HtmlFormatter rfmt = dv.getRowFormatter();

				Font cellFont = FontFactory.getFont(FONT_FAMILY, 
													FONT_SIZE,
													Font.NORMAL, Color.BLACK);
				if(cfmt!= null) {
					cellFormatterFont(cfmt,cellFont);
				}
				else if(rfmt != null) {
					cellFormatterFont(rfmt,cellFont);
				}
				else {
					if(dv.isBold()) {
						cellFont.setStyle(Font.BOLD);
					}
				}
				
				String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
				PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
				
				//row background color can be overwritten by cell background color
				cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
				
				if(nvl(dv.getAlignment()).trim().length()>0)
					cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
				else
					cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
				
				if(cfmt!= null) {
					formatterCell(cfmt,cell);
				}
				else if(rfmt != null) {
					formatterCell(rfmt,cell);
				}
				
				table.addCell(cell);
			
			}//if isVisible()
		}					
	}


	private void addTotalRowColumns(PdfPTable table, DataRow dr, int idx) {
		
		table.getDefaultCell().setColspan(1);
		dr.resetNext();
		dr.getNext();
		for(;dr.hasNext();)
		{
			DataValue dv = dr.getNext();
			//System.out.println(columnCount +" --> "+dv);
			if(dv.isVisible()) {
				HtmlFormatter cfmt = dv.getCellFormatter();
				HtmlFormatter rfmt = dv.getRowFormatter();

				Font cellFont = FontFactory.getFont(FONT_FAMILY, 
													FONT_SIZE,
													Font.NORMAL, Color.BLACK);
				if(cfmt!= null) {
					cellFormatterFont(cfmt,cellFont);
				}
				else if(rfmt != null) {
					cellFormatterFont(rfmt,cellFont);
				}
				else {
					if(dv.isBold()) {
						cellFont.setStyle(Font.BOLD);
					}
				}
				
				String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
				PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
				
				//row background color can be overwritten by cell background color
				cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
				
				if(nvl(dv.getAlignment()).trim().length()>0)
					cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
				else
					cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
				
				if(cfmt!= null) {
					formatterCell(cfmt,cell);
				}
				else if(rfmt != null) {
					formatterCell(rfmt,cell);
				}
				
				table.addCell(cell);
			
			}//if isVisible()
		}					
	}
	
	
	private void formatterCell(HtmlFormatter fmt, PdfPCell cell) {
		
		if(nvl(fmt.getBgColor()).trim().length()>0)
			cell.setBackgroundColor(Color.decode(fmt.getBgColor()));
		if(nvl(fmt.getAlignment()).trim().length()>0)
			cell.setHorizontalAlignment(ElementTags.alignmentValue(fmt.getAlignment()));
	}

	private void cellFormatterFont(HtmlFormatter fmt, Font font) {
		
		if(fmt.isBold()) 
			font.setStyle(Font.BOLD);
		if(fmt.isItalic()) 
			font.setStyle(Font.ITALIC);
		if(fmt.isUnderline()) 
			font.setStyle(Font.UNDERLINE);
		if(fmt.getFontColor().trim().length()>0)
			font.setColor(Color.decode(fmt.getFontColor()));
		if(fmt.getFontSize().trim().length()>0)
			font.setSize(Float.parseFloat(fmt.getFontSize())-Globals.getDataFontSizeOffset());
//		if(fmt.getFontFace().trim().length()>0)
//			cellFont.setFamily()
		
	}

	private Color getRowBackgroundColor(DataRow dr, int idx) {
		
		Color color =  Color.decode(Globals.getDataDefaultBackgroundHexCode());
		
		HtmlFormatter rhf = dr.getRowFormatter();
		if(rhf!=null && nvl(rhf.getBgColor()).trim().length()>0)
			
			color = Color.decode(rhf.getBgColor());
		
		else if(pb.isAlternateColor() && idx%2==0)
			
			color = Color.decode(Globals.getDataBackgroundAlternateHexCode());
		
		return color;		

	}

	private int getTotalVisbleColumns(ReportData rd) {
		
		int totalVisbleColumn = rd.getTotalColumnCount();
		for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();)
		{	
 			DataRow dr = rd.reportDataRows.getNext();
			for(dr.resetNext();dr.hasNext();) {
				DataValue dv = dr.getNext();
				if(!dv.isVisible()) totalVisbleColumn--;
			}
			
			break;
		}
		
		return totalVisbleColumn;
	}

	/*
	private int getFirstRowIndex(ReportRuntime rr) {
		return (pb.getCurrentPage()>0)?pb.getCurrentPage()*rr.getPageSize()+1 : 1;
	}
  	*/
	private float[] getRelativeWidths(ReportData rd, boolean crosstab){
		
		int totalColumns = getTotalVisbleColumns(rd);
		/*if(rd.reportTotalRowHeaderCols!=null) {
			totalColumns += 1;
		}*/
		if(crosstab) {
			totalColumns += 1;
		}

		if(totalColumns == 0 )
			totalColumns=1;
		
		float[] relativeWidths = new float[totalColumns];
		//initial widths are even
		for(int i=0; i<relativeWidths.length; i++)
			relativeWidths[i] = 10f;
		
		int index=0;
		boolean firstPass = true;
		
		for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) 
		{
			if(firstPass) {
				/*if(rd.reportTotalRowHeaderCols!=null) { 
					String columnWidth = "5";
					
					if(columnWidth != null && columnWidth.trim().endsWith("%"))
						relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
					
					index++;
				}*/
				
				for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
					String columnWidth = rd.reportRowHeaderCols.getNext().getColumnWidth();
					
					if(columnWidth != null && columnWidth.trim().endsWith("%"))
						relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
					
					index++;
				}
				firstPass = false;
			}
		
			ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
			for (chr.resetNext(); chr.hasNext();) {
				
				ColumnHeader ch = chr.getNext();

				if(ch.isVisible()) {
					
					String columnWidth = ch.getColumnWidth();
					
					if(ch.getColSpan() <= 1){
						if(columnWidth != null && columnWidth.trim().endsWith("%")) 
							relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
					} 
					else {
						for(int i=0; i<ch.getColSpan(); i++) {
							index += i;
							if(columnWidth != null && columnWidth.trim().endsWith("%"))
								relativeWidths[index] = 
									(Float.parseFloat(removeLastCharacter(columnWidth)))/ch.getColSpan();							
						}
					}
					
					index++;
				}
			}
		}
		
		return relativeWidths;
	}
	
	public static String removeLastCharacter(String str) {
		return str.substring(0, str.length()-1);
	}
	
	private PdfPTable paintPdfReportHeader(HttpServletRequest request, Document document, PdfPTable table, ReportRuntime rr, float[] f) 
			throws DocumentException, IOException {
		
		HttpSession session = request.getSession();
		String drilldown_index = (String) session.getAttribute("drilldown_index");
		int index = 0;
		try {
		 index = Integer.parseInt(drilldown_index);
		} catch (NumberFormatException ex) {
			index = 0;
		}
		String title = (String) session.getAttribute("TITLE_"+index);
		String subtitle = (String) session.getAttribute("SUBTITLE_"+index);
		if(nvl(title).length()>0) {
			//PdfPTable table = new PdfPTable(1);
			table.setWidthPercentage(100f);
			table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
			table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
	        
	
			Font font = FontFactory.getFont(FONT_FAMILY, 
					FONT_SIZE-2f,
					Font.BOLD, 
					Color.BLACK);
		
			//addEmptyRows(table,1);
			table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
			//table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
		    title = Utils.replaceInString(title, "<BR/>", " ");
		    title = Utils.replaceInString(title, "<br/>", " ");
		    title = Utils.replaceInString(title, "<br>", " ");
			title  = strip.stripHtml(nvl(title).trim());
			//subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
			//subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
			//subtitle = Utils.replaceInString(subtitle, "<br>", " ");
			//subtitle  = strip.stripHtml(nvl(subtitle).trim());
			StyleSheet styles = new StyleSheet();
			
			HTMLWorker htmlWorker = new HTMLWorker(document); 
			ArrayList cc = new ArrayList(); 
			cc = htmlWorker.parseToList(new StringReader(subtitle), styles); 
			                     	
			Phrase p1 = new Phrase(); 
			for (int i = 0; i < cc.size(); i++){ 
				Element elem = (Element)cc.get(i); 
				ArrayList al  = elem.getChunks();
				for (int j = 0; j < al.size(); j++) {
					Chunk chunk = (Chunk) al.get(j);
					chunk.font().setSize(6.0f);
				}
				p1.add(elem); 
			} 
			//cell = new PdfPCell(p1);
	    	StyleSheet style = new StyleSheet();
	    	style.loadTagStyle("font", "font-size", "3");
	    	style.loadTagStyle("font", "size", "3");
            styles.loadStyle("pdfFont1", "size", "11px");                                 
            styles.loadStyle("pdfFont1", "font-size", "11px"); 
        	/*ArrayList p = HTMLWorker.parseToList(new StringReader(nvl(title)), style);
        	for (int k = 0; k < p.size(); ++k){
        		document.add((com.lowagie.text.Element)p.get(k));
       	 	}*/
            //p1.font().setSize(3.0f);
			PdfPCell titleCell = new PdfPCell(new Phrase(title, font));
			titleCell.setColspan(rr.getVisibleColumnCount());
			PdfPCell subtitleCell = new PdfPCell(p1);
			subtitleCell.setColspan(rr.getVisibleColumnCount());
			titleCell.setHorizontalAlignment(1);
			subtitleCell.setHorizontalAlignment(1);
			table.addCell(titleCell);
			table.addCell(subtitleCell);
			//document.add(table);
		}
		return table;
	}


	private void paintPdfReportFooter(HttpServletRequest request, Document document, ReportRuntime rr, float[] f) 
			throws DocumentException, IOException {
		
		HttpSession session = request.getSession();
		String drilldown_index = (String) session.getAttribute("drilldown_index");
		int index = 0;
		try {
		 index = Integer.parseInt(drilldown_index);
		} catch (NumberFormatException ex) {
			index = 0;
		}

		String title = (String) session.getAttribute("FOOTER_"+index);
		if(nvl(title).length()>0) {
			PdfPTable table = new PdfPTable(1);
			table.setWidthPercentage(100f);
			table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
			table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
	        
			Font font = FontFactory.getFont(FONT_FAMILY, 
					FONT_SIZE-3f,
					Font.BOLD, 
					Color.BLACK);
		
			
			//addEmptyRows(table,1);
			table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
			//table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
		    /*title = Utils.replaceInString(title, "<BR/>", " ");
		    title = Utils.replaceInString(title, "<br/>", " ");
		    title = Utils.replaceInString(title, "<br>", " ");
			title  = strip.stripHtml(nvl(title).trim());*/
	    	StyleSheet style = new StyleSheet();
	    	
			HTMLWorker htmlWorker = new HTMLWorker(document); 
			ArrayList cc = new ArrayList(); 
			cc = htmlWorker.parseToList(new StringReader(title), style); 
			                     	
			Phrase p1 = new Phrase(); 
			for (int i = 0; i < cc.size(); i++){ 
				Element elem = (Element)cc.get(i); 
				ArrayList al  = elem.getChunks();
				for (int j = 0; j < al.size(); j++) {
					Chunk chunk = (Chunk) al.get(j);
					chunk.font().setSize(6.0f);
				}
				p1.add(elem); 
			} 
	    	
/*			
			HTMLWorker.parseToList(new StringReader(nvl(title)), style);*/
			PdfPCell titleCell = new PdfPCell(p1);
			titleCell.setHorizontalAlignment(Element.ALIGN_LEFT);
			table.addCell(titleCell);
			//table.
			document.add(table);
		}
		//return table;
	}
	
	
	private void paintPdfTableHeader(Document document, ReportData rd, PdfPTable table) 
																throws DocumentException {
			
		Font font = FontFactory.getFont(FONT_FAMILY, 
										FONT_SIZE+1f,
										Font.BOLD, 
										Color.decode(Globals.getDataTableHeaderFontColor()));
		//table.setHeaderRows(1);
		table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
		table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
		String title = "";
		
		boolean firstPass = true;
		
		/*if(rd.reportTotalRowHeaderCols!=null) {
			if(firstPass) {
				table.addCell(new Paragraph("No.", font));
				firstPass = false;
			}
		}*/		
		for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) 
		{
			if(firstPass) {
				for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
					/*if(firstPass) {
						table.addCell(new Paragraph("No.", font));
						firstPass = false;
					} else {*/
						RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
						title = rhc.getColumnTitle();
	    				title = Utils.replaceInString(title,"_nl_", " \n");
						table.addCell(new Paragraph(title,font));
					//}
				}
			}
			
			ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
			for (chr.resetNext(); chr.hasNext();) {
				ColumnHeader ch = chr.getNext();
				//System.out.println(ch);
				if(ch.isVisible()) {
					title = ch.getColumnTitle();
    				title = Utils.replaceInString(title,"_nl_", " \n");
					table.addCell(new Paragraph(title,font));
				}
			}
		}
	}
	
	public static String currentTime(String pattern) {
		try {
	        SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
	        Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
	        SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
	        return dtimestamp.format(sysdate)+" "+Globals.getTimeZone();
	        //paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
        } catch(Exception ex) {}	 
		
		SimpleDateFormat s = new SimpleDateFormat(pattern);
		s.setTimeZone(TimeZone.getTimeZone(Globals.getTimeZone()));
		//System.out.println("^^^^^^^^^^^^^^^^^^^^ " + Calendar.getInstance().getTime());
		//System.out.println("^^^^^^^^^^^^^^^^^^^^ " + s.format(Calendar.getInstance().getTime()));
		return s.format(Calendar.getInstance().getTime());
	}

	private PdfBean preparePdfBean(HttpServletRequest request,ReportRuntime rr) {
		PdfBean pb = new PdfBean();

		pb.setUserId(AppUtils.getUserID(request));

		pb.setWhereToShowPageNumber(Globals.getPageNumberPosition());
		pb.setAlternateColor(Globals.isDataAlternateColor());
		pb.setTimestampPattern(Globals.getDatePattern());

		int temp = -1;
		try {
			temp = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE));
		} catch (NumberFormatException e) {}		
		pb.setCurrentPage(temp);
	
		//pb.setPortrait( trueORfalse(request.getParameter("isPortrait"),true));
		pb.setPortrait(trueORfalse(rr.getPDFOrientation() == "portait"?"true":"false", true));
		//pb.setCoverPageIncluded( trueORfalse(request.getParameter("isCoverPageIncluded"), true));
		//if(Globals.isCoverPageNeeded()) {
			pb.setCoverPageIncluded(Globals.isCoverPageNeeded()?rr.isPDFCoverPage():false);
		//}
		pb.setTitle(nvl(request.getParameter("title")));
		pb.setPagesize(nvls(request.getParameter("pagesize"),"LETTER"));
		
		pb.setLogo1Url(rr.getPDFLogo1());
		pb.setLogo2Url(rr.getPDFLogo2());
		pb.setLogo1Size(rr.getPDFLogo1Size());
		pb.setLogo2Size(rr.getPDFLogo2Size());
		pb.setFullWebContextPath(request.getSession().getServletContext().getRealPath(File.separator));
		

		pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart());
			
		String id = nvl(request.getParameter("pdfAttachmentKey")).trim();
		String log_id = nvl(request.getParameter("log_id")).trim();
		if(id.length()>0 && log_id.length()>0)
			pb.setAttachmentOfEmail(true);
		
		return pb;
	}
	
	private boolean trueORfalse(String str) {
		return (str != null) && (str.equalsIgnoreCase("true"));
	}
	
	private boolean trueORfalse(String str,boolean b_default) {
		return str==null ? b_default : (str.equalsIgnoreCase("true"));
	}
	
   
}