Esempio n. 1
0
        public static ActionResult PDF(
            int companyId,
            bool externa,
            string from,
            bool interna,
            bool provider,
            bool status0,
            bool status1,
            bool status2,
            bool status3,
            bool status4,
            bool status5,
            string to,
            string filterText,
            string listOrder)
        {
            var source = "AuditoryExportList";
            var res    = ActionResult.NoAction;
            var user   = HttpContext.Current.Session["User"] as ApplicationUser;

            Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
            var    company = new Company(companyId);
            string path    = HttpContext.Current.Request.PhysicalApplicationPath;

            if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
            {
                path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
            }

            var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

            string fileName = string.Format(
                CultureInfo.InvariantCulture,
                @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
                Dictionary["Item_Auditories"],
                formatedDescription,
                DateTime.Now);


            var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
            var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                                   new FileStream(
                                                                       string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                       FileMode.Create));

            writer.PageEvent = new TwoColumnHeaderFooter
            {
                CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
                IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
                Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
                CreatedBy   = user.UserName,
                CompanyId   = company.Id,
                CompanyName = company.Name,
                Title       = Dictionary["Item_Auditories"].ToUpperInvariant()
            };

            pdfDoc.Open();

            var titleTable = new iTSpdf.PdfPTable(1);

            titleTable.SetWidths(new float[] { 50f });
            titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
            {
                HorizontalAlignment = iTS.Element.ALIGN_CENTER,
                Border = iTS.Rectangle.NO_BORDER
            });

            //------ CRITERIA
            var criteriatable = new iTSpdf.PdfPTable(4)
            {
                WidthPercentage = 100
            };

            criteriatable.SetWidths(new float[] { 10f, 50f, 10f, 80f });

            #region texts

            string criteriaProccess = Dictionary["Common_All_Male_Plural"];

            string periode = string.Empty;
            if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
            {
                periode = Dictionary["Item_Incident_List_Filter_From"] + " " + from;
            }
            else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
            {
                periode = Dictionary["Item_Incident_List_Filter_To"] + " " + to;
            }
            else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
            {
                periode = from + " - " + to;
            }
            else
            {
                periode = Dictionary["Common_All_Male"];
            }

            string typetext  = string.Empty;
            bool   firtsType = false;
            if (interna)
            {
                typetext += Dictionary["Item_Adutory_Type_Label_0"];
                firtsType = false;
            }
            if (externa)
            {
                typetext += firtsType ? string.Empty : ", ";
                typetext += Dictionary["Item_Adutory_Type_Label_1"];
                firtsType = false;
            }
            if (provider)
            {
                typetext += firtsType ? string.Empty : ", ";
                typetext += Dictionary["Item_Adutory_Type_Label_2"];
            }
            if (firtsType)
            {
                typetext = Dictionary["Common_All_Female_Plural"];
            }

            string statustext  = string.Empty;
            bool   firstStatus = false;
            if (status0)
            {
                statustext += Dictionary["Item_Adutory_Status_Label_0"];
                firstStatus = false;
            }
            if (status1)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_1"];
                firstStatus = false;
            }
            if (status2)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_2"];
                firstStatus = false;
            }
            if (status3)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_3"];
                firstStatus = false;
            }
            if (status4)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_4"];
                firstStatus = false;
            }
            if (status5)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_5"];
            }
            if (firstStatus)
            {
                statustext = Dictionary["Common_All_Male_Plural"];
            }


            #endregion

            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Common_Period"]));
            criteriatable.AddCell(ToolsPdf.CriteriaCellData(periode));
            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Item_Auditory_Filter_Type"]));
            criteriatable.AddCell(ToolsPdf.CriteriaCellData(typetext));
            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Item_Auditory_Filter_Status"]));
            criteriatable.AddCell(ToolsPdf.CriteriaCellData(statustext));
            if (!string.IsNullOrEmpty(filterText))
            {
                criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Common_PDF_Filter_Contains"]));
                criteriatable.AddCell(ToolsPdf.CriteriaCellData(filterText));
            }
            else
            {
                criteriatable.AddCell(ToolsPdf.CriteriaCellData(string.Empty));
                criteriatable.AddCell(ToolsPdf.CriteriaCellData(string.Empty));
            }

            pdfDoc.Add(criteriatable);
            //---------------------------

            var tableWidths = new float[] { 40f, 10f, 10f, 10f, 10f, 10f };
            var table       = new iTSpdf.PdfPTable(tableWidths.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 1,
                SpacingBefore       = 20f,
                SpacingAfter        = 30f
            };

            table.SetWidths(tableWidths);

            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Name"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_Filter_Type"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Status"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Planned"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Closed"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Ammount"]));

            int cont = 0;
            var data = new List <Auditory>();
            using (var cmd = new SqlCommand("Auditory_Filter"))
            {
                using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString))
                {
                    cmd.Connection  = cnn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(DataParameter.Input("@CompanyId", companyId));
                    cmd.Parameters.Add(DataParameter.Input("@From", from));
                    cmd.Parameters.Add(DataParameter.Input("@To", to));
                    cmd.Parameters.Add(DataParameter.Input("@TypeInterna", interna));
                    cmd.Parameters.Add(DataParameter.Input("@TypeExterna", externa));
                    cmd.Parameters.Add(DataParameter.Input("@TypeProveedor", provider));
                    cmd.Parameters.Add(DataParameter.Input("@Status0", status0));
                    cmd.Parameters.Add(DataParameter.Input("@Status1", status1));
                    cmd.Parameters.Add(DataParameter.Input("@Status2", status2));
                    cmd.Parameters.Add(DataParameter.Input("@Status3", status3));
                    cmd.Parameters.Add(DataParameter.Input("@Status4", status4));
                    cmd.Parameters.Add(DataParameter.Input("@Status5", status5));
                    try
                    {
                        cmd.Connection.Open();
                        using (var rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                var newAuditory = new Auditory
                                {
                                    Id          = rdr.GetInt64(ColumnsAuditoryFilter.Id),
                                    Description = rdr.GetString(ColumnsAuditoryFilter.Nombre),
                                    Amount      = rdr.GetDecimal(ColumnsAuditoryFilter.Amount),
                                    Status      = rdr.GetInt32(ColumnsAuditoryFilter.Status),
                                    Type        = rdr.GetInt32(ColumnsAuditoryFilter.Type)
                                };

                                if (!rdr.IsDBNull(ColumnsAuditoryFilter.PlannedOn))
                                {
                                    newAuditory.PlannedOn = rdr.GetDateTime(ColumnsAuditoryFilter.PlannedOn);
                                }

                                if (!rdr.IsDBNull(ColumnsAuditoryFilter.ValidatedOn))
                                {
                                    newAuditory.ValidatedOn = rdr.GetDateTime(ColumnsAuditoryFilter.ValidatedOn);
                                }

                                data.Add(newAuditory);
                            }
                        }
                    }
                    catch (SqlException ex)
                    {
                        ExceptionManager.Trace(ex, source);
                    }
                    catch (FormatException ex)
                    {
                        ExceptionManager.Trace(ex, source);
                    }
                    catch (NullReferenceException ex)
                    {
                        ExceptionManager.Trace(ex, source);
                    }
                    finally
                    {
                        if (cmd.Connection.State != ConnectionState.Closed)
                        {
                            cmd.Connection.Close();
                        }
                    }
                }
            }

            switch (listOrder.ToUpperInvariant())
            {
            default:
            case "TH1|ASC":
                data = data.OrderBy(d => d.Status).ToList();
                break;

            case "TH1|DESC":
                data = data.OrderByDescending(d => d.Status).ToList();
                break;

            case "TH2|ASC":
                data = data.OrderBy(d => d.Description).ToList();
                break;

            case "TH2|DESC":
                data = data.OrderByDescending(d => d.Description).ToList();
                break;

            case "TH3|ASC":
                data = data.OrderBy(d => d.PlannedOn).ToList();
                break;

            case "TH3|DESC":
                data = data.OrderByDescending(d => d.PlannedOn).ToList();
                break;

            case "TH4|ASC":
                data = data.OrderBy(d => d.ValidatedOn).ToList();
                break;

            case "TH4|DESC":
                data = data.OrderByDescending(d => d.ValidatedOn).ToList();
                break;

            case "TH5|ASC":
                data = data.OrderBy(d => d.Amount).ToList();
                break;

            case "TH5|DESC":
                data = data.OrderByDescending(d => d.Amount).ToList();
                break;
            }

            foreach (var auditory in data)
            {
                if (!string.IsNullOrEmpty(filterText))
                {
                    var match = auditory.Description;
                    if (match.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1)
                    {
                        continue;
                    }
                }
                cont++;
                string statustextCell = string.Empty;
                switch (auditory.Status)
                {
                case 0: statustextCell = Dictionary["Item_Adutory_Status_Label_0"]; break;

                case 1: statustextCell = Dictionary["Item_Adutory_Status_Label_1"]; break;

                case 2: statustextCell = Dictionary["Item_Adutory_Status_Label_2"]; break;

                case 3: statustextCell = Dictionary["Item_Adutory_Status_Label_3"]; break;

                case 4: statustextCell = Dictionary["Item_Adutory_Status_Label_4"]; break;

                case 5: statustextCell = Dictionary["Item_Adutory_Status_Label_5"]; break;
                }

                string typetextCell = string.Empty;
                switch (auditory.Type)
                {
                case 0: typetextCell = Dictionary["Item_Adutory_Type_Label_0"]; break;

                case 1: typetextCell = Dictionary["Item_Adutory_Type_Label_1"]; break;

                case 2: typetextCell = Dictionary["Item_Adutory_Type_Label_2"]; break;
                }

                table.AddCell(ToolsPdf.DataCell(auditory.Description));
                table.AddCell(ToolsPdf.DataCellCenter(typetextCell));
                table.AddCell(ToolsPdf.DataCellCenter(statustextCell));
                table.AddCell(ToolsPdf.DataCellCenter(auditory.PlannedOn));
                table.AddCell(ToolsPdf.DataCellCenter(auditory.ValidatedOn));
                table.AddCell(ToolsPdf.DataCellMoney(auditory.Amount));
            }

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                                 CultureInfo.InvariantCulture,
                                                                 @"{0}: {1}",
                                                                 Dictionary["Common_RegisterCount"],
                                                                 cont), ToolsPdf.LayoutFonts.Times))
            {
                Border     = iTS.Rectangle.TOP_BORDER,
                Padding    = 6f,
                PaddingTop = 4f,
                Colspan    = 4
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
            {
                Border  = iTS.Rectangle.TOP_BORDER,
                Colspan = 4
            });

            pdfDoc.Add(table);
            pdfDoc.CloseDocument();
            res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
            return(res);
        }
