CloseDocument() public method

Closes the document.
Version for languages that are not case-dependant. Once all the content has been written in the body, you have to close the body. After that nothing can be written to the body anymore.
public CloseDocument ( ) : void
return void
Exemplo 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);
        }
Exemplo n.º 2
0
        public override byte[] Render(global::Campus.Report.Base.Report report)
        {
            byte[] buffer;

            using (var outputMemoryStream = new MemoryStream())
            {
                var pdfDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 25, 15, 10);

                var arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");
                FontFactory.Register(arialuniTff);

                //FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.Fonts));

                var pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);

                pdfWriter.CloseStream = false;
                pdfDocument.Open();

                //pdfDocument.NewPage();
                pdfDocument.Add(new Paragraph(new Phrase(" ")));

                foreach (var x in report)
                {
                    if (x is TextElement)
                    {
                        var element = x as TextElement;

                        if (Render(element, pdfDocument, arialuniTff))
                        {
                            continue;
                        }
                    }

                    if (x is TableElement)
                    {
                        var element = x as TableElement;
                        if (Render(element, pdfDocument, arialuniTff))
                        {
                            continue;
                        }
                    }

                    if (x is ImageElement)
                    {
                        var element = x as ImageElement;

                        if (Render(element, pdfDocument))
                        {
                            continue;
                        }
                    }

                    if (x is ComplexHeaderCell)
                    {
                        var element = x as ComplexHeaderCell;

                        if (Render(element, pdfDocument))
                        {
                            continue;
                        }
                    }

                    if (x is ComplexHeader)
                    {
                        var element = x as ComplexHeader;

                        if (Render(element, pdfDocument))
                        {
                            continue;
                        }
                    }
                }

                pdfDocument.Close();
                pdfDocument.CloseDocument();

                buffer = new byte[outputMemoryStream.Position];
                outputMemoryStream.Position = 0;
                outputMemoryStream.Read(buffer, 0, buffer.Length);
            }

            return(buffer);
        }
Exemplo n.º 3
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);
    }
Exemplo n.º 4
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);
    }
Exemplo n.º 5
0
        /// <summary>
        /// Exports the chart to the specified output stream as binary. When 
        /// exporting to a web response the WriteToHttpResponse() method is likely
        /// preferred.
        /// </summary>
        /// <param name="outputStream">An output stream.</param>
        internal void WriteToStream(Stream outputStream)
        {
            switch (this.ContentType)
              {
            case "image/jpeg":
              CreateSvgDocument().Draw().Save(
            outputStream,
            ImageFormat.Jpeg);
              break;

            case "image/png":
              // PNG output requires a seekable stream.
              using (MemoryStream seekableStream = new MemoryStream())
              {
            CreateSvgDocument().Draw().Save(
                seekableStream,
                ImageFormat.Png);
            seekableStream.WriteTo(outputStream);
              }
              break;

            case "application/pdf":
              SvgDocument svgDoc = CreateSvgDocument();

              // Create PDF document.
              using (Document pdfDoc = new Document())
              {
            // Scalar to convert from 72 dpi to 150 dpi.
            float dpiScalar = 150f / 72f;

            // Set page size. Page dimensions are in 1/72nds of an inch.
            // Page dimensions are scaled to boost dpi and keep page
            // dimensions to a smaller size.
            pdfDoc.SetPageSize(new Rectangle(
              svgDoc.Width / dpiScalar,
              svgDoc.Height / dpiScalar));

            // Set margin to none.
            pdfDoc.SetMargins(0f, 0f, 0f, 0f);

            // Create PDF writer to write to response stream.
            using (PdfWriter pdfWriter = PdfWriter.GetInstance(
              pdfDoc,
              outputStream))
            {
              // Configure PdfWriter.
              pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
              pdfWriter.CompressionLevel = PdfStream.DEFAULT_COMPRESSION;

              // Add meta data.
              pdfDoc.AddCreator(PdfMetaCreator);
              pdfDoc.AddTitle(this.Name);

              // Output PDF document.
              pdfDoc.Open();
              pdfDoc.NewPage();

              // Create image element from SVG image.
              Image image = Image.GetInstance(svgDoc.Draw(), ImageFormat.Bmp);
              image.CompressionLevel = PdfStream.DEFAULT_COMPRESSION;

              // Must match scaling performed when setting page size.
              image.ScalePercent(100f / dpiScalar);

              // Add image element to PDF document.
              pdfDoc.Add(image);

              pdfDoc.CloseDocument();
            }
              }

              break;

            case "image/svg+xml":
              using (StreamWriter writer = new StreamWriter(outputStream))
              {
            writer.Write(this.Svg);
            writer.Flush();
              }

              break;

            default:
              throw new InvalidOperationException(string.Format(
            "ContentType '{0}' is invalid.", this.ContentType));
              }

              outputStream.Flush();
        }