Esempio n. 2
0
    public static ActionResult PDF(
        int companyId,
        string from,
        string to,
        long rulesId,
        long processId,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            Dictionary["Item_Oportunities"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = Dictionary["Item_Oportunities"].ToUpperInvariant()
        };

        pdfDoc.Open();
        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 15f, 50f, 15f, 50f, 15f, 50f });

        #region texts

        string criteriaProccess = Dictionary["Common_All_Male_Plural"];
        if (processId > 0)
        {
            var process = new Process(processId, companyId);
            if (!string.IsNullOrEmpty(process.Description))
            {
                criteriaProccess = process.Description;
            }
        }

        string periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = Dictionary["Item_Incident_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = Dictionary["Item_Incident_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " - " + to;
        }
        else
        {
            periode = Dictionary["Common_All_Male"];
        }

        string typetext = Dictionary["Common_All_Male_Plural"];

        string ruleDescription = Dictionary["Common_All_Female_Plural"];
        if (rulesId > 0)
        {
            var rule = Rules.GetById(companyId, rulesId);
            if (!string.IsNullOrEmpty(rule.Description))
            {
                ruleDescription = rule.Description;
            }
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, Dictionary["Common_Period"], periode);
        ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Process"], typetext);
        ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Rule"], ruleDescription);
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(7)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 10f, 10f, 30f, 20f, 20f, 10f, 10f });

        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_IncidentAction_Header_Type"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Date"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Oportunity"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Process"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Rule"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_StartValue"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_IPR"]));

        int cont = 0;
        var data = HttpContext.Current.Session["OportunityFilterData"] as List <OportunityFilterItem>;

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH1|ASC":
            data = data.OrderBy(d => d.OpenDate).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.OpenDate).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Process.Description).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Process.Description).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.Rule.Description).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Rule.Description).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.Rule.Limit).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.Rule.Limit).ToList();
            break;
        }

        foreach (OportunityFilterItem risk in data)
        {
            cont++;
            string typeText = string.Empty;
            if (risk.Result == 0)
            {
                typeText = Dictionary["Item_BusinessRisk_Status_Unevaluated"];
            }
            else if (risk.Result < risk.Rule.Limit)
            {
                typeText = Dictionary["Item_BusinessRisk_Status_NotSignificant"];
            }
            else
            {
                typeText = Dictionary["Item_BusinessRisk_Status_Significant"];
            }

            string initialResultText = risk.Result == 0 ? string.Empty : risk.Result.ToString();

            table.AddCell(ToolsPdf.DataCellCenter(typeText));
            table.AddCell(ToolsPdf.DataCellCenter(risk.OpenDate));
            table.AddCell(ToolsPdf.DataCell(risk.Description));
            table.AddCell(ToolsPdf.DataCell(risk.Process.Description));
            table.AddCell(ToolsPdf.DataCellCenter(risk.Rule.Description));
            table.AddCell(ToolsPdf.DataCellCenter(initialResultText));
            table.AddCell(ToolsPdf.DataCellRight(risk.Rule.Limit));
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             Dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border     = iTS.Rectangle.TOP_BORDER,
            Padding    = 6f,
            PaddingTop = 4f,
            Colspan    = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border  = iTS.Rectangle.TOP_BORDER,
            Colspan = 4
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 3
0
    public static ActionResult PDF(int companyId, string yearFrom, string yearTo, string mode, string listOrder, string textFilter)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_LearningList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        // evento para poner titulo y pie de página cada vez que salta de página
        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_LearningList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(4)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 3f, 12f, 3f, 22f });

        string periode = string.Empty;

        if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0" && !string.IsNullOrEmpty(yearTo) && yearTo != "0")
        {
            periode = yearFrom + " - " + yearTo;
        }
        else if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0")
        {
            periode = dictionary["Common_From"] + " " + yearFrom;
        }
        else if (!string.IsNullOrEmpty(yearTo) && yearTo != "0")
        {
            periode = dictionary["Item_Incident_List_Filter_To"] + " " + yearTo;
        }

        if (string.IsNullOrEmpty(periode))
        {
            periode = dictionary["Item_Learning_Filter_AllPeriode"];
        }
        ;

        string modeText = dictionary["Common_All_Female_Plural"];

        if (!string.IsNullOrEmpty(mode))
        {
            modeText = string.Empty;
            bool first = true;
            if (mode.IndexOf("0") != -1)
            {
                modeText += dictionary["Item_Learning_Status_InProgress"];
                first     = false;
            }

            if (mode.IndexOf("1") != -1)
            {
                if (!first)
                {
                    modeText += ", ";
                }
                modeText += dictionary["Item_Learning_Status_Started"];
                first     = false;
            }
            if (mode.IndexOf("2") != -1)
            {
                if (!first)
                {
                    modeText += ", ";
                }
                modeText += dictionary["Item_Learning_Status_Finished"];
                first     = false;
            }
            if (mode.IndexOf("3") != -1)
            {
                if (!first)
                {
                    modeText += ", ";
                }
                modeText += dictionary["Item_Learning_Status_Evaluated"];
            }
        }

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(modeText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        if (!string.IsNullOrEmpty(textFilter))
        {
            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_PDF_Filter_Contains"] + " :", ToolsPdf.LayoutFonts.TimesBold))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f
            });

            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(textFilter, ToolsPdf.LayoutFonts.Times))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 5
            });
        }

        pdfDoc.Add(criteriatable);

        var table = new iTSpdf.PdfPTable(5)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 15f, 5f, 5f, 5f, 5f });
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Course"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_EstimatedDate"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_ListHeader_DateComplete"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Cost"]));
        int cont = 0;

        DateTime?yFrom = null;
        DateTime?yTo   = null;

        if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0")
        {
            // yFrom = Tools.TextToDate(yearFrom);
            var parts = yearFrom.Split('/');
            yFrom = new DateTime(Convert.ToInt32(parts[2]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[0]));
        }

        if (!string.IsNullOrEmpty(yearTo) && yearTo != "0")
        {
            // yTo = Tools.TextToDate(yearTo);
            var parts = yearTo.Split('/');
            yTo = new DateTime(Convert.ToInt32(parts[2]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[0]));
        }

        var learningFilter = new LearningFilter(companyId)
        {
            Pendent   = mode.IndexOf("0") != -1,
            Started   = mode.IndexOf("1") != -1,
            Finished  = mode.IndexOf("2") != -1,
            Evaluated = mode.IndexOf("3") != -1,
            YearFrom  = yFrom,
            YearTo    = yTo
        };

        decimal totalCost = 0;
        int     count     = 0;

        var data = learningFilter.Filter().ToList();

        if (!string.IsNullOrEmpty(listOrder))
        {
            switch (listOrder.ToUpperInvariant())
            {
            default:
            case "TH0|ASC":
                data = data.OrderBy(d => d.Description).ToList();
                break;

            case "TH0|DESC":
                data = data.OrderByDescending(d => d.Description).ToList();
                break;

            case "TH1|ASC":
                data = data.OrderBy(d => d.RealStart).ToList();
                break;

            case "TH1|DESC":
                data = data.OrderByDescending(d => d.RealStart).ToList();
                break;

            case "TH2|ASC":
                data = data.OrderBy(d => d.RealFinish).ToList();
                break;

            case "TH2|DESC":
                data = data.OrderByDescending(d => d.RealFinish).ToList();
                break;

            case "TH3|ASC":
                data = data.OrderBy(d => d.Status).ToList();
                break;

            case "TH3|DESC":
                data = data.OrderByDescending(d => d.Status).ToList();
                break;

            case "TH4|ASC":
                data = data.OrderBy(d => d.Amount).ToList();
                break;

            case "TH4|DESC":
                data = data.OrderByDescending(d => d.Amount).ToList();
                break;
            }
        }

        // aplicar filtro de texto
        if (!string.IsNullOrEmpty(textFilter))
        {
            data = data.Where(d => d.Description.IndexOf(textFilter, StringComparison.OrdinalIgnoreCase) != -1).ToList();
        }

        foreach (var learning in data)
        {
            count++;
            learning.ObtainAssistance();
            string assist = string.Empty;
            bool   first  = true;
            foreach (var alumno in learning.Assistance)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    assist += ", ";
                }

                assist += alumno.Employee.FullName;
            }

            if (string.IsNullOrEmpty(assist))
            {
                assist = "(" + dictionary["Item_LearningList_NoAssistants"] + ")";
            }

            int border = 0;
            table.AddCell(ToolsPdf.DataCell(learning.Description));
            table.AddCell(ToolsPdf.DataCellCenter(learning.DateEstimated));

            /*
             * string fecha = Tools.TranslatedMonth(learning.DateEstimated.Month, dictionary) + " " + learning.DateEstimated.Year;
             * table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(fecha, ToolsPdf.LayoutFonts.Times))
             * {
             *  Border = border,
             *  Padding = 6f,
             *  PaddingTop = 4f,
             *  HorizontalAlignment = Rectangle.ALIGN_CENTER
             * });
             */
            if (learning.RealFinish != null)
            {
                if (learning.RealFinish.Value.Year == 1970)
                {
                    table.AddCell(ToolsPdf.DataCell(string.Empty));
                }
                else
                {
                    table.AddCell(ToolsPdf.DataCellCenter(learning.RealFinish));
                }
            }
            else
            {
                table.AddCell(ToolsPdf.DataCell(string.Empty));
            }

            string statusText = string.Empty;
            switch (learning.Status)
            {
            default:
            case 0: statusText = dictionary["Item_Learning_Status_InProgress"]; break;

            case 1: statusText = dictionary["Item_Learning_Status_Started"]; break;

            case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break;

            case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break;
            }

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                Padding             = ToolsPdf.PaddingTableCell,
                PaddingTop          = ToolsPdf.PaddingTopTableCell,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(ToolsPdf.DataCellMoney(learning.Amount));
            totalCost += learning.Amount;

            cont++;
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            count);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 3
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        string totalText = string.Format("{0:#,##0.00}", totalCost);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalText, ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int objetivoId = Convert.ToInt32(Request.QueryString["id"]);
        int companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var company    = new Company(companyId);
        var res        = ActionResult.NoAction;
        var user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var objetivo   = Objetivo.ById(objetivoId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(objetivo.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Objetivo"],
            formatedDescription,
            DateTime.Now);

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;
        string status       = string.Empty;

        var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);
        var writer   = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = objetivo.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Objetivo"].ToUpperInvariant()
        };

        document.Open();

        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 15f, 30f, 15f, 30f });

        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Name"], objetivo.Name, 3);
        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Responsible"], objetivo.Responsible.FullName, 3);
        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_DateStart"], objetivo.StartDate);
        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_ClosePreviewDate"], objetivo.PreviewEndDate);

        if (objetivo.VinculatedToIndicator)
        {
            var indicador = Indicador.ById(objetivo.IndicatorId.Value, companyId);
            ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Indicator"], indicador.Description);
            ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Periodicity"], indicador.Periodicity);
        }

        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Description"], objetivo.Description, 4);
        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Methodology"], objetivo.Methodology, 4);
        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Resources"], objetivo.Resources, 4);
        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Notes"], objetivo.Notes, 4);

        document.Add(table);

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            #region Acciones
            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                var acciones = IncidentAction.ByObjetivoId(objetivoId, companyId);
                if (acciones.Count > 0)
                {
                    document.SetPageSize(PageSize.A4.Rotate());
                    document.NewPage();

                    var tableAcciones = new PdfPTable(5)
                    {
                        WidthPercentage     = 100,
                        HorizontalAlignment = 1,
                        SpacingBefore       = 20f
                    };

                    tableAcciones.SetWidths(new float[] { 20f, 120f, 20f, 20f, 20f });
                    ToolsPdf.AddTableTitle(tableAcciones, dictionary["Item_Objetivo_ActionsReportTitle"]);
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Cost"]));

                    int     cont          = 0;
                    decimal totalAcciones = 0;
                    foreach (var accion in acciones)
                    {
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.Status));
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.Description));
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.WhatHappenedOn));
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.ActionsOn));
                        tableAcciones.AddCell(ToolsPdf.DataCell(0));
                        cont++;
                        var costs = IncidentActionCost.GetByIncidentActionId(accion.Id, company.Id);
                        foreach (var cost in costs)
                        {
                            totalAcciones = cost.Amount;
                        }
                    }

                    // TotalRow
                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        Padding             = 8f
                    });

                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_RIGHT,
                        Padding             = 8f
                    });

                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        Padding             = 8f,
                        Colspan             = 2
                    });

                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", totalAcciones), ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_RIGHT,
                        Padding             = 8f
                    });

                    tableAcciones.AddCell(new PdfPCell(new Phrase(string.Empty))
                    {
                        Colspan = 3, Border = Rectangle.TOP_BORDER
                    });

                    document.Add(tableAcciones);
                }
            }
            #endregion
        }

        #region Registros
        if (objetivo.VinculatedToIndicator)
        {
            var registros = IndicadorRegistro.ByIndicadorId(objetivo.IndicatorId.Value, companyId).ToList();
            if (registros.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableRegistros = new PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableRegistros.SetWidths(new float[] { 20f, 20f, 120f, 40f, 50f });
                ToolsPdf.AddTableTitle(tableRegistros, dictionary["Item_Objetivo_RecordsReportTitle"]);
                tableRegistros.AddCell(ToolsPdf.HeaderCell("*" + dictionary["Item_Indicador_TableRecords_Header_Value"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"]));

                int cont = 0;
                foreach (var registro in registros)
                {
                    string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString();
                    // WEKE ALEX: con datacellmoney el dato debe ser decimal y lo poen con dos decimales
                    tableRegistros.AddCell(ToolsPdf.DataCellMoney(registro.Value));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Date));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments));
                    tableRegistros.AddCell(ToolsPdf.DataCell(meta));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName));
                    cont++;
                }

                // TotalRow
                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_LEFT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty))
                {
                    Colspan = 3, Border = Rectangle.TOP_BORDER
                });

                document.Add(tableRegistros);
            }
        }
        else
        {
            var registros = ObjetivoRegistro.GetByObjetivo(objetivoId, companyId).ToList();
            if (registros.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableRegistros = new PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableRegistros.SetWidths(new float[] { 20f, 120f, 20f, 40f, 50f });

                tableRegistros.AddCell(new PdfPCell(new Phrase(dictionary["Item_Objetivo_RecordsReportTitle"]))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Value"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"]));

                int cont = 0;
                foreach (var registro in registros)
                {
                    string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString();
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Value));
                    tableRegistros.AddCell(ToolsPdf.DataCellCenter(registro.Date));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments));
                    tableRegistros.AddCell(ToolsPdf.DataCell(meta));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName));
                    cont++;
                }

                // TotalRow
                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_LEFT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty))
                {
                    Colspan = 3, Border = Rectangle.TOP_BORDER
                });

                document.Add(tableRegistros);
            }
        }
        #endregion

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            #region Historico
            var historico = ObjetivoHistorico.ByObjetivoId(objetivoId);
            if (historico.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableHistorico = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableHistorico.SetWidths(new float[] { 20f, 20f, 120f, 50f });
                ToolsPdf.AddTableTitle(tableHistorico, dictionary["Item_Objetivo_TabHistoric"]);
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_Action"]));
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IndicatorRecord_FieldLabel_Date"]));
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_ObjetivoRecord_FieldLabel_Reason"]));
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_CloseResponsible"]));

                int cont = 0;
                foreach (var objetivoHistorico in historico)
                {
                    var actionText  = string.Empty;
                    var description = string.Empty;

                    if (objetivoHistorico.Reason == "Restore")
                    {
                        actionText = dictionary["Item_ObjetivoHistorico_StatusRestore"];
                    }
                    else
                    {
                        actionText  = dictionary["Item_ObjetivoHistorico_StatusAnulate"];
                        description = objetivoHistorico.Reason;
                    }

                    tableHistorico.AddCell(ToolsPdf.DataCell(actionText));
                    tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Date));
                    tableHistorico.AddCell(ToolsPdf.DataCell(description));
                    tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Employee.FullName));
                    cont++;
                }

                // TotalRow
                tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_LEFT,
                    Padding             = 8f
                });

                tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 8f
                });

                tableHistorico.AddCell(new PdfPCell(new Phrase(string.Empty))
                {
                    Colspan = 2, Border = Rectangle.TOP_BORDER
                });

                document.Add(tableHistorico);
            }
            #endregion
        }

        document.Close();

        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        long auditoryId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company    = new Company(companyId);
        var  res        = ActionResult.NoAction;
        var  user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  auditory   = Auditory.ById(auditoryId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }



        string formatedDescription = auditory.Description.Replace("?", string.Empty);

        formatedDescription = formatedDescription.Replace("#", string.Empty);
        formatedDescription = formatedDescription.Replace("/", string.Empty);
        formatedDescription = formatedDescription.Replace("\\", string.Empty);
        formatedDescription = formatedDescription.Replace(":", string.Empty);
        formatedDescription = formatedDescription.Replace(";", string.Empty);
        formatedDescription = formatedDescription.Replace(".", string.Empty);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Auditory"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);
        var document        = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = auditory.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Auditory"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        #region Dades bàsiques
        // Ficha pincipal
        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 50f, 30f, 50f });

        table.AddCell(new PdfPCell(new Phrase(auditory.Description, descriptionFont))
        {
            Colspan             = 4,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 20f,
            PaddingBottom       = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Type"]));
        table.AddCell(TitleData(dictionary["Item_Adutory_Type_Label_" + auditory.Type.ToString()]));

        if (auditory.Provider.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Provider"]));
            table.AddCell(TitleData(auditory.Provider.Description));
        }
        else if (auditory.Customer.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Customer"]));
            table.AddCell(TitleData(auditory.Customer.Description));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 2));
        }

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Rules"]));
        var  rulesText = string.Empty;
        bool firstRule = true;
        foreach (var rule in auditory.Rules)
        {
            if (firstRule)
            {
                firstRule = false;
            }
            else
            {
                rulesText += ", ";
            }

            rulesText += rule.Description;
        }
        table.AddCell(TitleData(rulesText, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_InternalResponsible"]));
        table.AddCell(TitleData(auditory.InternalResponsible.FullName, 3));

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PannedDate"]));
        //table.AddCell(TitleData(previewDateText));

        table.AddCell(TitleLabel(dictionary["Item_Audiotry_PDF_Planned"]));
        if (auditory.PlannedBy.Id > 0)
        {
            var planningText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.PlannedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-");
            table.AddCell(TitleData(planningText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PlanningDate"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Closing"]));
        if (auditory.ClosedBy.Employee.Id > 0)
        {
            var closedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ClosedBy.Employee.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-");
            table.AddCell(TitleData(closedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ClosedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Validation"]));
        if (auditory.ValidatedBy.Id > 0)
        {
            var validatedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ValidatedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-");
            table.AddCell(TitleData(validatedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ValidatedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Address"]));
        table.AddCell(TitleData(auditory.EnterpriseAddress, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_AuditorTeam"]));
        table.AddCell(TitleData(auditory.AuditorTeam, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Notes"]));
        table.AddCell(TitleData(string.IsNullOrEmpty(auditory.Notes.Trim()) ? "-" : auditory.Notes, 3));

        document.Add(table);
        #endregion

        if (auditory.Status > 3)
        {
            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();


            var widthsActions = new float[] { 5f, 30f, 5f };
            var tableAccions  = new PdfPTable(widthsActions.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableAccions.SetWidths(widthsActions);
            tableAccions.AddCell(new PdfPCell(new Phrase(dictionary["Item_IncidentActions"], descriptionFont))
            {
                Colspan             = 3,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Tipo"]));
            tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction"]));
            tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));

            var accions = IncidentAction.ByAuditoryId(auditory.Id, auditory.CompanyId);
            foreach (var accio in accions)
            {
                tableAccions.AddCell(ToolsPdf.DataCell(dictionary["Item_IncidentAction_Type" + accio.ActionType.ToString()]));
                tableAccions.AddCell(ToolsPdf.DataCell(accio.Description));
                tableAccions.AddCell(ToolsPdf.DataCell(accio.WhatHappenedOn));
            }

            document.Add(tableAccions);
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Esempio n. 6
0
    public static ActionResult PDF(
        long equipmentId,
        int companyId,
        bool calibrationInternal,
        bool calibrationExternal,
        bool verificationInternal,
        bool verificationExternal,
        bool maintenanceInternal,
        bool maintenanceExternal,
        bool repairInternal,
        bool repairExternal,
        DateTime?dateFrom,
        DateTime?dateTo,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var equipment = Equipment.ById(equipmentId, companyId);
        var company   = new Company(equipment.CompanyId);
        var data      = HttpContext.Current.Session["EquipmentRecordsFilter"] as List <EquipmentRecord>;

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Equipment"],
            equipment.Description,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = equipment.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Equipment_PDFTitle"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(220, 220, 220);

        string periode = string.Empty;

        if (dateFrom.HasValue && dateTo.HasValue)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"Periode: {0:dd/MM/yyyy} - {1:dd/MM/yyyy}",
                dateFrom.Value,
                dateTo.Value);
        }
        else if (dateFrom.HasValue && dateTo == null)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"{1}: {0:dd/MM/yyyy}",
                dateFrom.Value,
                dictionary["Common_From"]);
        }
        else if (dateFrom == null && dateTo.HasValue)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"{1}: {0:dd/MM/yyyy}",
                dateTo.Value,
                dictionary["Common_To"]);
        }

        if (string.IsNullOrEmpty(periode))
        {
            periode = dictionary["Common_PeriodAll"];
        }

        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 25f, 250f });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Equipment"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Description, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Customer_Header_Type"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        string typeText  = string.Empty;
        bool   firstType = true;

        if (calibrationInternal)
        {
            firstType = false;
            typeText += dictionary["Item_EquipmentRecord_Filter_CalibrationInternal"];
        }

        if (calibrationExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_CalibrationExternal"];
            firstType = false;
        }

        if (verificationInternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_VerificationInternal"];
            firstType = false;
        }

        if (verificationExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_VerificationExternal"];
            firstType = false;
        }
        if (maintenanceInternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_MaintenanceInternal"];
            firstType = false;
        }

        if (maintenanceExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_MaintenanceExternal"];
            firstType = false;
        }

        if (repairInternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_RepairInternal"];
            firstType = false;
        }

        if (repairExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_RepairExternal"];
        }

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(typeText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        pdfDoc.Add(criteriatable);

        var table = new iTSpdf.PdfPTable(5)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        //relative col widths in proportions - 1/3 and 2/3
        table.SetWidths(new float[] { 10f, 20f, 15f, 30f, 15f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Date"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Type"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Operation"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Responsible"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Cost"]));

        decimal totalCost = 0;
        int     cont      = 0;

        // Poner el tipo de registro diccionarizado
        foreach (var record in data)
        {
            record.RecordTypeText = dictionary[record.Item + "-" + (record.RecordType == 0 ? "Int" : "Ext")];
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Date).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Date).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.RecordTypeText).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.RecordTypeText).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Operation).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Operation).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Responsible.FullName).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Responsible.FullName).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.Cost).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Cost).ToList();
            break;
        }

        foreach (var equipmentRecord in data)
        {
            table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", equipmentRecord.Date), ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(equipmentRecord.RecordTypeText, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(equipmentRecord.Operation, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(equipmentRecord.Responsible.FullName, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellMoney(equipmentRecord.Cost, ToolsPdf.LayoutFonts.Times));

            if (equipmentRecord.Cost.HasValue)
            {
                totalCost += equipmentRecord.Cost.Value;
            }

            cont++;
        }


        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 2
        });

        table.AddCell(new PdfPCell(new iTS.Phrase(dictionary["Common_Total"], ToolsPdf.LayoutFonts.Times))
        {
            Border = iTS.Rectangle.TOP_BORDER,
            HorizontalAlignment = iTS.Element.ALIGN_RIGHT,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Colspan             = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#,##0.00}", totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            HorizontalAlignment = iTS.Element.ALIGN_RIGHT
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 7
0
    public ActionResult PDF(
        int companyId,
        string from,
        string to,
        bool statusIdentified,
        bool statusAnalyzed,
        bool statusInProgress,
        bool statusClose,
        bool typeImprovement,
        bool typeFix,
        bool typePrevent,
        int origin,
        int reporter,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentActionList"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentActions"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        var titleCell = new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = ToolsPdf.BorderNone
        };

        titleTable.AddCell(titleCell);

        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(4);

        criteriatable.SetWidths(new float[] { 20f, 50f, 15f, 100f });
        criteriatable.WidthPercentage = 100;

        #region texts

        string criteriaOrigin = dictionary["Common_All_Male"];
        if (origin == 1)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin1"];
        }
        if (origin == 2)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin2"];
        }
        if (origin == 3)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin3"];
        }
        if (origin == 4)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin46"];
        }
        if (origin == 5)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin5"];
        }

        string reporterText = dictionary["Common_All_Male"];
        if (reporter == 1)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType1"];
        }
        if (reporter == 2)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType2"];
        }
        if (reporter == 3)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType3"];
        }


        string periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_IncidentAction_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_IncidentAction_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " " + to;
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        string typetext = string.Empty;

        bool firstType = false;
        if (typeImprovement)
        {
            typetext  = dictionary["Item_IncidentAction_Type1"];
            firstType = false;
        }
        if (typeFix)
        {
            if (!firstType)
            {
                typetext += " - ";
            }
            typetext += dictionary["Item_IncidentAction_Type2"];
            firstType = false;
        }
        if (typePrevent)
        {
            if (!firstType)
            {
                typetext += " - ";
            }
            typetext += dictionary["Item_IncidentAction_Type3"];
        }

        string statusText  = string.Empty;
        bool   firstStatus = true;
        if (statusIdentified)
        {
            firstStatus = false;
            statusText += dictionary["Item_IndicentAction_Status1"];
        }

        if (statusAnalyzed)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status2"];
            firstStatus = false;
        }

        if (statusInProgress)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status3"];
            firstType   = false;
        }

        if (statusClose)
        {
            if (!firstType)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status4"];

            firstType = false;
        }
        #endregion

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Customer_Header_Type"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new PdfPCell(new iTS.Phrase(typetext, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_IncidentAction_Header_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_IncidentAction_Header_Origin"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(criteriaOrigin, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_IncidentAction_Label_Reporter"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(reporterText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        if (string.IsNullOrEmpty(filterText))
        {
            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.TimesBold))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 2
            });
        }
        else
        {
            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_PDF_Filter_Contains"] + " :", ToolsPdf.LayoutFonts.TimesBold))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f
            });

            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(filterText, ToolsPdf.LayoutFonts.Times))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f
            });
        }

        pdfDoc.Add(criteriatable);
        //---------------------------

        var table = new iTSpdf.PdfPTable(8)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 3f, 10f, 10f, 30f, 10f, 10f, 10f, 10f });
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Label_Number"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Type"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
        // table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Cost"]));

        int     cont      = 0;
        decimal totalCost = 0;
        var     data      = HttpContext.Current.Session["IncidentActionFilterData"] as List <IncidentActionFilterItem>;

        // @alex: necesitamos el texto del tipo de acción y el origen para ordenarlos alfbéticamente
        //       independientemente del id en la bbdd
        foreach (var item in data)
        {
            string originText = string.Empty;
            if (item.Origin == 1)
            {
                originText = dictionary["Item_IncidentAction_Origin1"];
            }
            if (item.Origin == 2)
            {
                originText = dictionary["Item_IncidentAction_Origin2"];
            }
            if (item.Origin == 3)
            {
                originText = dictionary["Item_IncidentAction_Origin3"];
            }
            if (item.Origin == 4)
            {
                originText = dictionary["Item_IncidentAction_Origin4"];
            }
            if (item.Origin == 5)
            {
                originText = dictionary["Item_IncidentAction_Origin5"];
            }
            if (item.Origin == 6)
            {
                originText = dictionary["Item_IncidentAction_Origin6"];
            }
            item.OriginText = originText;

            string typeText = string.Empty;
            if (item.ActionType == 1)
            {
                typeText = dictionary["Item_IncidentAction_Type1"];
            }
            if (item.ActionType == 2)
            {
                typeText = dictionary["Item_IncidentAction_Type2"];
            }
            if (item.ActionType == 3)
            {
                typeText = dictionary["Item_IncidentAction_Type3"];
            }
            item.ActionTypeText = typeText;
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Status).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Status).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.OpenDate).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.OpenDate).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.OriginText).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.OriginText).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.ActionTypeText).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.ActionTypeText).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.ImplementationDate).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.ImplementationDate).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.CloseDate).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.CloseDate).ToList();
            break;
        }

        foreach (IncidentActionFilterItem action in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                if (action.Description.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1 &&
                    action.Number.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    continue;
                }
            }

            int border = 0;
            totalCost += action.Amount;

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(action.Number, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            string actionTypeText = string.Empty;
            switch (action.ActionType)
            {
            default:
            case 1: actionTypeText = dictionary["Item_IncidentAction_Type1"]; break;

            case 2: actionTypeText = dictionary["Item_IncidentAction_Type2"]; break;

            case 3: actionTypeText = dictionary["Item_IncidentAction_Type3"]; break;
            }

            string statustext = string.Empty;
            if (action.Status == 1)
            {
                statustext = dictionary["Item_IndicentAction_Status1"];
            }
            if (action.Status == 2)
            {
                statustext = dictionary["Item_IndicentAction_Status2"];
            }
            if (action.Status == 3)
            {
                statustext = dictionary["Item_IndicentAction_Status3"];
            }
            if (action.Status == 4)
            {
                statustext = dictionary["Item_IndicentAction_Status4"];
            }

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statustext, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.OpenDate), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", action.Number, action.Description), ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = ToolsPdf.LineBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(action.OriginText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(actionTypeText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ImplementationDate), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            /*table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CloseDate), ToolsPdf.LayoutFonts.Times))
             * {
             *  Border = border,
             *  BackgroundColor = ToolsPdf.LineBackgroundColor,
             *  Padding = 6f,
             *  PaddingTop = 4f,
             *  HorizontalAlignment = Rectangle.ALIGN_CENTER
             * });*/

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(action.Amount), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            cont++;
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Colspan         = 1
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var incidentId = Convert.ToInt64(Request.QueryString["id"]);
        var companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var company    = new Company(companyId);
        var res        = ActionResult.NoAction;
        var user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var incident   = Incident.GetById(incidentId, user.CompanyId);
        var path       = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(incident.Description);

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Incident"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;

        if (incident.Origin == 1)
        {
            origin = dictionary["Item_Incident_Origin1"];
        }
        if (incident.Origin == 2)
        {
            origin = dictionary["Item_Incident_Origin2"];
        }
        if (incident.Origin == 3)
        {
            origin = dictionary["Item_Incident_Origin3"];
        }

        if (incident.Department.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin1"];
            reporter     = Department.ById(incident.Department.Id, incident.CompanyId).Description;
        }
        else if (incident.Provider.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin2"];
            reporter     = Provider.ById(incident.Provider.Id, incident.CompanyId).Description;
        }
        else if (incident.Customer.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin3"];
            reporter     = Customer.ById(incident.Customer.Id, incident.CompanyId).Description;
        }

        string status = string.Empty;

        var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = incident.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Incident"]
        };

        pageEventHandler.Titles = new List <string>
        {
            dictionary["Item_IncidentAction"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 15f, 30f, 15f, 30f });

        var borderNone  = Rectangle.NO_BORDER;
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderAll   = Rectangle.RIGHT_BORDER + Rectangle.TOP_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;

        var alignLeft  = Element.ALIGN_LEFT;
        var alignRight = Element.ALIGN_RIGHT;

        var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY);
        var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK);

        // Descripción
        table.AddCell(LabelCell(dictionary["Item_Incident"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(incident.Code.ToString() + " - " + incident.Description, borderNone, alignLeft, 3));

        // Reportador
        if (incident.Origin != 4)
        {
            table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER));
            table.AddCell(ValueCell(reporterType + " (" + reporter + ")", borderNone, alignLeft, 3));
        }

        // WhatHappend
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.WhatHappened, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.WhatHappenedOn), borderBR, alignRight, 2));

        // Causes
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Causes, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.CausesBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.CausesOn), borderBR, alignRight, 2));

        // Actions
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_Incident_Label_Actions"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Actions, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.ActionsBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], incident.ActionsOn), borderBR, alignRight, 2));

        // Close
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], incident.ClosedBy.FullName), borderTBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], incident.ClosedOn), borderTBR, alignRight, 2));

        // Notes
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Notes, borderAll, alignLeft, 4));

        document.Add(table);

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            // Añadir posible acción
            var action = IncidentAction.ByIncidentId(incident.Id, companyId);
            if (action.Id > 0)
            {
                var tableAction = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f });

                // Descripción
                var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK);
                tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont))
                {
                    Colspan             = 4,
                    Border              = ToolsPdf.BorderBottom,
                    HorizontalAlignment = Rectangle.ALIGN_CENTER
                });
                tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER));
                tableAction.AddCell(ValueCell(action.Description, borderNone, alignLeft, 3));

                // WhatHappend
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

                // Causes
                var causesFullName = string.Empty;
                var causesDate     = string.Empty;
                if (action.CausesBy != null)
                {
                    causesFullName = action.CausesBy.FullName;
                    causesDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2));

                // Actions
                var actionFullName = string.Empty;
                var actionDate     = string.Empty;
                if (action.ActionsBy != null)
                {
                    actionFullName = action.ActionsBy.FullName;
                    actionDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2));

                // Monitoring
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, borderAll, alignLeft, 4));

                // Close
                var closedFullName = string.Empty;
                var closedDate     = string.Empty;
                if (action.ClosedBy != null)
                {
                    closedFullName = action.ClosedBy.FullName;
                    closedDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2));

                // Notes
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, borderAll, alignLeft, 4));

                document.NewPage();
                document.Add(tableAction);
            }
        }

        // Costes
        var costs = IncidentCost.AllCosts(incidentId, companyId);

        if (costs.Count > 0)
        {
            var times           = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK);
            var fontSummary     = new Font(arial, 9, Font.BOLD, BaseColor.BLACK);
            var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK);
            var tableCosts      = new PdfPTable(5)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 1,
                SpacingBefore       = 20f,
                SpacingAfter        = 30f
            };

            tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f });

            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

            decimal total           = 0;
            decimal totalIncidencia = 0;
            decimal totalAccion     = 0;
            int     cont            = 0;
            int     contIncidencia  = 0;
            int     contAccion      = 0;
            foreach (var cost in costs.Where(c => c.Source == "I"))
            {
                tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                total           += cost.Amount * cost.Quantity;
                totalIncidencia += cost.Amount * cost.Quantity;
                cont++;
                contIncidencia++;
            }

            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                               CultureInfo.InvariantCulture,
                                                               @"{0} {2}: {1}",
                                                               dictionary["Common_RegisterCount"],
                                                               contIncidencia,
                                                               dictionary["Item_Incident"]), times))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 2
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalIncidencia), times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 1
                });
            }

            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                // Acciones
                foreach (var cost in costs.Where(c => c.Source == "A"))
                {
                    tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                    tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                    total      += cost.Amount * cost.Quantity;
                    totalAccion = cost.Amount * cost.Quantity;
                    cont++;
                    contAccion++;
                }

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                               CultureInfo.InvariantCulture,
                                                               @"{0} {2}: {1}",
                                                               dictionary["Common_RegisterCount"],
                                                               contAccion,
                                                               dictionary["Item_IncidentAction"]), times))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 2
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalAccion), times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 1
                });
            }

            // resumen
            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                           CultureInfo.InvariantCulture,
                                                           @"{0}: {1}",
                                                           dictionary["Common_RegisterCount"],
                                                           cont), fontSummary))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 2
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], fontSummary))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), fontSummary))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT,
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, fontSummary)))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 1
            });

            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();
            document.Add(tableCosts);
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Esempio n. 9
0
    public static ActionResult PDF(
        int companyId,
        int indicatorType,
        DateTime?from,
        DateTime?to,
        int?processId,
        int?processTypeId,
        int?targetId,
        int status,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Indicador_List"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_Indicador_List"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        var table = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 20f, 50f, 25f, 50f, 20f, 150f });

        var criteriaBlank = new iTSpdf.PdfPCell(new iTS.Phrase(".", ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = ToolsPdf.PaddingTopTableCell,
            PaddingTop          = ToolsPdf.PaddingTopCriteriaCell
        };

        string periode = string.Empty;

        if (from.HasValue && to == null)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_From"], from);
        }
        else if (from == null && to.HasValue)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_To"], to);
        }
        else if (from.HasValue && to.HasValue)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy} {1:dd/MM/yyyy}", from, to);
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Common_Period"]));

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = ToolsPdf.PaddingTopTableCell,
            PaddingTop          = ToolsPdf.PaddingTopCriteriaCell
        });

        criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_IncidentAction_Header_Status"]));

        string statusText = dictionary["Common_All"];

        if (status == 1)
        {
            statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowActive"];
        }

        if (status == 2)
        {
            statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowClosed"];
        }

        criteriatable.AddCell(ToolsPdf.CriteriaCellData(statusText));
        criteriatable.AddCell(criteriaBlank);
        criteriatable.AddCell(criteriaBlank);

        criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_Indicaddor_Filter_TypeLabel"]));

        string indicadorTypeText = string.Empty;

        switch (indicatorType)
        {
        case 0:
            indicadorTypeText = dictionary["Common_All_Male_Plural"];
            break;

        case 1:
            indicadorTypeText = dictionary["Item_Indicaddor_Filter_TypeProcess"];
            break;

        case 2:
            indicadorTypeText = dictionary["Item_Indicaddor_Filter_TypeObjetivo"];
            break;

        default:
            indicadorTypeText = dictionary["Common_All_Male_Plural"];
            break;
        }

        criteriatable.AddCell(ToolsPdf.CriteriaCellData(indicadorTypeText));

        switch (indicatorType)
        {
        case 1:
            string processText = dictionary["Common_All_Male_Plural"];
            if (processId.HasValue)
            {
                processText = new Process(processId.Value, companyId).Description;
            }

            string processTypeCriteriaText = dictionary["Common_All_Male_Plural"];
            if (processTypeId.HasValue)
            {
                switch (processTypeId.Value)
                {
                case 1:
                    processTypeCriteriaText = dictionary["Item_ProcessType_Name_Principal"];
                    break;

                case 2:
                    processTypeCriteriaText = dictionary["Item_ProcessType_Name_Support"];
                    break;

                case 3:
                    processTypeCriteriaText = dictionary["Item_ProcessType_Name_Estrategic"];
                    break;

                default:
                    processTypeCriteriaText = string.Empty;
                    foreach (var t in ProcessType.ObtainByCompany(companyId, dictionary))
                    {
                        if (t.Id == processTypeId)
                        {
                            processTypeCriteriaText = t.Description;
                        }
                    }

                    break;
                }
            }

            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_Process"]));

            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(processText, ToolsPdf.LayoutFonts.Times))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = ToolsPdf.PaddingTopTableCell,
                PaddingTop          = ToolsPdf.PaddingTopCriteriaCell
            });

            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_ProcessType"]));

            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(processTypeCriteriaText, ToolsPdf.LayoutFonts.Times))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = ToolsPdf.PaddingTopTableCell,
                PaddingTop          = ToolsPdf.PaddingTopCriteriaCell
            });
            break;

        case 2:

            string objetivoText = dictionary["Common_All_Male_Plural"];
            if (targetId.HasValue)
            {
                objetivoText = Objetivo.ById(targetId.Value, companyId).Name;
            }

            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_Objetivo"]));

            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(objetivoText, ToolsPdf.LayoutFonts.Times))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = ToolsPdf.PaddingTopTableCell,
                PaddingTop          = ToolsPdf.PaddingTopCriteriaCell,
                Colspan             = 3
            });
            break;

        default:
            criteriatable.AddCell(criteriaBlank);
            criteriatable.AddCell(criteriaBlank);
            criteriatable.AddCell(criteriaBlank);
            criteriatable.AddCell(criteriaBlank);
            break;
        }

        pdfDoc.Add(criteriatable);
        //---------------------------

        table.SetWidths(new float[] { 7f, 30f, 10f, 30f, 10f, 10f });;

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_StartDate"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_Process"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_ProcessType"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_ObjetivoResponsible"]));

        var tipoProcesos = ProcessType.ObtainByCompany(company.Id, dictionary);

        int cont = 0;
        var data = Indicador.Filter(companyId, indicatorType, from, to, processId, processTypeId, targetId, status).ToList();

        foreach (var item in data)
        {
            string processTypeText = string.Empty;
            switch (item.Proceso.ProcessType)
            {
            case 1:
                item.Proceso.Work = dictionary["Item_ProcessType_Name_Principal"];
                break;

            case 2:
                item.Proceso.Work = dictionary["Item_ProcessType_Name_Support"];
                break;

            case 3:
                item.Proceso.Work = dictionary["Item_ProcessType_Name_Estrategic"];
                break;

            default:
                item.Proceso.Work = tipoProcesos.First(tp => tp.Id == item.Proceso.ProcessType).Description;
                break;
            }
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Indicador.Description).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Indicador.Description).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.StartDate).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.StartDate).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Proceso.Description).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Proceso.Description).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Proceso.Work).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Proceso.Work).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.ObjetivoResponsible).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.ObjetivoResponsible).ToList();
            break;
        }

        foreach (var item in data)
        {
            table.AddCell(ToolsPdf.DataCell(item.Status == 0 ? dictionary["Common_Active"] : dictionary["Common_Inactive"], ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Indicador.Description, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.StartDate, ToolsPdf.LayoutFonts.Times, Rectangle.ALIGN_CENTER));
            table.AddCell(ToolsPdf.DataCell(item.Proceso.Description, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Proceso.Work, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.ObjetivoResponsible, ToolsPdf.LayoutFonts.Times));
            cont++;
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = backgroundColor,
            Padding         = ToolsPdf.PaddingTopTableCell,
            PaddingTop      = ToolsPdf.PaddingTopCriteriaCell,
            Colspan         = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = backgroundColor,
            Colspan         = 4
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 10
0
    public static ActionResult Excel(int companyId, DateTime?dateFrom, DateTime?dateTo, string indicadorName, int indicadorId, string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var company   = new Company(companyId);
        var registros = IndicadorRegistro.ByIndicadorId(indicadorId, companyId).ToList();

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(indicadorName);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.xls",
            dictionary["Item_Indicador_RecordsReportTitle"],
            formatedDescription,
            DateTime.Now);

        fileName = fileName.Replace("%", "");

        var wb         = HSSFWorkbook.Create(InternalWorkbook.CreateWorkbook());
        var sh         = (HSSFSheet)wb.CreateSheet(dictionary["Item_Indicador_RecordsReportTitle"]);
        var shCriteria = (HSSFSheet)wb.CreateSheet(dictionary["Common_SearchCriteria"]);

        var moneyCellStyle = wb.CreateCellStyle();
        var hssfDataFormat = wb.CreateDataFormat();

        moneyCellStyle.DataFormat = hssfDataFormat.GetFormat("#,##0.00");

        var headerCellStyle = wb.CreateCellStyle();
        var headerFont      = wb.CreateFont();

        headerFont.Boldweight = (short)FontBoldWeight.Bold;
        headerCellStyle.SetFont(headerFont);
        headerCellStyle.BorderBottom = BorderStyle.Double;

        var totalCellStyle = wb.CreateCellStyle();
        var totalFont      = wb.CreateFont();

        totalFont.Boldweight = (short)FontBoldWeight.Bold;
        totalCellStyle.SetFont(headerFont);
        totalCellStyle.BorderTop = BorderStyle.Double;

        var totalValueCellStyle = wb.CreateCellStyle();

        totalFont.Boldweight = (short)FontBoldWeight.Bold;
        totalValueCellStyle.SetFont(headerFont);
        totalValueCellStyle.BorderTop    = BorderStyle.Double;
        totalValueCellStyle.BorderBottom = BorderStyle.None;
        totalValueCellStyle.DataFormat   = hssfDataFormat.GetFormat("#,##0.00");

        var titleCellStyle = wb.CreateCellStyle();
        var titleFont      = wb.CreateFont();

        titleFont.Boldweight = (short)FontBoldWeight.Bold;
        titleFont.FontHeight = 400;
        titleCellStyle.SetFont(titleFont);

        var decimalFormat = wb.CreateCellStyle();

        decimalFormat.DataFormat = wb.CreateDataFormat().GetFormat("#.00");

        var integerformat = wb.CreateCellStyle();

        integerformat.DataFormat = wb.CreateDataFormat().GetFormat("#0");

        var cra = new CellRangeAddress(0, 1, 0, 4);

        sh.AddMergedRegion(cra);
        if (sh.GetRow(0) == null)
        {
            sh.CreateRow(0);
        }
        sh.GetRow(0).CreateCell(0);
        sh.GetRow(0).GetCell(0).SetCellValue(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Indicador_RecordsReportTitle"], indicadorName));
        sh.GetRow(0).GetCell(0).CellStyle = titleCellStyle;

        var dataFormatCustom = wb.CreateDataFormat();

        // Condiciones del filtro
        if (shCriteria.GetRow(1) == null)
        {
            shCriteria.CreateRow(1);
        }
        if (shCriteria.GetRow(2) == null)
        {
            shCriteria.CreateRow(2);
        }
        if (shCriteria.GetRow(3) == null)
        {
            shCriteria.CreateRow(3);
        }

        if (shCriteria.GetRow(1).GetCell(1) == null)
        {
            shCriteria.GetRow(1).CreateCell(1);
        }
        shCriteria.GetRow(1).GetCell(1).SetCellValue(dictionary["Item_Indicador_Field_Name"]);
        if (shCriteria.GetRow(1).GetCell(2) == null)
        {
            shCriteria.GetRow(1).CreateCell(2);
        }
        shCriteria.GetRow(1).GetCell(2).SetCellValue(indicadorName);


        if (shCriteria.GetRow(2).GetCell(1) == null)
        {
            shCriteria.GetRow(2).CreateCell(1);
        }
        shCriteria.GetRow(2).GetCell(1).SetCellValue(dictionary["Common_From"]);
        if (shCriteria.GetRow(2).GetCell(2) == null)
        {
            shCriteria.GetRow(2).CreateCell(2);
        }
        string fromValue = "-";

        if (dateFrom.HasValue)
        {
            fromValue = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", dateFrom.Value);
        }
        shCriteria.GetRow(2).GetCell(2).SetCellValue(fromValue);

        if (shCriteria.GetRow(3).GetCell(1) == null)
        {
            shCriteria.GetRow(3).CreateCell(1);
        }
        shCriteria.GetRow(3).GetCell(1).SetCellValue(dictionary["Common_To"]);
        if (shCriteria.GetRow(3).GetCell(2) == null)
        {
            shCriteria.GetRow(3).CreateCell(2);
        }
        string toValue = "-";

        if (dateTo.HasValue)
        {
            toValue = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", dateTo.Value);
        }

        shCriteria.GetRow(3).GetCell(2).SetCellValue(toValue);

        // Crear Cabecera
        var headers = new List <string>()
        {
            dictionary["Item_Indicador_TableRecords_Header_Status"].ToUpperInvariant(),
            dictionary["Item_Indicador_TableRecords_Header_Value"].ToUpperInvariant(),
            dictionary["Item_Indicador_TableRecords_Header_Date"].ToUpperInvariant(),
            dictionary["Item_Indicador_TableRecords_Header_Comments"].ToUpperInvariant(),
            dictionary["Item_Indicador_TableRecords_Header_Meta"].ToUpperInvariant(),
            dictionary["Item_Indicador_TableRecords_Header_Alarm"].ToUpperInvariant(),
            dictionary["Item_Indicador_TableRecords_Header_Responsible"].ToUpperInvariant()
        };

        int countColumns = 0;

        foreach (string headerLabel in headers)
        {
            if (sh.GetRow(3) == null)
            {
                sh.CreateRow(3);
            }

            if (sh.GetRow(3).GetCell(countColumns) == null)
            {
                sh.GetRow(3).CreateCell(countColumns);
            }
            sh.GetRow(3).GetCell(countColumns).SetCellValue(headerLabel);
            sh.GetRow(3).GetCell(countColumns).CellStyle = headerCellStyle;
            countColumns++;
        }

        int countRow = 4;

        if (dateFrom.HasValue)
        {
            registros = registros.Where(r => r.Date >= dateFrom).ToList();
        }

        if (dateTo.HasValue)
        {
            registros = registros.Where(r => r.Date <= dateTo).ToList();
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH1|ASC":
            registros = registros.OrderBy(d => d.Value).ToList();
            break;

        case "TH1|DESC":
            registros = registros.OrderByDescending(d => d.Value).ToList();
            break;

        case "TH2|ASC":
            registros = registros.OrderBy(d => d.Date).ToList();
            break;

        case "TH2|DESC":
            registros = registros.OrderByDescending(d => d.Date).ToList();
            break;

        case "TH4|ASC":
            registros = registros.OrderBy(d => d.Meta).ToList();
            break;

        case "TH4|DESC":
            registros = registros.OrderByDescending(d => d.Meta).ToList();
            break;

        case "TH5|ASC":
            registros = registros.OrderBy(d => d.Alarma).ToList();
            break;

        case "TH5|DESC":
            registros = registros.OrderByDescending(d => d.Alarma).ToList();
            break;

        case "TH6|ASC":
            registros = registros.OrderBy(d => d.Responsible.FullName).ToList();
            break;

        case "TH6|DESC":
            registros = registros.OrderByDescending(d => d.Responsible.FullName).ToList();
            break;
        }

        foreach (var registro in registros)
        {
            if (sh.GetRow(countRow) == null)
            {
                sh.CreateRow(countRow);
            }
            string metaText  = IndicadorRegistro.ComparerLabelSign(registro.MetaComparer, dictionary);
            string alarmText = IndicadorRegistro.ComparerLabelSign(registro.AlarmaComparer, dictionary);

            string statusLabel = dictionary["Item_Objetivo_StatusLabelWithoutMeta"];
            if (!string.IsNullOrEmpty(metaText))
            {
                metaText = string.Format(CultureInfo.InvariantCulture, "{0} {1:#,##0.00}", metaText, registro.Meta);
                if (metaText == "=" && registro.Value == registro.Meta)
                {
                    statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
                }
                else if (metaText == ">" && registro.Value > registro.Meta)
                {
                    statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
                }
                else if (metaText == ">=" && registro.Value >= registro.Meta)
                {
                    statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
                }
                else if (metaText == "<" && registro.Value < registro.Meta)
                {
                    statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
                }
                else if (metaText == "<=" && registro.Value <= registro.Meta)
                {
                    statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
                }
                else if (!string.IsNullOrEmpty(alarmText))
                {
                    if (alarmText == ">" && registro.Value > registro.Alarma)
                    {
                        statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                    }
                    else if (alarmText == ">=" && registro.Value >= registro.Alarma)
                    {
                        statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                    }
                    else if (alarmText == "<" && registro.Value < registro.Alarma)
                    {
                        statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                    }
                    else if (alarmText == "<=" && registro.Value <= registro.Alarma)
                    {
                        statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                    }
                    else
                    {
                        statusLabel = dictionary["Item_Objetivo_StatusLabelNoMeta"];
                    }
                }
                else
                {
                    statusLabel = dictionary["Item_Objetivo_StatusLabelNoMeta"];
                }
            }

            // Status
            if (sh.GetRow(countRow).GetCell(0) == null)
            {
                sh.GetRow(countRow).CreateCell(0);
            }
            sh.GetRow(countRow).GetCell(0).SetCellValue(statusLabel);

            // Value
            if (sh.GetRow(countRow).GetCell(1) == null)
            {
                sh.GetRow(countRow).CreateCell(1);
            }
            sh.GetRow(countRow).GetCell(1).SetCellType(CellType.Numeric);
            sh.GetRow(countRow).GetCell(1).CellStyle = moneyCellStyle;
            sh.GetRow(countRow).GetCell(1).SetCellValue(Convert.ToDouble(registro.Value));

            // Date
            if (sh.GetRow(countRow).GetCell(2) == null)
            {
                sh.GetRow(countRow).CreateCell(2);
            }
            sh.GetRow(countRow).GetCell(2).CellStyle.DataFormat = dataFormatCustom.GetFormat("dd/MM/yyyy");
            sh.GetRow(countRow).GetCell(2).SetCellValue(registro.Date);

            // Comments
            if (sh.GetRow(countRow).GetCell(3) == null)
            {
                sh.GetRow(countRow).CreateCell(3);
            }
            sh.GetRow(countRow).GetCell(3).SetCellValue(registro.Comments);

            // Meta
            if (sh.GetRow(countRow).GetCell(4) == null)
            {
                sh.GetRow(countRow).CreateCell(4);
            }
            sh.GetRow(countRow).GetCell(4).SetCellValue(metaText);

            // Alarm
            if (!registro.Alarma.HasValue)
            {
                alarmText = string.Empty;
            }
            else
            {
                alarmText = string.Format(CultureInfo.InvariantCulture, "{0} {1:#,##0.00}", alarmText, registro.Alarma);
            }

            if (sh.GetRow(countRow).GetCell(5) == null)
            {
                sh.GetRow(countRow).CreateCell(5);
            }
            sh.GetRow(countRow).GetCell(5).SetCellValue(alarmText);

            // Responsible
            if (sh.GetRow(countRow).GetCell(6) == null)
            {
                sh.GetRow(countRow).CreateCell(6);
            }
            sh.GetRow(countRow).GetCell(6).SetCellValue(registro.Responsible.FullName);

            countRow++;
        }

        sh.SetColumnWidth(0, 4000);
        sh.SetColumnWidth(1, 4000);
        sh.SetColumnWidth(2, 4000);
        sh.SetColumnWidth(3, 10000);
        sh.SetColumnWidth(4, 8400);
        sh.SetColumnWidth(5, 8400);
        sh.SetColumnWidth(6, 8400);

        if (!path.EndsWith("\\"))
        {
            path += "\\Temp\\";
        }
        else
        {
            path += "Temp\\";
        }

        using (var fs = new FileStream(string.Format("{0}{1}", path, fileName), FileMode.Create, FileAccess.Write))
        {
            wb.Write(fs);
        }

        res.SetSuccess(string.Format("/Temp/{0}", fileName));
        return(res);
    }
Esempio n. 11
0
    public static ActionResult PDF(int companyId, DateTime?dateFrom, DateTime?dateTo, string indicadorName, int indicadorId, string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var company = new Company(companyId);

        var registros = IndicadorRegistro.ByIndicadorId(indicadorId, companyId).ToList();

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }


        var formatedDescription = ToolsPdf.NormalizeFileName(indicadorName);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.xls",
            dictionary["Item_Indicador_RecordsReportTitle"],
            formatedDescription,
            DateTime.Now);

        fileName = fileName.Replace("%", "");

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = companyId,
            CompanyName = company.Name,
            Title       = string.Format(CultureInfo.InvariantCulture, "{0} {1}", dictionary["Item_Indicador_RecordsReportTitle"].ToUpperInvariant(), indicadorName)
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(220, 220, 220);

        string periode = string.Empty;

        if (dateFrom.HasValue && dateTo.HasValue)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"{2} {0:dd/MM/yyyy} {3} {1:dd/MM/yyyy}",
                dateFrom.Value,
                dateTo.Value,
                dictionary["Common_From"].ToLowerInvariant(),
                dictionary["Common_To"].ToLowerInvariant());
        }
        else if (dateFrom.HasValue && dateTo == null)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"{1}: {0:dd/MM/yyyy}",
                dateFrom.Value,
                dictionary["Common_From"]);
        }
        else if (dateFrom == null && dateTo.HasValue)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"{1}: {0:dd/MM/yyyy}",
                dateTo.Value,
                dictionary["Common_To"]);
        }

        if (string.IsNullOrEmpty(periode))
        {
            periode = dictionary["Common_PeriodAll"];
        }

        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        string typeText = string.Empty;

        criteriatable.SetWidths(new float[] { 25f, 250f });
        criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Common_Period"]));
        criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(periode));
        criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(typeText));
        pdfDoc.Add(criteriatable);

        var table = new iTSpdf.PdfPTable(7)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 15f, 10f, 15f, 15f, 20f, 20f, 30f });
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Value"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Alarm"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"]));

        // Aplicar filtro
        if (dateFrom.HasValue)
        {
            registros = registros.Where(r => r.Date >= dateFrom).ToList();
        }

        if (dateTo.HasValue)
        {
            registros = registros.Where(r => r.Date <= dateTo).ToList();
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH1|ASC":
            registros = registros.OrderBy(d => d.Value).ToList();
            break;

        case "TH1|DESC":
            registros = registros.OrderByDescending(d => d.Value).ToList();
            break;

        case "TH2|ASC":
            registros = registros.OrderBy(d => d.Date).ToList();
            break;

        case "TH2|DESC":
            registros = registros.OrderByDescending(d => d.Date).ToList();
            break;

        case "TH4|ASC":
            registros = registros.OrderBy(d => d.Meta).ToList();
            break;

        case "TH4|DESC":
            registros = registros.OrderByDescending(d => d.Meta).ToList();
            break;

        case "TH5|ASC":
            registros = registros.OrderBy(d => d.Alarma).ToList();
            break;

        case "TH5|DESC":
            registros = registros.OrderByDescending(d => d.Alarma).ToList();
            break;

        case "TH6|ASC":
            registros = registros.OrderBy(d => d.Responsible.FullName).ToList();
            break;

        case "TH6|DESC":
            registros = registros.OrderByDescending(d => d.Responsible.FullName).ToList();
            break;
        }

        int cont       = 0;
        var dataPoints = new List <PointData>();

        foreach (var registro in registros.OrderByDescending(r => r.Date))
        {
            cont++;
            string metaText  = IndicadorRegistro.ComparerLabelSign(registro.MetaComparer, dictionary);
            string alarmText = IndicadorRegistro.ComparerLabelSign(registro.AlarmaComparer, dictionary);
            int    color     = 0;

            string statusLabel = dictionary["Item_Objetivo_StatusLabelWithoutMeta"];
            if (metaText == "=" && registro.Value == registro.Meta)
            {
                color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
            }
            else if (metaText == ">" && registro.Value > registro.Meta)
            {
                color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
            }
            else if (metaText == ">=" && registro.Value >= registro.Meta)
            {
                color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
            }
            else if (metaText == "<" && registro.Value < registro.Meta)
            {
                color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
            }
            else if (metaText == "<=" && registro.Value <= registro.Meta)
            {
                color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"];
            }
            else if (!string.IsNullOrEmpty(alarmText))
            {
                if (alarmText == "=" && registro.Value == registro.Alarma)
                {
                    color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                }
                else if (alarmText == ">" && registro.Value > registro.Alarma)
                {
                    color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                }
                else if (alarmText == ">=" && registro.Value >= registro.Alarma)
                {
                    color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                }
                else if (alarmText == "<" && registro.Value < registro.Alarma)
                {
                    color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                }
                else if (alarmText == "<=" && registro.Value <= registro.Alarma)
                {
                    color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"];
                }
                else
                {
                    statusLabel = dictionary["Item_Objetivo_StatusLabelNoMeta"];
                    color       = 3;
                }
            }
            else
            {
                statusLabel = dictionary["Item_Objetivo_StatusLabelNoMeta"];
                color       = 3;
            }

            table.AddCell(ToolsPdf.DataCell(statusLabel, ToolsPdf.LayoutFonts.Times));

            metaText  = string.Format(CultureInfo.InvariantCulture, "{0} {1:#,##0.00}", metaText, registro.Meta);
            alarmText = string.Format(CultureInfo.InvariantCulture, "{0} {1:#,##0.00}", alarmText, registro.Alarma);
            table.AddCell(ToolsPdf.DataCellRight(string.Format(CultureInfo.InvariantCulture, "{0:#,##0.00}", registro.Value)));
            table.AddCell(ToolsPdf.DataCell(registro.Date));
            table.AddCell(ToolsPdf.DataCell(registro.Comments));
            table.AddCell(ToolsPdf.DataCell(metaText));
            table.AddCell(ToolsPdf.DataCell(alarmText));
            table.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName));

            dataPoints.Add(new PointData
            {
                Value  = registro.Value,
                Meta   = registro.Meta,
                Alarma = registro.Alarma,
                Date   = registro.Date,
                Status = color
            });
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = backgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = backgroundColor,
            Colspan         = 5
        });

        string graphName = string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, "graph.jpg");

        dataPoints = dataPoints.OrderBy(dp => dp.Date).ToList();
        using (var chart = new Chart())
        {
            chart.ChartAreas.Add(new ChartArea("Valor"));
            var series = new Series();
            chart.Width  = 800;
            chart.Height = 350;
            chart.Series.Add("Values");
            chart.Series["Values"].ChartType  = SeriesChartType.Column;
            chart.Series["Values"].YValueType = ChartValueType.Double;

            chart.Series.Add("Meta");
            chart.Series["Meta"].ChartType   = SeriesChartType.Line;
            chart.Series["Meta"].BorderWidth = 3;
            chart.Series["Meta"].BorderColor = DR.Color.Green;
            chart.Series["Meta"].YValueType  = ChartValueType.Double;

            chart.Series.Add("Alarma");
            chart.Series["Alarma"].ChartType   = SeriesChartType.Line;
            chart.Series["Alarma"].BorderWidth = 3;
            chart.Series["Alarma"].BorderColor = DR.Color.Pink;
            chart.Series["Alarma"].YValueType  = ChartValueType.Double;

            foreach (var dataPoint in dataPoints)
            {
                chart.Series["Values"].Points.AddXY(string.Format("{0:dd/MM/yyyy}", dataPoint.Date), dataPoint.Value);
                chart.Series["Meta"].Points.AddY(dataPoint.Meta);
                chart.Series["Alarma"].Points.AddY(dataPoint.Alarma ?? 0);
            }

            chart.Series["Values"].IsValueShownAsLabel = true;
            chart.Series["Values"].Font = new DR.Font("Arial", 8, DR.FontStyle.Bold);

            chart.Series["Values"].ChartArea = "Valor";
            chart.Series["Meta"].ChartArea   = "Valor";
            chart.Series["Alarma"].ChartArea = "Valor";

            chart.ChartAreas["Valor"].AxisX.LabelStyle.Font   = new DR.Font("Arial", 8);
            chart.ChartAreas["Valor"].AxisX.MajorGrid.Enabled = false;
            chart.ChartAreas["Valor"].AxisX.LabelStyle.Angle  = 75;
            chart.ChartAreas["Valor"].AxisY.LabelStyle.Font   = new DR.Font("Arial", 10);
            chart.ChartAreas["Valor"].RecalculateAxesScale();

            int cp = 0;
            foreach (var Point in chart.Series["Values"].Points)
            {
                switch (dataPoints[cp].Status)
                {
                default:
                case 0: Point.Color = DR.Color.DarkGray; break;

                case 1: Point.Color = DR.Color.Green; break;

                case 2: Point.Color = DR.Color.Red; break;

                case 3: Point.Color = DR.Color.Orange; break;
                }

                cp++;
            }

            chart.Series.Add(series);
            chart.SaveImage(graphName, ChartImageFormat.Jpeg);
        }

        var tif = Image.GetInstance(graphName);

        tif.ScalePercent(100);

        pdfDoc.Add(table);
        pdfDoc.NewPage();
        pdfDoc.Add(new iTS.Phrase("Grafico", ToolsPdf.LayoutFonts.Times));
        pdfDoc.Add(tif);

        var logoIssus = Image.GetInstance(string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path));

        logoIssus.ScalePercent(20f);
        logoIssus.SetAbsolutePosition(40f, 24f);
        pdfDoc.Add(logoIssus);

        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 12