Exemplo n.º 6
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);
    }
        // based on example http://itextsharp.sourceforge.net/examples/Concat.cs
        public string ConcatFilesOld(List <string> files, string targetPath)
        {
            try
            {
                if (files.Count > 0)
                {
                    string file = files[0];
                    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(GetFullPath(file));
                    int n = reader.NumberOfPages;
                    iTextSharp.text.Document      document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                    iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(targetPath, System.IO.FileMode.Create));

                    reader.Close();
                    document.Open();
                    iTextSharp.text.pdf.PdfContentByte  cb = writer.DirectContent;
                    iTextSharp.text.pdf.PdfImportedPage page;
                    int rotation;
                    foreach (string sourceFile in files)
                    {
                        int i = 0;
                        iTextSharp.text.pdf.PdfReader reader2 = new iTextSharp.text.pdf.PdfReader(GetFullPath(sourceFile));
                        n = reader2.NumberOfPages;
                        while (i < n)
                        {
                            i++;
                            document.SetPageSize(reader2.GetPageSizeWithRotation(i));
                            document.NewPage();
                            page     = writer.GetImportedPage(reader2, i);
                            rotation = reader2.GetPageRotation(i);
                            if (rotation == 90)
                            {
                                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader2.GetPageSizeWithRotation(i).Height);
                            }
                            else if ((rotation == 270))
                            {
                                cb.AddTemplate(page, 0f, 1f, -1f, 0f, reader2.GetPageSizeWithRotation(i).Width, 0f);
                            }
                            else
                            {
                                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                        }

                        writer.FreeReader(reader2);
                        reader2.Close();
                    }

                    if (document.IsOpen())
                    {
                        document.CloseDocument();
                        document.Close();
                    }
                    return("");
                }
                else
                {
                    return("No files to process, use AddFile method");
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Exemplo n.º 8
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);
    }
Exemplo n.º 9
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);
    }
Exemplo n.º 10
0
        private void GenerateInvoicePDF()
        {
            Document document = new Document(PageSize.A4, 20f, 20f, 20f, 20f);
            try
            {
                if (!Directory.Exists(InvoiceFolderPath))
                {
                    Directory.CreateDirectory(InvoiceFolderPath);
                }

                PdfWriter.GetInstance(document, new FileStream(string.Format(InvoiceFolderPath + @"/Invoice{0}.pdf", txtInvoiceNumber.Text), FileMode.Create));
                document.Open();
                //Tables for Logo and Invoice Details
                PdfPTable outerHeader = new PdfPTable(2);
                outerHeader.DefaultCell.BorderWidth = 0;
                outerHeader.TotalWidth = 750f;
                outerHeader.WidthPercentage = 100;
                outerHeader.SpacingAfter = 20f;
                outerHeader.HorizontalAlignment = Element.ALIGN_LEFT;
                PdfPTable pdfCompanyTable = CreateCompanyGrid();
                PdfPTable pdfInvoiceTable = CreateInvoiceGrid();
                outerHeader.AddCell(pdfCompanyTable);
                outerHeader.AddCell(pdfInvoiceTable);

                //Tables for Billing and Shipping Address
                PdfPTable outerAddress = new PdfPTable(2);
                outerAddress.DefaultCell.BorderWidth = 0;
                outerAddress.TotalWidth = 750f;
                outerAddress.WidthPercentage = 100;
                outerAddress.SpacingAfter = 10f;
                outerAddress.HorizontalAlignment = Element.ALIGN_LEFT;
                PdfPTable pdfBillingAddressTable = CreateBillingAddressGrid();
                outerAddress.AddCell(pdfBillingAddressTable);
                PdfPTable pdfShippingAddressTable = CreateShippingAddressGrid();
                outerAddress.AddCell(pdfShippingAddressTable);

                //Product Table
                PdfPTable pdfProductTable = CreateProductsGrid();

                //Tables for Authorized Signatory and Invoice Amounts
                PdfPTable outerInvoiceDetails = new PdfPTable(2);
                outerInvoiceDetails.DefaultCell.BorderWidth = 0;
                outerInvoiceDetails.TotalWidth = 750f;
                outerInvoiceDetails.WidthPercentage = 100;
                outerInvoiceDetails.SpacingAfter = 20f;
                outerInvoiceDetails.HorizontalAlignment = Element.ALIGN_LEFT;
                PdfPTable pdfAuthorizedSignatoryTable = CreateAuthorizedSignatoryGrid();
                outerInvoiceDetails.AddCell(pdfAuthorizedSignatoryTable);
                PdfPTable pdfinvoiceAmountTable = CreateInvoiceAmountDetailsGrid();
                outerInvoiceDetails.AddCell(pdfinvoiceAmountTable);
                PdfPTable pdfNotes = CreateNotesGrid();
                //Adding all tables to the document
                document.Add(outerHeader);
                document.Add(outerAddress);
                document.Add(pdfProductTable);
                document.Add(outerInvoiceDetails);
                document.Add(pdfNotes);
                document.Close();
            }
            catch (Exception ex)
            {
                if (document.IsOpen())
                {
                    document.CloseDocument();
                }

                MessageBox.Show("Error previwing Invoice :" + ex.Message);
            }
        }
        /// <summary>
        /// Generates the PDF.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <returns>
        /// The pdf in bytes.
        /// </returns>
        public static byte[] GeneratePdf(PageData page)
        {
            List<KeyValuePair<string, string>> propertyValues = page.GetPropertyValues();

            IContentRepository contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
            PageData startPage = contentRepository.Get<PageData>(ContentReference.StartPage);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (Document document = new Document(PageSize.A4))
                {
                    PdfWriter.GetInstance(document, memoryStream);

                    document.AddCreationDate();

                    string author = page["Author"] as string;
                    string title = page["Title"] as string;
                    XhtmlString pdfHeader = startPage["PdfHeader"] as XhtmlString;
                    XhtmlString pdfFooter = startPage["PdfFooter"] as XhtmlString;

                    if (!string.IsNullOrWhiteSpace(author))
                    {
                        document.AddAuthor(author);
                    }

                    document.AddTitle(!string.IsNullOrWhiteSpace(title) ? title : page.Name);

                    document.Open();

                    Dictionary<string, object> providers = new Dictionary<string, object>
                                                               {
                                                                   {
                                                                       HTMLWorker.IMG_PROVIDER,
                                                                       new ImageProvider(
                                                                       document)
                                                                   }
                                                               };

                    StyleSheet styleSheet = OutputHelper.GetStyleSheet();

                    try
                    {
                        Paragraph paragraph = new Paragraph(!string.IsNullOrWhiteSpace(title) ? title : page.Name);
                        document.Add(paragraph);

                        // Add the header
                        if (pdfHeader != null && !pdfHeader.IsEmpty)
                        {
                            using (StringReader stringReader = new StringReader(pdfHeader.ToHtmlString()))
                            {
                                foreach (IElement element in
                                    HTMLWorker.ParseToList(stringReader, styleSheet, providers))
                                {
                                    document.Add(element);
                                }
                            }
                        }

                        // Add the selected properties
                        foreach (KeyValuePair<string, string> content in propertyValues)
                        {
                            using (StringReader stringReader = new StringReader(content.Value))
                            {
                                foreach (IElement element in
                                    HTMLWorker.ParseToList(stringReader, styleSheet, providers))
                                {
                                    document.Add(element);
                                }
                            }
                            
                            document.Add(new Chunk(Environment.NewLine));
                        }

                        // Add the footer
                        if (pdfFooter != null && !pdfFooter.IsEmpty)
                        {
                            using (StringReader stringReader = new StringReader(pdfFooter.ToHtmlString()))
                            {
                                foreach (IElement element in
                                    HTMLWorker.ParseToList(stringReader, styleSheet, providers))
                                {
                                    document.Add(element);
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Paragraph paragraph = new Paragraph("Error!" + exception.Message);
                        Chunk text = paragraph.Chunks[0];
                        if (text != null)
                        {
                            text.Font.Color = BaseColor.RED;
                        }

                        document.Add(paragraph);
                    }

                    document.CloseDocument();
                }

                return memoryStream.ToArray();
            }
        }
Exemplo n.º 12
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);
    }