0
    public static ActionResult PDF(string from, string to, string filter, int companyId)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var fromDate = Tools.DateFromTextYYYYMMDD(from);
        var toDate   = Tools.DateFromTextYYYYMMDD(to);

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_EquipmentList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_EquipmentListCosts"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        var titleCell = new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        };

        titleTable.AddCell(titleCell);

        var CI = filter.IndexOf("|CI") != -1;
        var CE = filter.IndexOf("|CE") != -1;
        var VI = filter.IndexOf("|VI") != -1;
        var VE = filter.IndexOf("|VE") != -1;
        var MI = filter.IndexOf("|MI") != -1;
        var ME = filter.IndexOf("|ME") != -1;
        var RI = filter.IndexOf("|RI") != -1;
        var RE = filter.IndexOf("|RE") != -1;
        var AC = filter.IndexOf("|AC") != -1;
        var IN = filter.IndexOf("|IN") != -1;

        var numberColumns = 2;

        numberColumns += CI ? 1 : 0;
        numberColumns += CE ? 1 : 0;
        numberColumns += VI ? 1 : 0;
        numberColumns += VE ? 1 : 0;
        numberColumns += MI ? 1 : 0;
        numberColumns += ME ? 1 : 0;
        numberColumns += RI ? 1 : 0;
        numberColumns += RE ? 1 : 0;

        var table = new iTSpdf.PdfPTable(numberColumns)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        var widths = new List <float>();

        widths.Add(20f + (10 - numberColumns) * 5);
        if (CI)
        {
            widths.Add(5f);
        }
        if (CE)
        {
            widths.Add(5f);
        }
        if (VI)
        {
            widths.Add(5f);
        }
        if (VE)
        {
            widths.Add(5f);
        }
        if (MI)
        {
            widths.Add(5f);
        }
        if (ME)
        {
            widths.Add(5f);
        }
        if (RI)
        {
            widths.Add(5f);
        }
        if (RE)
        {
            widths.Add(5f);
        }

        widths.Add(10f);

        table.SetWidths(widths.ToArray());

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Description"]));
        if (CI)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Calibration_Int"]));
        }
        if (CE)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Calibration_Ext"]));
        }
        if (VI)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Verification_Int"]));
        }
        if (VE)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Verification_Ext"]));
        }
        if (MI)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Maintenance_Int"]));
        }
        if (ME)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Maintenance_Ext"]));
        }
        if (RI)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Repair_Int"]));
        }
        if (RE)
        {
            table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_FilterLabel_Repair_Ext"]));
        }
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Total"]));

        int cont = 0;
        var data = new List <EquipmentCost>();

        decimal totalCI = 0;
        decimal totalCE = 0;
        decimal totalVI = 0;
        decimal totalVE = 0;
        decimal totalMI = 0;
        decimal totalME = 0;
        decimal totalRI = 0;
        decimal totalRE = 0;

        using (var cmd = new SqlCommand("Equipment_GetCosts2"))
        {
            using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString))
            {
                cmd.Connection  = cnn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(DataParameter.Input("@From", fromDate));
                cmd.Parameters.Add(DataParameter.Input("@to", toDate));
                cmd.Parameters.Add(DataParameter.Input("@CompanyId", company.Id));
                try
                {
                    cmd.Connection.Open();
                    using (var rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            var newEquipmentCost = new EquipmentCost
                            {
                                Id          = rdr.GetInt64(8),
                                Description = rdr.GetString(9),
                                Active      = rdr.GetBoolean(10),
                                CI          = CI ? rdr.GetDecimal(0) : 0,
                                CE          = CE ? rdr.GetDecimal(1) : 0,
                                VI          = VI ? rdr.GetDecimal(2) : 0,
                                VE          = VE ? rdr.GetDecimal(3) : 0,
                                MI          = MI ? rdr.GetDecimal(4) : 0,
                                ME          = ME ? rdr.GetDecimal(5) : 0,
                                RI          = RI ? rdr.GetDecimal(6) : 0,
                                RE          = RE ? rdr.GetDecimal(7) : 0
                            };

                            totalCI += newEquipmentCost.CI;
                            totalCE += newEquipmentCost.CE;
                            totalVI += newEquipmentCost.VI;
                            totalVE += newEquipmentCost.VE;
                            totalMI += newEquipmentCost.MI;
                            totalME += newEquipmentCost.ME;
                            totalRI += newEquipmentCost.RI;
                            totalRE += newEquipmentCost.RE;

                            data.Add(newEquipmentCost);
                        }
                    }
                }
                finally
                {
                    if (cmd.Connection.State != ConnectionState.Closed)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }



        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 8f, 50f });

        string periodText    = string.Empty;
        string operativaText = string.Empty;

        if (string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periodText = dictionary["Common_PeriodAll"];
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periodText = string.Format(
                @"{0} {1:dd/MM/yyyy} {2} {3:dd/MM/yyyy}",
                dictionary["Common_From"],
                Tools.DateFromTextYYYYMMDD(from),
                dictionary["Common_To"],
                Tools.DateFromTextYYYYMMDD(to));
        }
        else if (!string.IsNullOrEmpty(from))
        {
            periodText = string.Format(
                @"{0} {1:dd/MM/yyyy}",
                dictionary["Common_From"],
                Tools.DateFromTextYYYYMMDD(from));
        }
        else
        {
            periodText = string.Format(
                @"{0} {1:dd/MM/yyyy}",
                dictionary["Common_To"],
                Tools.DateFromTextYYYYMMDD(to));
        }

        bool first = true;

        if (CI)
        {
            first         = false;
            operativaText = dictionary["Item_Equipment_FilterLabel_Calibration_Int"];
        }
        if (CE)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_FilterLabel_Calibration_Ext"];
        }
        if (VI)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_FilterLabel_Verification_Int"];
        }
        if (VE)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_FilterLabel_Verification_Ext"];
        }
        if (MI)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_FilterLabel_Maintenance_Int"];
        }
        if (ME)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_FilterLabel_Maintenance_Ext"];
        }
        if (RI)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_FilterLabel_Repair_Int"];
        }
        if (RE)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_FilterLabel_Repair_Ext"];
        }

        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByOperation"], operativaText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByPeriod"], periodText);

        bool    pair   = false;
        decimal total  = 0;
        int     border = 0;

        foreach (EquipmentCost equipment in data)
        {
            if (equipment.Total == 0)
            {
                continue;
            }

            total += equipment.Total;

            var lineBackground = pair ? rowEven : rowPair;

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Description, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = lineBackground,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            if (CI)
            {
                string CIText = string.Format("{0:#,##0.00}", equipment.CI);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(CIText, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            if (CE)
            {
                string CEText = string.Format("{0:#,##0.00}", equipment.CE);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(CEText, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            if (VI)
            {
                string VIText = string.Format("{0:#,##0.00}", equipment.VI);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(VIText, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            if (VE)
            {
                string VEText = string.Format("{0:#,##0.00}", equipment.VE);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(VEText, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            if (MI)
            {
                string MIText = string.Format("{0:#,##0.00}", equipment.MI);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(MIText, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            if (ME)
            {
                string METext = string.Format("{0:#,##0.00}", equipment.ME);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(METext, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            if (RI)
            {
                string RIText = string.Format("{0:#,##0.00}", equipment.RI);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(RIText, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            if (RE)
            {
                string REText = string.Format("{0:#,##0.00}", equipment.RE);
                table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(REText, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    HorizontalAlignment = 2
                });
            }

            string TotalText = string.Format("{0:#,##0.00}", equipment.Total);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(TotalText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = lineBackground,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });

            cont++;
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f
        });

        /*table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
         * {
         *  Border = iTS.Rectangle.TOP_BORDER,
         *  BackgroundColor = rowEven,
         *  Padding = 6f,
         *  PaddingTop = 4f,
         *  HorizontalAlignment = 2
         * });*/

        if (CI)
        {
            string totalTextCI = string.Format("{0:#,##0.00}", totalCI);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextCI, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        if (CE)
        {
            string totalTextCE = string.Format("{0:#,##0.00}", totalCE);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextCE, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        if (VI)
        {
            string totalTextVI = string.Format("{0:#,##0.00}", totalVI);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextVI, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        if (VE)
        {
            string totalTextVE = string.Format("{0:#,##0.00}", totalVE);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextVE, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        if (MI)
        {
            string totalTextMI = string.Format("{0:#,##0.00}", totalMI);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextMI, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        if (ME)
        {
            string totalTextME = string.Format("{0:#,##0.00}", totalME);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextME, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        if (RI)
        {
            string totalTextRI = string.Format("{0:#,##0.00}", totalRI);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextRI, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        if (RE)
        {
            string totalTextRE = string.Format("{0:#,##0.00}", totalRE);
            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalTextRE, ToolsPdf.LayoutFonts.Times))
            {
                Border              = iTS.Rectangle.TOP_BORDER,
                BackgroundColor     = rowEven,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = 2
            });
        }

        string totalText = string.Format("{0:#,##0.00}", total);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalText, ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 2
        });

        pdfDoc.Add(criteriatable);
        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 13
0
    public static ActionResult PDF(long equipmentId, int companyId, long applicationUserId)
    {
        var res        = ActionResult.NoAction;
        var user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var equipment  = Equipment.ById(equipmentId, companyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(equipment.Description);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Equipment"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.LETTER, 50, 50, 80, 50);


        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        var company = new Company(equipment.CompanyId);

        var pageEventHandler = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_CreatedBy"], user.UserName),
            CompanyId   = equipment.CompanyId,
            CompanyName = company.Name,
            Title       = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Equipment"], equipment.Description)
        };

        writer.PageEvent = pageEventHandler;

        // Font styles
        var headerFont = new iTS.Font(iTSpdf.BaseFont.CreateFont(iTSpdf.BaseFont.HELVETICA, iTSpdf.BaseFont.CP1252, false), 22, iTS.Font.BOLD, iTS.BaseColor.BLACK);
        var labelFont  = new iTS.Font(iTSpdf.BaseFont.CreateFont(iTSpdf.BaseFont.HELVETICA, iTSpdf.BaseFont.CP1252, false), 14, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
        var dataFont   = new iTS.Font(iTSpdf.BaseFont.CreateFont(iTSpdf.BaseFont.HELVETICA, iTSpdf.BaseFont.CP1252, false), 14, iTS.Font.BOLD, iTS.BaseColor.BLACK);

        pdfDoc.Open();

        // Main data
        pdfDoc.Add(new Phrase(dictionary["Item_Equipment_Tab_Basic"], headerFont));
        var mainDataTable = new iTSpdf.PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        mainDataTable.SetWidths(new float[] { 15f, 30f, 15f, 30f });

        var mainC1 = new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Equipment_Field_Code_Label"], labelFont));
        var mainC2 = new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Equipment_Field_Description_Label"], labelFont));
        var mainC3 = new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Equipment_Field_TradeMark_Label"], labelFont));
        var mainC4 = new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Equipment_Field_Model_Label"], labelFont));

        var mainD1 = new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Code, dataFont));
        var mainD2 = new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Description, dataFont));
        var mainD3 = new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Trademark, dataFont));
        var mainD4 = new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Model, dataFont));

        mainC1.Border = 0; mainD1.Border = 0;
        mainC2.Border = 0; mainD2.Border = 0;
        mainC3.Border = 0; mainD3.Border = 0;
        mainC4.Border = 0; mainD4.Border = 0;

        mainDataTable.AddCell(mainC1); mainDataTable.AddCell(mainD1);
        mainDataTable.AddCell(mainC2); mainDataTable.AddCell(mainD2);
        mainDataTable.AddCell(mainC3); mainDataTable.AddCell(mainD3);
        mainDataTable.AddCell(mainC4); mainDataTable.AddCell(mainD4);

        pdfDoc.Add(mainDataTable);

        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        long actionId   = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company    = new Company(companyId);
        var  res        = ActionResult.NoAction;
        var  user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  action     = IncidentAction.ById(actionId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(action.Description);

        formatedDescription = formatedDescription.Replace(@"\", "/");

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentAction"],
            formatedDescription,
            DateTime.Now);

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;

        if (action.ActionType == 1)
        {
            type = dictionary["Item_IncidentAction_Type1"];
        }
        if (action.ActionType == 2)
        {
            type = dictionary["Item_IncidentAction_Type2"];
        }
        if (action.ActionType == 3)
        {
            type = dictionary["Item_IncidentAction_Type3"];
        }

        if (action.Origin == 1)
        {
            origin = dictionary["Item_IncidentAction_Origin1"];
        }
        if (action.Origin == 2)
        {
            origin = dictionary["Item_IncidentAction_Origin2"];
        }
        if (action.Origin == 3)
        {
            if (action.IncidentId.HasValue)
            {
                var incident = Incident.GetById(action.IncidentId.Value, action.CompanyId);
                origin = string.Format(
                    CultureInfo.InvariantCulture,
                    @"{0}: {1}",
                    dictionary["Item_Incident"],
                    incident.Description);
            }
        }

        if (action.Origin == 4)
        {
            if (action.BusinessRiskId.HasValue)
            {
                if (action.BusinessRiskId > Constant.DefaultId)
                {
                    var businessRisk = BusinessRisk.ById(action.CompanyId, action.BusinessRiskId.Value);
                    origin      = businessRisk.Description;
                    originSufix = " (" + dictionary["Item_BusinessRisk"] + ")";
                }
            }
        }
        if (action.Origin == 5)
        {
            if (action.ObjetivoId.HasValue)
            {
                if (action.ObjetivoId > Constant.DefaultId)
                {
                    var objetivo = Objetivo.ById(Convert.ToInt32(action.ObjetivoId.Value), action.CompanyId);
                    origin      = objetivo.Name;
                    originSufix = " (" + dictionary["Item_Objetivo"] + ")";
                }
            }
        }
        if (action.Origin == 6)
        {
            if (action.Oportunity.Id > Constant.DefaultId)
            {
                var oportunidad = Oportunity.ById(Convert.ToInt32(action.Oportunity.Id), action.CompanyId);
                origin      = oportunidad.Description;
                originSufix = " (" + dictionary["Item_Oportunity"] + ")";
            }
        }
        else
        {
            switch (action.ReporterType)
            {
            case 1:
                reporterType = dictionary["Item_IncidentAction_ReporterType1"];
                if (action.Department != null && action.Department.Id > 0)
                {
                    var department = Department.ById(action.Department.Id, action.CompanyId);
                    reporter = department.Description;
                }
                break;

            case 2:
                reporterType = dictionary["Item_IncidentAction_ReporterType2"];
                if (action.Provider != null && action.Provider.Id > 0)
                {
                    var provider = Provider.ById(action.Provider.Id, action.CompanyId);
                    reporter = provider.Description;
                }
                break;

            case 3:
                reporterType = dictionary["Item_IncidentAction_ReporterType3"];
                if (action.Customer != null && action.Customer.Id > 0)
                {
                    var customer = Customer.ById(action.Customer.Id, action.CompanyId);
                    reporter = customer.Description;
                }
                break;

            default:
                break;
            }
        }

        string status   = string.Empty;
        var    document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);
        var    writer   = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = action.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentAction"].ToUpperInvariant()
        };

        document.Open();
        var styles = new iTextSharp.text.html.simpleparser.StyleSheet();
        var hw     = new iTextSharp.text.html.simpleparser.HTMLWorker(document);

        var widths = new float[] { 15f, 30f, 15f, 30f };
        var table  = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(widths);
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;

        var alignLeft  = Element.ALIGN_LEFT;
        var alignRight = Element.ALIGN_RIGHT;

        var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY);
        var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK);

        // Descripción
        table.AddCell(LabelCell(dictionary["Item_IncidentAction"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(action.Number.ToString() + " - " + action.Description, ToolsPdf.BorderNone, alignLeft, 3));

        // Tipo
        table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Type"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(type, ToolsPdf.BorderNone, alignLeft, 1));

        // Origen
        table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Origin"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(origin + originSufix, ToolsPdf.BorderNone, alignLeft, 3));

        // Reportador
        if (action.Origin != 4 && action.Origin != 5 && !string.IsNullOrEmpty(reporter))
        {
            table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER));
            table.AddCell(ValueCell(reporterType + " (" + reporter + ")", ToolsPdf.BorderNone, alignLeft, 3));
        }

        // WhatHappend
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
        table.AddCell(BlankRow());
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

        // Causes
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
        table.AddCell(BlankRow());
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.CausesBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.CausesOn), borderBR, alignRight, 2));

        // Actions
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
        table.AddCell(BlankRow());
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.ActionsBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], action.ActionsOn), borderBR, alignRight, 2));

        // Monitoring
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4));

        // Close
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], action.ClosedBy.FullName), borderTBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], action.ClosedOn), borderTBR, alignRight, 2));

        // Notes
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4));

        document.Add(table);

        // Costes
        var costs = IncidentActionCost.GetByIncidentActionId(actionId, companyId);

        if (costs.Count > 0)
        {
            var times           = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK);
            var fontSummary     = new Font(arial, 9, Font.BOLD, BaseColor.BLACK);
            var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK);

            // @alex: hay que crear la tabla con 6 columnas en lugar de 5
            //var tableCosts = new PdfPTable(5)
            var tableCosts = new PdfPTable(6)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 1,
                SpacingBefore       = 20f,
                SpacingAfter        = 30f
            };

            // @alex: se añade una nueva columna de 10f para la fecha
            //tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f });
            tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 10f, 20f });

            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
            // @alex: se añade una nueva cabecera
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Date"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

            decimal total       = 0;
            decimal totalAccion = 0;
            int     cont        = 0;
            int     contAccion  = 0;

            // Acciones
            foreach (var cost in costs.Where(c => c.Active == true))
            {
                tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));

                // @alex: se añade la columna en la misma posición que en el listado de la ficha
                tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Date, times));

                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                total      += cost.Amount * cost.Quantity;
                totalAccion = cost.Amount * cost.Quantity;
                cont++;
                contAccion++;
            }

            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                           CultureInfo.InvariantCulture,
                                                           @"{0} {2}: {1}",
                                                           dictionary["Common_RegisterCount"],
                                                           contAccion,
                                                           dictionary["Item_IncidentAction"]), times))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 3//@ alex: al haber una columna más el colspan crece de 2 a 3
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), times))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT,
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 1
            });


            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();
            document.Add(tableCosts);
        }

        document.Close();

        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Esempio n. 15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var learningId = Convert.ToInt32(Request.QueryString["id"]);
        var companyId = Convert.ToInt32(Request.QueryString["companyId"]);
        var company = new Company(companyId);
        var res = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary<string, string>;
        var learning = new Learning(learningId, companyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(learning.Description);

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Learning"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;
        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);

        var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId = learning.CompanyId,
            CompanyName = company.Name,
            Title = dictionary["Item_Learning"]
        };

        writer.PageEvent = pageEventHandler;

        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;

        document.Open();

        #region Dades bàsiques
        // Ficha pincipal
        var table = new PdfPTable(6)
        {
            WidthPercentage = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 30f, 30f, 30f, 30f, 30f });

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Course"]));
        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Description, descriptionFont))
        {
            Border = 0,
            BackgroundColor = new iTS.BaseColor(255, 255, 255),
            Padding = 6f,
            PaddingTop = 4f,
            HorizontalAlignment = Rectangle.ALIGN_LEFT,
            Colspan = 5
        });

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EstimatedDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.DateEstimated, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Hours"]));
        table.AddCell(ToolsPdf.DataCell(learning.Hours, descriptionFont));

        string statusText = string.Empty;
        switch (learning.Status)
        {
            case 1: statusText = dictionary["Item_Learning_Status_Started"]; break;
            case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break;
            case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break;
            default: statusText = dictionary["Item_Learning_Status_InProgress"]; break;
        }

        table.AddCell(TitleLabel(dictionary["Item_Learning_ListHeader_Status"]));
        table.AddCell(ToolsPdf.DataCell(statusText, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_StartDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.RealStart, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EndDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.RealFinish, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Amount"]));
        table.AddCell(ToolsPdf.DataCellMoney(learning.Amount, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Coach"]));
        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Master, descriptionFont))
        {
            Border = 0,
            BackgroundColor = new iTS.BaseColor(255, 255, 255),
            Padding = 6f,
            PaddingTop = 4f,
            HorizontalAlignment = Rectangle.ALIGN_LEFT,
            Colspan = 5
        });

        // Objective
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_Objetive"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Objective, borderSides, Rectangle.ALIGN_LEFT, 6));

        // Methodology
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Methodology"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Methodology, borderSides, Rectangle.ALIGN_LEFT, 6));

        // Notes
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Notes, borderSides, Rectangle.ALIGN_LEFT, 6));

        document.Add(table);
        #endregion

        #region Asistentes
        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair = new iTS.BaseColor(255, 255, 255);
        var rowEven = new iTS.BaseColor(240, 240, 240);
        var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        document.SetPageSize(PageSize.A4.Rotate());
        document.NewPage();

        var tableAssistants = new iTSpdf.PdfPTable(3)
        {
            WidthPercentage = 100,
            HorizontalAlignment = 1,
            SpacingBefore = 20f
        };

        tableAssistants.SetWidths(new float[] { 90f, 20f, 20f });
        tableAssistants.AddCell(new PdfPCell(new Phrase(learning.Description, descriptionFont))
        {
            Colspan = 5,
            Border = Rectangle.NO_BORDER,
            PaddingTop = 20f,
            PaddingBottom = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistants"]));
        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Done"]));
        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Evaluated"]));

        int cont = 0;
        bool pair = false;
        var times = new iTS.Font(arial, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
        var timesBold = new iTS.Font(arial, 8, iTS.Font.BOLD, iTS.BaseColor.BLACK);
        learning.ObtainAssistance();
        foreach (var assistance in learning.Assistance)
        {
            int border = 0;
            var lineBackground = pair ? rowEven : rowPair;

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(assistance.Employee.FullName, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });

            string completedText = string.Empty;
            if (assistance.Completed.HasValue)
            {
                completedText = assistance.Completed.Value ? dictionary["Common_Yes"] : dictionary["Common_No"];
            }

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(completedText, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });

            string successText = string.Empty;
            if (assistance.Success.HasValue)
            {
                successText = assistance.Success.Value ? dictionary["Common_Yes"] : dictionary["Common_No"];
            }

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(successText, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });
            cont++;
        }

        // TotalRow
        if(learning.Assistance.Count == 0)
        {
            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_LearningList_NoAssistants"], descriptionFont))
            {
                Border = iTS.Rectangle.TOP_BORDER,
                BackgroundColor = rowEven,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell,
                Colspan = 3,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });
        }

        tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont), times))
        {
            Border = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding = ToolsPdf.PaddingTableCell,
            PaddingTop = ToolsPdf.PaddingTopTableCell,
            Colspan = 3
        });

        document.Add(tableAssistants);
        #endregion

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Esempio n. 16
0
    public static ActionResult PDF(
        int companyId,
        string from,
        string to,
        bool statusIdnetified,
        bool statusAnalyzed,
        bool statusInProgress,
        bool statusClose,
        int origin,
        int departmentId,
        int providerId,
        int customerId,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);
        var fileName            = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        // ------------ FONTS
        var awesomeFont     = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        criteriaFont = new iTS.Font(arial, 10, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
        var titleFont  = new iTS.Font(arial, 18, iTS.Font.BOLD, iTS.BaseColor.BLACK);
        var symbolFont = new iTS.Font(awesomeFont, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        var fontAwesomeIcon = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        fontAwe = new Font(fontAwesomeIcon, 10);
        // -------------------

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), titleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        var borderNone = iTS.Rectangle.NO_BORDER;

        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 8f, 50f });

        #region texts

        var criteriaOrigin = dictionary["Item_Incident_Origin0"];
        if (origin == 1)
        {
            if (departmentId > 0)
            {
                var department = Department.ById(departmentId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin1"], department.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin1"], dictionary["Common_All_Male_Plural"]);
            }
        }
        if (origin == 2)
        {
            if (providerId > 0)
            {
                var provider = Provider.ById(providerId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin2"], provider.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin2"], dictionary["Common_All_Male_Plural"]);
            }
        }
        if (origin == 3)
        {
            if (customerId > 0)
            {
                var customer = Customer.ById(customerId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin3"], customer.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin3"], dictionary["Common_All_Male_Plural"]);
            }
        }

        var periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_Incident_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_Incident_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " " + to;
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        var typetext  = string.Empty;
        var firstType = false;

        var statusText  = string.Empty;
        var firstStatus = true;
        if (statusIdnetified)
        {
            firstStatus = false;
            statusText += dictionary["Item_IndicentAction_Status1"];
        }
        if (statusAnalyzed)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status2"];
            firstStatus = false;
        }
        if (statusInProgress)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status3"];
            firstType   = false;
        }
        if (statusClose)
        {
            if (!firstType)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status4"];
            firstType   = false;
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode);
        if (!string.IsNullOrEmpty(filterText))
        //{
        //    ToolsPdf.AddCriteria(criteriatable, string.Empty, string.Empty);
        //}
        //else
        {
            ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText);
        }

        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Origin"], criteriaOrigin);
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(8)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 5f, 35f, 10f, 10f, 20f, 8f, 10f, 10f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Label_Number"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Open"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_ActionNumber"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Cost"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Close"]));

        int     cont      = 0;
        decimal totalCost = 0;
        var     data      = HttpContext.Current.Session["IncidentFilterData"] as List <IncidentFilterItem>;
        bool    pair      = false;

        foreach (IncidentFilterItem item in data)
        {
            var originValue = string.Empty;
            if (!string.IsNullOrEmpty(item.Customer.Description))
            {
                originValue = item.Customer.Description;
            }
            if (!string.IsNullOrEmpty(item.Provider.Description))
            {
                originValue = item.Provider.Description;
            }
            if (!string.IsNullOrEmpty(item.Department.Description))
            {
                originValue = item.Department.Description;
            }

            item.OriginText = originValue;
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.Open).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.Open).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.OriginText).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.OriginText).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.Action.Description).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Action.Description).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.Amount).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.Amount).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.Close).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.Close).ToList();
            break;
        }

        foreach (var incidentFilter in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                var match = incidentFilter.Description;
                match += "|" + incidentFilter.Code;
                match += "|" + incidentFilter.Customer.Description;
                match += "|" + incidentFilter.Provider.Description;
                match += "|" + incidentFilter.Department.Description;


                if (match.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    continue;
                }
            }

            cont++;
            totalCost += incidentFilter.Amount;
            var incident = Incident.GetById(incidentFilter.Id, companyId);
            var action   = IncidentAction.ByIncidentId(incident.Id, companyId);

            var lineBackground = pair ? rowEven : rowPair;
            // pair = !pair;

            var statustext = string.Empty;
            switch (incidentFilter.Status)
            {
            case 1: statustext = dictionary["Item_IndicentAction_Status1"]; break;

            case 2: statustext = dictionary["Item_IndicentAction_Status2"]; break;

            case 3: statustext = dictionary["Item_IndicentAction_Status3"]; break;

            case 4: statustext = dictionary["Item_IndicentAction_Status4"]; break;

            default: statusText = string.Empty; break;
            }

            var actionDescription = string.Empty;
            if (!string.IsNullOrEmpty(action.Description))
            {
                actionDescription = dictionary["Common_Yes"];
            }

            var originText = string.Empty;
            switch (incidentFilter.Origin)
            {
            case 1: originText = dictionary["Item_IncidentAction_Origin1"]; break;

            case 2: originText = dictionary["Item_IncidentAction_Origin2"]; break;

            case 3: originText = dictionary["Item_IncidentAction_Origin3"]; break;

            case 4: originText = dictionary["Item_IncidentAction_Origin4"]; break;

            default: originText = string.Empty; break;
            }

            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Code, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(incidentFilter.Description, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Open, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(statustext, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(incidentFilter.OriginText, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(actionDescription, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellMoney(incidentFilter.Amount, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Close, ToolsPdf.LayoutFonts.Times));
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 2
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 17
0
    public static ActionResult Excel(
        long equipmentId,
        int companyId,
        bool calibrationInternal,
        bool calibrationExternal,
        bool verificationInternal,
        bool verificationExternal,
        bool maintenanceInternal,
        bool maintenanceExternal,
        bool repairInternal,
        bool repairExternal,
        DateTime?dateFrom,
        DateTime?dateTo,
        string listOrder)
    {
        var    res        = ActionResult.NoAction;
        var    user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var    dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    equipment  = Equipment.ById(equipmentId, companyId);
        var    data       = HttpContext.Current.Session["EquipmentRecordsFilter"] as List <EquipmentRecord>;
        string path       = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(equipment.Description);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.xls",
            dictionary["Item_Equipment"],
            formatedDescription,
            DateTime.Now);

        var wb         = HSSFWorkbook.Create(InternalWorkbook.CreateWorkbook());
        var sh         = (HSSFSheet)wb.CreateSheet(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Equipment"], dictionary["Item_Equipment_Tab_Records"]));
        var shCriteria = (HSSFSheet)wb.CreateSheet(dictionary["Common_SearchCriteria"]);

        var moneyCellStyle = wb.CreateCellStyle();
        var hssfDataFormat = wb.CreateDataFormat();

        moneyCellStyle.DataFormat = hssfDataFormat.GetFormat("#,##0.00");

        var headerCellStyle = wb.CreateCellStyle();
        var headerFont      = wb.CreateFont();

        headerFont.Boldweight = (short)FontBoldWeight.Bold;
        headerCellStyle.SetFont(headerFont);
        headerCellStyle.BorderBottom = BorderStyle.Double;

        var totalCellStyle = wb.CreateCellStyle();
        var totalFont      = wb.CreateFont();

        totalFont.Boldweight = (short)FontBoldWeight.Bold;
        totalCellStyle.SetFont(headerFont);
        totalCellStyle.BorderTop = BorderStyle.Double;

        var totalValueCellStyle = wb.CreateCellStyle();

        totalFont.Boldweight = (short)FontBoldWeight.Bold;
        totalValueCellStyle.SetFont(headerFont);
        totalValueCellStyle.BorderTop    = BorderStyle.Double;
        totalValueCellStyle.BorderBottom = BorderStyle.None;
        totalValueCellStyle.DataFormat   = hssfDataFormat.GetFormat("#,##0.00");

        var titleCellStyle = wb.CreateCellStyle();
        var titleFont      = wb.CreateFont();

        titleFont.Boldweight = (short)FontBoldWeight.Bold;
        titleFont.FontHeight = 400;
        titleCellStyle.SetFont(titleFont);

        var decimalFormat = wb.CreateCellStyle();

        decimalFormat.DataFormat = wb.CreateDataFormat().GetFormat("#.00");

        var integerformat = wb.CreateCellStyle();

        integerformat.DataFormat = wb.CreateDataFormat().GetFormat("#0");

        var cra = new CellRangeAddress(0, 1, 0, 4);

        sh.AddMergedRegion(cra);
        if (sh.GetRow(0) == null)
        {
            sh.CreateRow(0);
        }
        sh.GetRow(0).CreateCell(0);
        sh.GetRow(0).GetCell(0).SetCellValue(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Equipment"], dictionary["Item_Equipment_Tab_Records"]));
        sh.GetRow(0).GetCell(0).CellStyle = titleCellStyle;

        var dataFormatCustom = wb.CreateDataFormat();

        // Condiciones del filtro
        if (shCriteria.GetRow(1) == null)
        {
            shCriteria.CreateRow(1);
        }
        if (shCriteria.GetRow(2) == null)
        {
            shCriteria.CreateRow(2);
        }
        if (shCriteria.GetRow(3) == null)
        {
            shCriteria.CreateRow(3);
        }
        if (shCriteria.GetRow(4) == null)
        {
            shCriteria.CreateRow(4);
        }
        if (shCriteria.GetRow(5) == null)
        {
            shCriteria.CreateRow(5);
        }

        if (shCriteria.GetRow(1).GetCell(1) == null)
        {
            shCriteria.GetRow(1).CreateCell(1);
        }
        shCriteria.GetRow(1).GetCell(1).SetCellValue(dictionary["Calibration-Int"]);
        if (shCriteria.GetRow(1).GetCell(3) == null)
        {
            shCriteria.GetRow(1).CreateCell(3);
        }
        shCriteria.GetRow(1).GetCell(3).SetCellValue(calibrationInternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(1).GetCell(4) == null)
        {
            shCriteria.GetRow(1).CreateCell(4);
        }
        shCriteria.GetRow(1).GetCell(4).SetCellValue(dictionary["Calibration-Ext"]);
        if (shCriteria.GetRow(1).GetCell(6) == null)
        {
            shCriteria.GetRow(1).CreateCell(6);
        }
        shCriteria.GetRow(1).GetCell(6).SetCellValue(calibrationInternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(2).GetCell(1) == null)
        {
            shCriteria.GetRow(2).CreateCell(1);
        }
        shCriteria.GetRow(2).GetCell(1).SetCellValue(dictionary["Verification-Int"]);
        if (shCriteria.GetRow(2).GetCell(3) == null)
        {
            shCriteria.GetRow(2).CreateCell(3);
        }
        shCriteria.GetRow(2).GetCell(3).SetCellValue(verificationInternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(2).GetCell(4) == null)
        {
            shCriteria.GetRow(2).CreateCell(4);
        }
        shCriteria.GetRow(2).GetCell(4).SetCellValue(dictionary["Verification-Ext"]);
        if (shCriteria.GetRow(2).GetCell(6) == null)
        {
            shCriteria.GetRow(2).CreateCell(6);
        }
        shCriteria.GetRow(2).GetCell(6).SetCellValue(verificationExternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(3).GetCell(1) == null)
        {
            shCriteria.GetRow(3).CreateCell(1);
        }
        shCriteria.GetRow(3).GetCell(1).SetCellValue(dictionary["Item_Equipment_FilterLabel_MaintenanceInternal"]);
        if (shCriteria.GetRow(3).GetCell(3) == null)
        {
            shCriteria.GetRow(3).CreateCell(3);
        }
        shCriteria.GetRow(3).GetCell(3).SetCellValue(maintenanceInternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(3).GetCell(4) == null)
        {
            shCriteria.GetRow(3).CreateCell(4);
        }
        shCriteria.GetRow(3).GetCell(4).SetCellValue(dictionary["Item_Equipment_FilterLabel_MaintenanceExternal"]);
        if (shCriteria.GetRow(3).GetCell(6) == null)
        {
            shCriteria.GetRow(3).CreateCell(6);
        }
        shCriteria.GetRow(3).GetCell(6).SetCellValue(maintenanceInternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(4).GetCell(1) == null)
        {
            shCriteria.GetRow(4).CreateCell(1);
        }
        shCriteria.GetRow(4).GetCell(1).SetCellValue(dictionary["Item_Equipment_FilterLabel_RepairInternal"]);
        if (shCriteria.GetRow(4).GetCell(3) == null)
        {
            shCriteria.GetRow(4).CreateCell(3);
        }
        shCriteria.GetRow(4).GetCell(3).SetCellValue(repairInternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(4).GetCell(4) == null)
        {
            shCriteria.GetRow(4).CreateCell(4);
        }
        shCriteria.GetRow(4).GetCell(4).SetCellValue(dictionary["Item_Equipment_FilterLabel_RepairExternal"]);
        if (shCriteria.GetRow(4).GetCell(6) == null)
        {
            shCriteria.GetRow(4).CreateCell(6);
        }
        shCriteria.GetRow(4).GetCell(6).SetCellValue(repairExternal ? dictionary["Common_Yes"] : dictionary["Common_No"]);

        if (shCriteria.GetRow(5).GetCell(1) == null)
        {
            shCriteria.GetRow(5).CreateCell(1);
        }
        shCriteria.GetRow(5).GetCell(1).SetCellValue(dictionary["Common_From"]);
        if (shCriteria.GetRow(5).GetCell(3) == null)
        {
            shCriteria.GetRow(5).CreateCell(3);
        }
        string fromValue = "-";

        if (dateFrom.HasValue)
        {
            fromValue = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", dateFrom.Value);
        }
        shCriteria.GetRow(5).GetCell(3).SetCellValue(fromValue);

        if (shCriteria.GetRow(5).GetCell(4) == null)
        {
            shCriteria.GetRow(5).CreateCell(4);
        }
        shCriteria.GetRow(5).GetCell(4).SetCellValue("Hasta");
        if (shCriteria.GetRow(5).GetCell(6) == null)
        {
            shCriteria.GetRow(5).CreateCell(6);
        }
        string toValue = "-";

        if (dateTo.HasValue)
        {
            toValue = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", dateTo.Value);
        }

        shCriteria.GetRow(5).GetCell(6).SetCellValue(toValue);


        // Crear Cabecera
        var headers = new List <string>()
        {
            dictionary["Item_EquipmentRepair_HeaderList_Date"],
            dictionary["Item_EquipmentRepair_HeaderList_Type"],
            dictionary["Item_EquipmentRepair_HeaderList_Operation"],
            dictionary["Item_EquipmentRepair_HeaderList_Responsible"],
            dictionary["Item_EquipmentRepair_HeaderList_Cost"]
        };

        int countColumns = 0;

        foreach (string headerLabel in headers)
        {
            if (sh.GetRow(3) == null)
            {
                sh.CreateRow(3);
            }

            if (sh.GetRow(3).GetCell(countColumns) == null)
            {
                sh.GetRow(3).CreateCell(countColumns);
            }

            sh.GetRow(3).GetCell(countColumns).SetCellValue(headerLabel);
            sh.GetRow(3).GetCell(countColumns).CellStyle = headerCellStyle;
            countColumns++;
        }

        int     countRow = 4;
        decimal total    = 0;

        // Poner el tipo de registro diccionarizado
        if (data != null)
        {
            foreach (var record in data)
            {
                record.RecordTypeText = dictionary[record.Item + "-" + (record.RecordType == 0 ? "Int" : "Ext")];
            }

            switch (listOrder.ToUpperInvariant())
            {
            default:
            case "TH0|ASC":
                data = data.OrderBy(d => d.Date).ToList();
                break;

            case "TH0|DESC":
                data = data.OrderByDescending(d => d.Date).ToList();
                break;

            case "TH1|ASC":
                data = data.OrderBy(d => d.RecordTypeText).ToList();
                break;

            case "TH1|DESC":
                data = data.OrderByDescending(d => d.RecordTypeText).ToList();
                break;

            case "TH2|ASC":
                data = data.OrderBy(d => d.Operation).ToList();
                break;

            case "TH2|DESC":
                data = data.OrderByDescending(d => d.Operation).ToList();
                break;

            case "TH3|ASC":
                data = data.OrderBy(d => d.Responsible.FullName).ToList();
                break;

            case "TH3|DESC":
                data = data.OrderByDescending(d => d.Responsible.FullName).ToList();
                break;

            case "TH4|ASC":
                data = data.OrderBy(d => d.Cost).ToList();
                break;

            case "TH4|DESC":
                data = data.OrderByDescending(d => d.Cost).ToList();
                break;
            }

            foreach (var equipmentRecord in data)
            {
                if (sh.GetRow(countRow) == null)
                {
                    sh.CreateRow(countRow);
                }

                // Fecha
                if (sh.GetRow(countRow).GetCell(0) == null)
                {
                    sh.GetRow(countRow).CreateCell(0);
                }
                sh.GetRow(countRow).GetCell(0).CellStyle.DataFormat = dataFormatCustom.GetFormat("dd/MM/yyyy");
                sh.GetRow(countRow).GetCell(0).SetCellValue(equipmentRecord.Date);

                // Tipo
                if (sh.GetRow(countRow).GetCell(1) == null)
                {
                    sh.GetRow(countRow).CreateCell(1);
                }
                sh.GetRow(countRow).GetCell(1).SetCellValue(equipmentRecord.RecordTypeText);

                // Operacion
                if (sh.GetRow(countRow).GetCell(2) == null)
                {
                    sh.GetRow(countRow).CreateCell(2);
                }
                sh.GetRow(countRow).GetCell(2).SetCellValue(equipmentRecord.Operation);

                // Responsable
                if (sh.GetRow(countRow).GetCell(3) == null)
                {
                    sh.GetRow(countRow).CreateCell(3);
                }
                sh.GetRow(countRow).GetCell(3).SetCellValue(equipmentRecord.Responsible.FullName);

                // Coste
                if (sh.GetRow(countRow).GetCell(4) == null)
                {
                    sh.GetRow(countRow).CreateCell(4);
                }
                if (equipmentRecord.Cost.HasValue)
                {
                    sh.GetRow(countRow).GetCell(4).SetCellValue(Convert.ToDouble(equipmentRecord.Cost.Value));
                    sh.GetRow(countRow).GetCell(4).SetCellType(CellType.Numeric);
                    sh.GetRow(countRow).GetCell(4).CellStyle = moneyCellStyle;
                    total += equipmentRecord.Cost.Value;
                }

                countRow++;
            }
        }

        if (sh.GetRow(countRow) == null)
        {
            sh.CreateRow(countRow);
        }
        if (sh.GetRow(countRow).GetCell(0) == null)
        {
            sh.GetRow(countRow).CreateCell(0);
        }
        if (sh.GetRow(countRow).GetCell(1) == null)
        {
            sh.GetRow(countRow).CreateCell(1);
        }
        if (sh.GetRow(countRow).GetCell(2) == null)
        {
            sh.GetRow(countRow).CreateCell(2);
        }
        if (sh.GetRow(countRow).GetCell(3) == null)
        {
            sh.GetRow(countRow).CreateCell(3);
        }

        sh.GetRow(countRow).GetCell(0).SetCellValue(string.Empty);
        sh.GetRow(countRow).GetCell(0).CellStyle = totalCellStyle;
        sh.GetRow(countRow).GetCell(1).SetCellValue(string.Empty);
        sh.GetRow(countRow).GetCell(1).CellStyle = totalCellStyle;
        sh.GetRow(countRow).GetCell(2).SetCellValue(string.Empty);
        sh.GetRow(countRow).GetCell(2).CellStyle = totalCellStyle;
        sh.GetRow(countRow).GetCell(3).SetCellValue(dictionary["Common_Total"]);
        sh.GetRow(countRow).GetCell(3).CellStyle = totalCellStyle;


        if (sh.GetRow(countRow).GetCell(4) == null)
        {
            sh.GetRow(countRow).CreateCell(4);
        }
        sh.GetRow(countRow).GetCell(4).SetCellValue(Convert.ToDouble(total));
        sh.GetRow(countRow).GetCell(4).SetCellType(CellType.Numeric);
        sh.GetRow(countRow).GetCell(4).CellStyle = totalValueCellStyle;

        sh.SetColumnWidth(0, 4000);
        sh.SetColumnWidth(1, 8400);
        sh.SetColumnWidth(1, 8400);
        sh.SetColumnWidth(2, 8400);
        sh.SetColumnWidth(3, 8400);
        sh.SetColumnWidth(4, 2800);

        // INsertar logo

        /*System.Drawing.Image image = System.Drawing.Image.FromFile(string.Format("{0}\\images\\Logos\\{1}.jpg", path, companyId));
         * MemoryStream ms = new MemoryStream();
         * //pull the memory stream from the image (I need this for the byte array later)
         * image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
         * //the drawing patriarch will hold the anchor and the master information
         * HSSFPatriarch patriarch = (HSSFPatriarch)sh.CreateDrawingPatriarch();
         * //store the coordinates of which cell and where in the cell the image goes
         * HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, 0, 0, 1, 2);
         * //types are 0, 2, and 3. 0 resizes within the cell, 2 doesn't
         * anchor.AnchorType = 0;// AnchorType.MoveDontResize;
         * //add the byte array and encode it for the excel file
         * int index = wb.AddPicture(ms.ToArray(), PictureType.PNG);
         * HSSFPicture signaturePicture = (HSSFPicture)patriarch.CreatePicture(anchor, index);*/
        if (!path.EndsWith("\\"))
        {
            path += "\\Temp\\";
        }
        else
        {
            path += "Temp\\";
        }

        using (var fs = new FileStream(string.Format("{0}{1}", path, fileName), FileMode.Create, FileAccess.Write))
        {
            wb.Write(fs);
        }

        res.SetSuccess(string.Format("/Temp/{0}", fileName));
        return(res);
    }
Esempio n. 18
0
    /// <summary>Page's load event</summary>
    /// <param name="sender">Loaded page</param>
    /// <param name="e">Event's arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        var    file = this.Request.Files[0];
        string path = Request.PhysicalApplicationPath;

        if (!path.EndsWith("\\"))
        {
            path += "\\";
        }

        int    itemLinked  = Convert.ToInt32(this.Request.Form["ItemLinked"]);
        long   itemId      = Convert.ToInt64(this.Request.Form["ItemId"]);
        int    companyId   = Convert.ToInt32(this.Request.Form["CompanyId"]);
        string description = this.Request.Form["Description"];

        if (string.IsNullOrEmpty(description))
        {
            description = file.FileName;
        }

        int    applicationUserId = Convert.ToInt32(this.Request.Form["ApplicationUserId"]);
        string itemLinkedText    = UploadFile.ResolveItemLinked(itemLinked);
        string fileName          = string.Format(@"{0}_{1}_{2}", itemLinkedText, itemId, Path.GetFileName(ToolsPdf.NormalizeFileName(file.FileName))).Replace("/", "-").Replace("/", "-");
        string fileDisk          = string.Format(@"{0}DOCS\{1}\{2}", path, companyId, fileName);

        bool exists = File.Exists(fileDisk);
        int  cont   = 1;

        while (exists)
        {
            string fileDiskName1   = Path.GetFileNameWithoutExtension(fileName);
            string extension       = Path.GetExtension(fileName);
            string fileDiskNameAll = Path.GetFileName(fileName);

            if (fileDiskName1.EndsWith(")", StringComparison.OrdinalIgnoreCase))
            {
                string part1 = fileDiskName1.Substring(0, fileDiskName1.LastIndexOf("("));
                fileName = string.Format(CultureInfo.InvariantCulture, "{0} ({1}){2}", part1, cont, extension);
            }
            else
            {
                fileName = string.Format(CultureInfo.InvariantCulture, "{0} ({1}){2}", fileDiskName1, cont, extension);
            }

            var folder = string.Format(@"{0}DOCS\{1}", path, companyId);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            fileDisk = string.Format(@"{0}DOCS\{1}\{2}", path, companyId, fileName);
            exists   = File.Exists(fileDisk);
            cont++;
        }

        file.SaveAs(fileDisk);
        long length     = new FileInfo(fileDisk).Length;
        var  uploadFile = new UploadFile
        {
            FileName    = fileName,
            Description = description,
            CompanyId   = companyId,
            Extension   = Path.GetExtension(file.FileName).Replace(".", string.Empty),
            ItemId      = itemId,
            ItemLinked  = itemLinked,
            Active      = true,
            CreatedBy   = new ApplicationUser {
                Id = applicationUserId
            },
            CreatedOn  = Constant.Now,
            ModifiedBy = new ApplicationUser {
                Id = applicationUserId
            },
            ModifiedOn = Constant.Now,
            Size       = length
        };

        var res = uploadFile.Insert(applicationUserId);

        this.Response.Clear();
        this.Response.ContentType = "application/json";
        this.Response.Write(res.MessageError);
        this.Response.Flush();
    }
Esempio n. 19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        long auditoryId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company    = new Company(companyId);
        var  res        = ActionResult.NoAction;
        var  user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  auditory   = Auditory.ById(auditoryId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }



        string formatedDescription = auditory.Description.Replace("?", string.Empty);

        formatedDescription = formatedDescription.Replace("#", string.Empty);
        formatedDescription = formatedDescription.Replace("/", string.Empty);
        formatedDescription = formatedDescription.Replace("\\", string.Empty);
        formatedDescription = formatedDescription.Replace(":", string.Empty);
        formatedDescription = formatedDescription.Replace(";", string.Empty);
        formatedDescription = formatedDescription.Replace(".", string.Empty);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Auditory"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);
        var document        = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = auditory.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Auditory"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        #region Dades bàsiques
        // Ficha pincipal

        var planning = AuditoryPlanning.ByAuditory(auditory.Id, auditory.CompanyId);
        var table    = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 50f, 30f, 50f });

        table.AddCell(new PdfPCell(new Phrase(auditory.Description, descriptionFont))
        {
            Colspan             = 4,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 20f,
            PaddingBottom       = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });


        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Type"]));
        table.AddCell(TitleData(dictionary["Item_Adutory_Type_Label_" + auditory.Type.ToString()]));

        if (auditory.Provider.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Provider"]));
            table.AddCell(TitleData(auditory.Provider.Description));
        }
        else if (auditory.Customer.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Customer"]));
            table.AddCell(TitleData(auditory.Customer.Description));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 2));
        }

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Rules"]));
        var  rulesText = string.Empty;
        bool firstRule = true;
        foreach (var rule in auditory.Rules)
        {
            if (firstRule)
            {
                firstRule = false;
            }
            else
            {
                rulesText += ", ";
            }

            rulesText += rule.Description;
        }
        table.AddCell(TitleData(rulesText, 3));

        var previewDateText = string.Empty;
        if (planning != null && planning.Count > 0)
        {
            previewDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", planning.OrderBy(p => p.Date).First().Date);
        }


        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_InternalResponsible"]));
        table.AddCell(TitleData(auditory.InternalResponsible.FullName, 3));

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PannedDate"]));
        //table.AddCell(TitleData(previewDateText));

        table.AddCell(TitleLabel(dictionary["Item_Audiotry_PDF_Planned"]));
        if (auditory.PlannedBy.Id > 0)
        {
            var planningText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.PlannedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-");
            table.AddCell(TitleData(planningText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PlanningDate"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Closing"]));
        if (auditory.ClosedBy.Employee.Id > 0)
        {
            var closedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ClosedBy.Employee.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-");
            table.AddCell(TitleData(closedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ClosedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Validation"]));
        if (auditory.ValidatedBy.Id > 0)
        {
            var validatedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ValidatedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-");
            table.AddCell(TitleData(validatedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ValidatedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Scope"]));
        table.AddCell(TitleData(auditory.Scope, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Address"]));
        table.AddCell(TitleData(auditory.EnterpriseAddress, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Notes"]));
        table.AddCell(TitleData(string.IsNullOrEmpty(auditory.Notes.Trim()) ? "-" : auditory.Notes, 3));

        document.Add(table);
        #endregion


        if (auditory.Status > 2)
        {
            var widthsPlanning = new float[] { 30f, 20f, 25f, 60f, 60f, 60f };
            var tablePlanning  = new PdfPTable(widthsPlanning.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tablePlanning.SetWidths(widthsPlanning);
            tablePlanning.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_PlanningTable_Title"], descriptionFont))
            {
                Colspan             = 6,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Date"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Hour"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Duration"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Process"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Auditor"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Audited"]));

            foreach (var pla in planning)
            {
                var hourText = string.Empty;
                var hours    = 0;
                var minutes  = pla.Hour;
                while (minutes > 59)
                {
                    hours++;
                    minutes -= 60;
                }
                hourText = string.Format(CultureInfo.InvariantCulture, "{0:0}:{1:00}", hours, minutes);

                var auditedText = pla.ProviderName;
                if (string.IsNullOrEmpty(auditedText))
                {
                    auditedText = pla.Audited.FullName;
                }

                tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Date));
                tablePlanning.AddCell(ToolsPdf.DataCellCenter(hourText));
                tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Duration));
                tablePlanning.AddCell(ToolsPdf.DataCell(pla.Process.Description));
                tablePlanning.AddCell(ToolsPdf.DataCell(pla.Auditor.Description));
                tablePlanning.AddCell(ToolsPdf.DataCell(auditedText));
            }

            document.Add(tablePlanning);

            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();

            var widthsTroballes = new float[] { 30f, 30f, 20f, 8f };
            var tableTroballes  = new PdfPTable(widthsTroballes.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableTroballes.SetWidths(widthsTroballes);
            tableTroballes.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Found"], descriptionFont))
            {
                Colspan             = 4,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Found"]));
            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Requirement"]));
            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Result"]));
            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"]));

            var troballes = AuditoryCuestionarioFound.ByAuditory(auditory.Id, auditory.CompanyId);
            foreach (var troballa in troballes)
            {
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Text));
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Requeriment));
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Unconformity));
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Action ? dictionary["Common_Yes"] : dictionary["Common_No"]));
            }

            document.Add(tableTroballes);



            var widthsMillores = new float[] { 80f, 8f };
            var tableMillores  = new PdfPTable(widthsMillores.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableMillores.SetWidths(widthsMillores);
            tableMillores.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Improvements"], descriptionFont))
            {
                Colspan             = 4,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Improvement"]));
            tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"]));

            var millores = AuditoryCuestionarioImprovement.ByAuditory(auditory.Id, auditory.CompanyId);
            foreach (var millora in millores)
            {
                tableMillores.AddCell(ToolsPdf.DataCell(millora.Text));
                tableMillores.AddCell(ToolsPdf.DataCell(millora.Action ? dictionary["Common_Yes"] : dictionary["Common_No"]));
            }

            document.Add(tableMillores);

            if (!string.IsNullOrEmpty(auditory.PuntosFuertes.Trim()))
            {
                document.Add(new Phrase(Environment.NewLine));
                document.Add(new Phrase(dictionary["Item_Auditory_Label_PuntosFuertes"], new Font(this.arial, 10, Font.BOLD, BaseColor.BLACK)));
                document.Add(new Phrase(Environment.NewLine));
                document.Add(new Phrase(auditory.PuntosFuertes));
            }

            var actions = IncidentAction.ByAuditoryId(auditory.Id, auditory.CompanyId);
            if (actions != null && actions.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var widthsActions = new float[] { 8f, 80f };
                var tableActions  = new PdfPTable(widthsActions.Length)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableActions.SetWidths(widthsActions);
                tableActions.AddCell(new PdfPCell(new Phrase(dictionary["Item_IncidentActions"], descriptionFont))
                {
                    Colspan             = 4,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Type"]));
                tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));

                foreach (var action in actions)
                {
                    string actionTypeText = string.Empty;
                    switch (action.ActionType)
                    {
                    default:
                    case 1: actionTypeText = dictionary["Item_IncidentAction_Type1"]; break;

                    case 2: actionTypeText = dictionary["Item_IncidentAction_Type2"]; break;

                    case 3: actionTypeText = dictionary["Item_IncidentAction_Type3"]; break;
                    }
                    tableActions.AddCell(ToolsPdf.DataCell(actionTypeText));
                    tableActions.AddCell(ToolsPdf.DataCell(action.Description));
                }

                document.Add(tableActions);
            }
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Esempio n. 20
0
    public static ActionResult PDF(int companyId, string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_EquipmentList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_EquipmentList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        var titleCell = new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        };

        titleTable.AddCell(titleCell);

        // @alex: hay que indicar que hay una columna menos por fila
        //// var table = new iTSpdf.PdfPTable(4)
        var table = new iTSpdf.PdfPTable(3)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 20f, 10f, 5f, 15f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Code"] + " - " + dictionary["Item_Equipment_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Location"]));

        // @alex: se omite la columna de la cabecera
        //// table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Cost"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Responsible"]));

        int cont = 0;
        var data = Equipment.ByCompany(companyId).ToList();

        string filter = GetFilter();

        if (filter.IndexOf("1", StringComparison.OrdinalIgnoreCase) != -1)
        {
            data = data.Where(d => !d.EndDate.HasValue).ToList();
        }

        if (filter.IndexOf("2", StringComparison.OrdinalIgnoreCase) != -1)
        {
            data = data.Where(d => d.EndDate.HasValue).ToList();
        }

        var dataC = new List <Equipment>();

        if (filter.IndexOf("C", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataC = data.Where(d => d.IsCalibration).ToList();
        }

        var dataV = new List <Equipment>();

        if (filter.IndexOf("V", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataV = data.Where(d => d.IsVerification).ToList();
        }

        var dataM = new List <Equipment>();

        if (filter.IndexOf("M", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataM = data.Where(d => d.IsMaintenance).ToList();
        }

        data = dataC;
        foreach (var equipmentV in dataV)
        {
            if (!data.Any(d => d.Id == equipmentV.Id))
            {
                data.Add(equipmentV);
            }
        }

        foreach (var equipmentM in dataM)
        {
            if (!data.Any(d => d.Id == equipmentM.Id))
            {
                data.Add(equipmentM);
            }
        }

        // aplicar filtros

        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 8f, 50f });

        string statusText    = string.Empty;
        string operativaText = string.Empty;

        if (filter.IndexOf("0") != -1)
        {
            statusText = dictionary["Common_All"];
        }
        else if (filter.IndexOf("1") != -1)
        {
            statusText = dictionary["Item_Equipment_List_Filter_ShowActive"];
        }
        else if (filter.IndexOf("2") != -1)
        {
            statusText = dictionary["Item_Equipment_List_Filter_ShowClosed"];
        }

        bool first = true;

        if (filter.IndexOf("C") != -1)
        {
            first         = false;
            operativaText = dictionary["Item_Equipment_List_Filter_ShowCalibration"];
        }
        if (filter.IndexOf("V") != -1)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_List_Filter_ShowVerification"];
        }
        if (filter.IndexOf("M") != -1)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_List_Filter_ShowMaintenance"];
        }

        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByOperation"], operativaText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByStatus"], statusText);

        bool    pair   = false;
        decimal total  = 0;
        int     border = 0;

        if (!string.IsNullOrEmpty(listOrder))
        {
            switch (listOrder.ToUpperInvariant())
            {
            default:
            case "TH0|ASC":
                data = data.OrderBy(d => d.Code).ToList();
                break;

            case "TH0|DESC":
                data = data.OrderByDescending(d => d.Code).ToList();
                break;

            case "TH1|ASC":
                data = data.OrderBy(d => d.Location).ToList();
                break;

            case "TH1|DESC":
                data = data.OrderByDescending(d => d.Location).ToList();
                break;

            case "TH2|ASC":
                data = data.OrderBy(d => d.Responsible.FullName).ToList();
                break;

            case "TH2|DESC":
                data = data.OrderByDescending(d => d.Responsible.FullName).ToList();
                break;

            case "TH3|ASC":
                data = data.OrderBy(d => d.TotalCost).ToList();
                break;

            case "TH3|DESC":
                data = data.OrderByDescending(d => d.TotalCost).ToList();
                break;
            }
        }

        foreach (Equipment equipment in data)
        {
            total += equipment.TotalCost;

            var lineBackground = pair ? rowEven : rowPair;

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Code + " - " + equipment.Description, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = lineBackground,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Location, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = lineBackground,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            // @alex: se omite la celda de los datos del coste

            /*string totalCost = string.Format("{0:#,##0.00}", equipment.TotalCost);
             * table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalCost, ToolsPdf.LayoutFonts.Times))
             * {
             *  Border = border,
             *  BackgroundColor = lineBackground,
             *  Padding = 6f,
             *  PaddingTop = 4f,
             *  HorizontalAlignment = 2
             * });*/

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Responsible.FullName, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = lineBackground,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            cont++;
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        string totalText = string.Format("{0:#,##0.00}", total);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalText, ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 2
        });

        pdfDoc.Add(criteriatable);
        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var alignRight  = Element.ALIGN_RIGHT;

        long oportunityId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId    = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company      = new Company(companyId);
        var  res          = ActionResult.NoAction;
        var  user         = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary   = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  oportunity   = Oportunity.ById(oportunityId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(oportunity.Description);

        var alignLeft = Element.ALIGN_LEFT;

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Oportunity"],
            formatedDescription,
            DateTime.Now);

        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);
        var document        = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = oportunity.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Oportunity"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        #region Dades bàsiques
        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 50f, 30f, 50f });

        table.AddCell(new PdfPCell(new Phrase(oportunity.Description, descriptionFont))
        {
            Colspan             = 4,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 10f,
            PaddingBottom       = 10f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        table.AddCell(TitleCell(dictionary["Item_BusinessRisk_Tab_Basic"], 4));

        table.AddCell(TitleLabel(dictionary["Item_BusinessRisk_LabelField_DateStart"]));
        table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", oportunity.DateStart)));

        table.AddCell(TitleLabel(dictionary["Item_Process"]));
        table.AddCell(TitleData(oportunity.Process.Description));

        table.AddCell(TitleLabel(dictionary["Item_Rule"]));
        table.AddCell(TitleData(oportunity.Rule.Description));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        string costText = oportunity.Cost.ToString();
        if (costText == "0")
        {
            costText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(costText));

        string impactText = oportunity.Impact.ToString();
        if (impactText == "0")
        {
            impactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(impactText));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Description"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Description, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Causes, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Control"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Control, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Notes, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());

        table.AddCell(TitleCell(dictionary["Item_Oportunity_Tab_Graphics"], 4));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        string finalCostText = oportunity.FinalCost.ToString();
        if (finalCostText == "0")
        {
            finalCostText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(finalCostText));

        string finalImpactText = oportunity.FinalImpact.ToString();
        if (finalImpactText == "0")
        {
            finalImpactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(finalImpactText));

        document.Add(table);
        #endregion

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            // Añadir posible acción
            var action = IncidentAction.ByOportunityId(oportunity.Id, companyId);
            if (action.Id > 0)
            {
                var tableAction = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f });

                // Descripción
                var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK);
                tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont))
                {
                    Colspan             = 4,
                    Border              = ToolsPdf.BorderBottom,
                    HorizontalAlignment = Rectangle.ALIGN_CENTER
                });
                tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER));
                tableAction.AddCell(ValueCell(action.Description, ToolsPdf.BorderNone, alignLeft, 3));

                // WhatHappend
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

                // Causes
                var causesFullName = string.Empty;
                var causesDate     = string.Empty;
                if (action.CausesBy != null)
                {
                    causesFullName = action.CausesBy.FullName;
                    causesDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2));

                // Actions
                var actionFullName = string.Empty;
                var actionDate     = string.Empty;
                if (action.ActionsBy != null)
                {
                    actionFullName = action.ActionsBy.FullName;
                    actionDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2));

                // Monitoring
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4));

                // Close
                var closedFullName = string.Empty;
                var closedDate     = string.Empty;
                if (action.ClosedBy != null)
                {
                    closedFullName = action.ClosedBy.FullName;
                    closedDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2));

                // Notes
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4));

                document.NewPage();
                document.Add(tableAction);
            }

            #region Historico acciones
            var historico = IncidentAction.ByOportunityCode(oportunity.Code, company.Id).Where(ia => ia.Oportunity.Id != oportunity.Id).OrderBy(incidentAction => incidentAction.WhatHappenedOn).ToList();
            if (historico.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableHistoric = new iTSpdf.PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableHistoric.SetWidths(new float[] { 20f, 30f, 120f, 20f, 20f });

                tableHistoric.AddCell(new PdfPCell(new Phrase(dictionary["Item_BusinessRisk_Tab_HistoryActions"], descriptionFont))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"]));

                int cont = 0;
                foreach (var accion in historico)
                {
                    string statusText = dictionary["Item_Incident_Status1"];

                    if (accion.CausesOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status2"];
                    }

                    if (accion.ActionsOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status3"];
                    }

                    if (accion.ClosedOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status4"];
                    }

                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.WhatHappenedOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(statusText, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(accion.Description, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ActionsOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ClosedOn, ToolsPdf.LayoutFonts.Times));

                    cont++;
                }

                tableHistoric.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 5,
                    Padding = 8f
                });

                document.Add(tableHistoric);
            }
            #endregion

            #region Costes
            var costs = IncidentActionCost.ByOportunityId(oportunity.Id, company.Id);
            if (costs.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableCost = new iTSpdf.PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableCost.SetWidths(new float[] { 90f, 40f, 30f, 60f, 20f });

                tableCost.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_Tab_Costs"], descriptionFont))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

                int     cont      = 0;
                decimal costTotal = 0;
                foreach (var cost in costs)
                {
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Description, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount * cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Responsible.FullName, ToolsPdf.LayoutFonts.Times));

                    costTotal += cost.Amount * cost.Quantity;
                    cont++;
                }

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 2,
                    Padding = 8f
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(costTotal), ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });



                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                document.Add(tableCost);
            }

            #endregion
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Esempio n. 22
0
    public static ActionResult PDF(
        int companyId,
        DateTime?from,
        DateTime?to,
        int status,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Objetivo_List"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_Objetivo_List"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var rowEven = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });


        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(4)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 20f, 50f, 20f, 150f });

        #region texts
        string periode = string.Empty;
        if (from.HasValue && to == null)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_From"], from);
        }
        else if (from == null && to.HasValue)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_To"], to);
        }
        else if (from.HasValue && to.HasValue)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy} {1:dd/MM/yyyy}", from, to);
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        string statusText = dictionary["Common_All"];
        if (status == 1)
        {
            statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowActive"];
        }

        if (status == 2)
        {
            statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowClosed"];
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText);

        if (!string.IsNullOrEmpty(filterText))
        {
            ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText);
        }
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(5)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 7f, 50f, 30f, 12f, 12f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Name"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Responsible"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_StartDate"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_PreviewEndDate"]));

        int cont = 0;
        var data = Objetivo.Filter(companyId, from, to, status).ToList();
        foreach (var item in data)
        {
            if (!item.Objetivo.EndDate.HasValue)
            {
                item.Objetivo.EndDate = item.Objetivo.PreviewEndDate;
            }
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Objetivo.Name).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Objetivo.Name).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.Objetivo.Responsible.FullName).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.Objetivo.Responsible.FullName).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Objetivo.StartDate).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Objetivo.StartDate).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Objetivo.EndDate).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Objetivo.EndDate).ToList();
            break;
        }

        cont = 0;
        foreach (var item in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                var show = false;
                if (item.Objetivo.Name.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    show = true;
                }

                if (item.Objetivo.Responsible.FullName.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    show = true;
                }

                if (!show)
                {
                    continue;
                }
            }

            string endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.PreviewEndDate);
            if (item.Objetivo.EndDate.HasValue)
            {
                endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.EndDate);
            }

            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Active ? dictionary["Common_Active"] : dictionary["Common_Inactve"], ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Name, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Responsible.FullName, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.StartDate), ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(endDateText, ToolsPdf.LayoutFonts.Times));
            cont++;
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 3
        });

        pdfDoc.Add(table);

        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Esempio n. 23