Exemplo n.º 13
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);
    }
Exemplo n.º 14
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);
    }
Exemplo n.º 15
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);
    }
Exemplo n.º 16
0
 /// <summary>
 /// 保存PDF文件
 /// </summary>
 /// <param name="filename"></param>
 public void Save(string filename)
 {
     m_doc.CloseDocument();
     m_stream.Flush();
     System.IO.File.WriteAllBytes(filename, m_stream.GetBuffer());
 }
Exemplo n.º 17
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);
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.Form["type"] != null && Request.Form["svg"] != null && Request.Form["filename"] != null)
                {
                    string tType = Request.Form["type"].ToString();
                    string tSvg = Request.Form["svg"].ToString();
                    string tFileName = Request.Form["filename"].ToString();

                    if (tFileName == "")
                    {
                        tFileName = "chart";
                    }

                    string tTmp = new Random().Next().ToString();

                    string tExt = "";
                    string tTypeString = "";

                    switch (tType)
                    {
                        case "image/png":
                            tTypeString = "-m image/png";
                            tExt = "png";
                            break;
                        case "image/jpeg":
                            tTypeString = "-m image/jpeg";
                            tExt = "jpg";
                            break;
                        case "application/pdf":
                            tTypeString = "-m application/pdf";
                            tExt = "pdf";
                            break;
                        case "image/svg+xml":
                            tTypeString = "-m image/svg+xml";
                            tExt = "svg";
                            break;
                    }

                    string tSvgOuputFile = tTmp + "." + "svg";
                    string tOutputFile = tTmp + "." + tExt;

                    if (tTypeString != "")
                    {
                        string tWidth = Request.Form["width"].ToString();
                        //WRITING SVG TO DISK
                        StreamWriter tSw = new StreamWriter(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                        tSw.Write(tSvg);
                        tSw.Close();
                        tSw.Dispose();

                        Svg.SvgDocument tSvgObj = SvgDocument.Open(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);

                        switch (tExt)
                        {
                            case "jpg":
                                tSvgObj.Draw().Save(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile, ImageFormat.Jpeg);
                                //DELETING SVG FILE 
                                if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))
                                {
                                    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                                }
                                break;
                            case "png":
                                tSvgObj.Draw().Save(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile, ImageFormat.Png);
                                //DELETING SVG FILE
                                if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))
                                {
                                    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                                }
                                break;
                            case "pdf":

                                PdfWriter tWriter = null;
                                Document tDocumentPdf = null;
                                try
                                {
                                    // First step saving png that would be used in pdf
                                    tSvgObj.Draw().Save(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png", ImageFormat.Png);

                                    // Creating pdf document
                                    tDocumentPdf = new Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));
                                    // setting up margin to full screen image
                                    tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);
                                    // creating image
                                    iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png");
                                    tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                                    // Insert content
                                    tWriter = PdfWriter.GetInstance(tDocumentPdf, new FileStream(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile, FileMode.Create));
                                    tDocumentPdf.Open();
                                    tDocumentPdf.NewPage();
                                    tDocumentPdf.Add(tGraph);
                                    tDocumentPdf.CloseDocument();

                                    // deleting png
                                    if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png"))
                                    {
                                        File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png");
                                    }

                                    // deleting svg
                                    if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))
                                    {
                                        File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                                    }

                                }
                                catch (Exception ex)
                                {
                                    throw ex;

                                }
                                finally
                                {
                                    tDocumentPdf.Close();
                                    tDocumentPdf.Dispose();
                                    tWriter.Close();
                                    tWriter.Dispose();

                                }


                                break;

                            case "svg":
                                tOutputFile = tSvgOuputFile;
                                break;
                        }





                        if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile))
                        {

                            //Putting session to be able to delete file in temp directory
                            Session["sFileToTransmit_highcharts_export"] = File.ReadAllBytes(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile);
                            //First step deleting disk file;
                            File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile);
                            
                            Response.ClearContent();
                            Response.ClearHeaders();
                            Response.ContentType = tType;
                            Response.AppendHeader("Content-Disposition", "attachment; filename=" + tFileName + "." + tExt + "");
                            Response.BinaryWrite((byte[])Session["sFileToTransmit_highcharts_export"]);
                            Response.End();
                        }

                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.Form["type"] != null && Request.Form["svg"] != null && Request.Form["filename"] != null)
                {
                    string tType = Request.Form["type"].ToString();
                    string tSvg = Request.Form["svg"].ToString();
                    string tFileName = Request.Form["filename"].ToString();
                    if (tFileName == "") tFileName = "chart";

                    MemoryStream data = new MemoryStream(Encoding.ASCII.GetBytes(tSvg));
                    MemoryStream stream = new MemoryStream();

                    switch (tType)
                    {
                        case "image/png":
                            tFileName += ".png";
                            SvgDocument.Open(data).Draw().Save(stream, ImageFormat.Png);
                            break;
                        case "image/jpeg":
                            tFileName += ".jpg";
                            SvgDocument.Open(data).Draw().Save(stream, ImageFormat.Jpeg);
                            break;
                        case "image/svg+xml":
                            tFileName += ".svg";
                            stream = data;
                            break;
                        case "application/pdf":
                            tFileName += ".pdf";

                            PdfWriter tWriter = null;
                            Document tDocumentPdf = null;
                            try
                            {
                                SvgDocument tSvgObj = SvgDocument.Open(data);

                                tSvgObj.Draw().Save(stream, ImageFormat.Png);

                                // Creating pdf document
                                tDocumentPdf = new Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));

                                // setting up margin to full screen image
                                tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);

                                // creating image
                                iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(stream.ToArray());
                                tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                                stream = new MemoryStream();

                                // create writer
                                tWriter = PdfWriter.GetInstance(tDocumentPdf, stream);

                                tDocumentPdf.Open();
                                tDocumentPdf.NewPage();
                                tDocumentPdf.Add(tGraph);
                                tDocumentPdf.CloseDocument();
                                tDocumentPdf.Close();
                            }
                            catch (Exception ex)
                            {
                                throw ex;

                            }
                            finally
                            {
                                tDocumentPdf.Close();
                                tDocumentPdf.Dispose();
                                tWriter.Close();
                                tWriter.Dispose();
                            }
                            break;
                    }

                    if (stream != null)
                    {
                        Response.ClearContent();
                        Response.ClearHeaders();
                        Response.ContentType = tType;
                        Response.AppendHeader("Content-Disposition", "attachment; filename=" + tFileName);
                        Response.BinaryWrite(stream.ToArray());
                        Response.End();
                    }
                }
            }
        }
Exemplo n.º 20
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);
    }
Exemplo n.º 21
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);
    }