0
    public static ActionResult PDF(int companyId, string filter, string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            Dictionary["Item_DocumentList"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = Dictionary["Item_DocumentList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 20f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        var criteriatable = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 10f, 20f, 12f, 30f, 10f, 80f });

        var criteria1Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Common_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        };

        var criteria2Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Item_Document_FieldLabel_Category"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        };

        var criteria3Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Item_Document_FieldLabel_Origin"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        };

        string statusText = Dictionary["Common_All_Male_Plural"];
        string category   = Dictionary["Common_All_Female_Plural"];
        string origin     = Dictionary["Common_All_Male_Plural"];

        if (filter.IndexOf("A|") != -1)
        {
            statusText = Dictionary["Common_Active_Plural"];
        }

        if (filter.StartsWith("I", StringComparison.OrdinalIgnoreCase))
        {
            statusText = Dictionary["Common_Inactive_Plural"];
        }

        if (filter.StartsWith("|", StringComparison.OrdinalIgnoreCase))
        {
            statusText = Dictionary["Common_None"];
        }

        var documents = GisoFramework.Item.Document.ByCompany(companyId);
        var data      = new List <GisoFramework.Item.Document>();

        // @alex: "A" indica que en el filtro se ha marcado "activos"
        if (filter.IndexOf("A") != -1)
        {
            data = documents.Where(d => d.EndDate.HasValue == false).ToList();
        }

        // @alex: "I" indica que en el filtro se ha marcado "inactivos"
        if (filter.IndexOf("I") != -1)
        {
            data.AddRange(documents.Where(d => d.EndDate.HasValue).ToList());
        }

        var parts = filter.Split('|');

        if (parts[1] != "-1")
        {
            data = data.Where(d => d.Category.Id == Convert.ToInt32(parts[1])).ToList();
            var cats = DocumentCategory.ByCompany(companyId);
            var cat  = cats.First(c => c.Id == Convert.ToInt32(parts[1]));
            category = cat.Description;
        }

        if (parts[2] == "0")
        {
            data   = data.Where(d => d.Origin.Id == 0).ToList();
            origin = Dictionary["Common_Internal"];
        }

        if (parts[2] == "1")
        {
            data   = data.Where(d => d.Origin.Id > 0).ToList();
            origin = Dictionary["Common_External"];
        }

        criteriatable.AddCell(criteria1Label);
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(criteria2Label);
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(category, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(criteria3Label);
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(origin, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        // @alex-20200605: hay que indicr que son 7 columnas en lugar de 6
        var table = new iTSpdf.PdfPTable(7)
                    //var table = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1
        };

        // @alex-20200605: supongo que te petaba aquí porque le enviarías 7 anchos cuando sólo había 6 columnas (mensaje anterior)
        table.SetWidths(new float[] { 20f, 5f, 12f, 9f, 9f, 5f, 5f });
        //table.SetWidths(new float[] { 20f, 5f, 15f, 15f, 10f, 5f });
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Name"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Code"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Category"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Location"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Revision"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinessRisk_LabelField_DateStart"]));

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.Code).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.Code).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.LastNumber).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.LastNumber).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Origin).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Origin).ToList();
            break;

        // @alex-20200605: toda columna ordenable en pantalla debe aparece aquí para replicar el orden en el pdf
        case "TH4|ASC":
            data = data.OrderBy(d => d.Location).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Location).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.LastNumber).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.LastNumber).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.StartDate).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.StartDate).ToList();
            break;
        }

        int count = 0;

        foreach (var document in data)
        {
            count++;
            table.AddCell(ToolsPdf.DataCell(document.Description));
            table.AddCell(ToolsPdf.DataCell(document.Code));
            table.AddCell(ToolsPdf.DataCell(document.Category.Description));
            table.AddCell(ToolsPdf.DataCell(document.Origin.Id == 0 ? Dictionary["Common_Internal"] : Dictionary["Common_External"]));
            table.AddCell(ToolsPdf.DataCell(document.Location));
            table.AddCell(ToolsPdf.DataCell(document.LastNumber));
            table.AddCell(ToolsPdf.DataCell(document.StartDate));
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            Dictionary["Common_RegisterCount"],
            count);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Colspan         = 5
        });

        pdfDoc.Add(criteriatable);
        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        var presupuestoId = Request.QueryString["presupuestoId"];
        var centro        = HttpContext.Current.Session["user"] as ApplicationUser;
        var polizaId      = Request.QueryString["polizaId"];
        var poliza        = Poliza.ById(polizaId);
        var dictionary    = ApplicationDictionary.Load("es");

        var path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}.pdf",
            dictionary["Item_Prespuesto"],
            Guid.NewGuid());

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;

        string status   = string.Empty;
        var    document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);
        var    writer   = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));

        document.Open();

        var borderNone  = Rectangle.NO_BORDER;
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderAll   = Rectangle.RIGHT_BORDER + Rectangle.TOP_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;

        document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
        document.Add(new Paragraph("N.I.F: " + centro.NIF, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph(centro.CP + ", " + centro.Poblacion, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph("Telf.: " + centro.Telefono1, FontFactory.GetFont(FontFactory.HELVETICA, 8)));

        var alignLeft  = Element.ALIGN_LEFT;
        var alignRight = Element.ALIGN_RIGHT;

        var table = new PdfPTable(2)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 30f });
        var labelFont = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL);
        var totalFont = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.NORMAL);
        var dataFont  = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD);

        var presupuestoCodigo = string.Empty;
        var presupuestoFecha  = string.Empty;

        var aseguradoNombre    = poliza.AseguradoNombre;
        var aseguradoDireccion = string.Empty;
        var aseguradoCP        = string.Empty;
        var aseguradoPoblacion = string.Empty;
        var aseguradoProvincia = string.Empty;
        var aseguradoNIF       = poliza.AseguradoNIF;
        var observaciones      = string.Empty;

        // Linea Total
        string  impuestoText = dictionary["PDF_IVA"] + " " + ConfigurationManager.AppSettings["IVA"].ToString() + "%";
        decimal impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["IVA"].ToString());

        if (centro.Provincia.IndexOf("tenerife", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("canaria", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("las palmas", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_IGIC"] + " " + ConfigurationManager.AppSettings["IGIC"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["IGIC"].ToString());
        }

        if (centro.Provincia.IndexOf("melilla", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_Melilla"] + " " + ConfigurationManager.AppSettings["Melilla"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["Melilla"].ToString());
        }

        if (centro.Provincia.IndexOf("ceuta", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_Ceuta"] + " " + ConfigurationManager.AppSettings["Ceuta"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["Ceuta"].ToString());
        }

        var tableObservaciones = new PdfPTable(2)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        var tableCostsAspad = new PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 10f
        };

        var tableCostsPropios = new PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 10f,
            SpacingAfter        = 20f
        };

        tableObservaciones.SetWidths(new float[] { 1f, 3f });
        tableCostsAspad.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f });
        tableCostsPropios.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f });

        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Especialidad"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Concepto"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Cantidad"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Base"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Dto"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Importe"]));

        /* CREATE PROCEDURE ASPADLAND_GetPresupuestoPendienteByPresupuestoId
         *   @PresupuestoId uniqueidentifier,
         *   @CentroId nvarchar(50) */
        bool    propios            = false;
        bool    hasObservaciones   = false;
        decimal totalBaseCost      = 0;
        decimal totalBaseCostASPAD = 0;

        using (var cmd = new SqlCommand("ASPADLAND_Salesforce_GetPresupuestoPendienteByPresupuestoId"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString))
            {
                cmd.Connection = cnn;
                cmd.Parameters.Add(DataParameter.Input("@PresupuestoId", presupuestoId));
                cmd.Parameters.Add(DataParameter.Input("@CentroId", centro.Id));
                try
                {
                    cmd.Connection.Open();
                    using (var rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            observaciones     = rdr.GetString(9);
                            presupuestoCodigo = rdr.GetString(1);
                            presupuestoFecha  = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", rdr.GetDateTime(7));

                            string amountText        = string.Empty;
                            string totalRowText      = string.Empty;
                            string actoObservaciones = rdr.GetString(10);
                            var    especialidad      = rdr.GetString(4);

                            decimal finalAmount = 0M;
                            if (!rdr.IsDBNull(5))
                            {
                                finalAmount = rdr.GetDecimal(5);

                                if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                                {
                                    finalAmount = finalAmount / (1 + impuesto / 100);
                                }

                                amountText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");

                                totalRowText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");
                            }

                            var dto = string.Empty;
                            if (!rdr.IsDBNull(6))
                            {
                                decimal dtoAmount = rdr.GetDecimal(6);
                                finalAmount = finalAmount / (1 + impuesto / 100);

                                amountText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");

                                finalAmount = finalAmount * (100 - dtoAmount) / 100;
                                dto         = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} %",
                                    dtoAmount).Replace(",", ".");
                                totalRowText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");
                            }

                            if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                            {
                                totalBaseCost += finalAmount;
                            }
                            else
                            {
                                totalBaseCostASPAD += finalAmount;
                            }

                            if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                            {
                                if (!propios)
                                {
                                    tableCostsPropios.AddCell(new PdfPCell(new Phrase(dictionary["PDF_Actospropios"], ToolsPdf.TimesBold))
                                    {
                                        Border              = ToolsPdf.BorderBottom,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0,
                                        Colspan             = 6
                                    });
                                }

                                tableCostsPropios.AddCell(ToolsPdf.DataCell(especialidad, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(1, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(amountText, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dto, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont));
                                propios = true;

                                if (!string.IsNullOrEmpty(actoObservaciones))
                                {
                                    hasObservaciones = true;
                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });

                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });
                                }
                            }
                            else
                            {
                                tableCostsAspad.AddCell(ToolsPdf.DataCell(especialidad, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(1, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(amountText, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dto, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont));

                                if (!string.IsNullOrEmpty(actoObservaciones))
                                {
                                    hasObservaciones = true;
                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });

                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (cmd.Connection.State != ConnectionState.Closed)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }

        var la1 = new Chunk(dictionary["PDF_Albaran"] + ": ", labelFont);
        var la2 = new Chunk(presupuestoCodigo + Environment.NewLine, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD));
        var la3 = new Chunk(dictionary["PDF_Fecha"] + ": ", labelFont);
        var la4 = new Chunk(presupuestoFecha, dataFont);

        var p1 = new Paragraph
        {
            la1,
            la2,
            la3,
            la4
        };

        document.Add(new Paragraph(Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine));

        var lb1 = new Chunk(aseguradoNombre + Environment.NewLine, dataFont);
        var lb2 = new Chunk(dictionary["PDF_Poliza"] + ": ", labelFont);
        var lb3 = new Chunk(poliza.Numero + Environment.NewLine, dataFont);

        var p2 = new Paragraph
        {
            lb1,
            lb2,
            lb3
        };

        var cell1 = new PdfPCell {
            Border = ToolsPdf.BorderNone
        };
        var cell2 = new PdfPCell {
            Border = ToolsPdf.BorderNone
        };

        cell1.AddElement(p1);
        cell2.AddElement(p2);


        table.AddCell(cell1);
        table.AddCell(cell2);

        document.Add(table);

        decimal baseIvaASPAD     = totalBaseCostASPAD * impuesto / 100;
        string  baseIvaTextASPAD = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIvaASPAD).Replace(",", ".");
        string  totalASPAD       = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD + baseIvaASPAD).Replace(",", ".");

        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"] + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD).Replace(",", "."), totalFont));

        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(baseIvaTextASPAD, totalFont));

        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalASPAD, totalFont));
        document.Add(tableCostsAspad);

        if (propios)
        {
            decimal baseIva     = totalBaseCost * impuesto / 100;
            string  baseIvaText = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIva).Replace(",", ".");
            string  total       = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva).Replace(",", ".");

            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"], labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost).Replace(",", "."), totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(baseIvaText, totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(total, totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));

            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(dictionary["PDF_Total"] + ":"));
            string superTotal = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva + totalBaseCostASPAD + baseIvaASPAD).Replace(",", ".");
            tableCostsPropios.AddCell(TotalCell(superTotal));

            document.Add(tableCostsPropios);
        }

        if (!string.IsNullOrEmpty(observaciones))
        {
            document.Add(new Paragraph("Observaciones", ToolsPdf.TimesBold));
            document.Add(new Paragraph(observaciones, labelFont));
        }

        if (hasObservaciones)
        {
            document.Add(tableObservaciones);
        }

        document.Add(new Phrase(dictionary["Item_Presupuesto_Print_Caducity"], ToolsPdf.TimesLittle));

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }