예제 #1
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);
    }
예제 #2
0
    public static ActionResult PDF(
        int companyId,
        string from,
        string to,
        long rulesId,
        long processId,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

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

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

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

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

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

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

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

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

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

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

        #region texts

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

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

        string typetext = Dictionary["Common_All_Male_Plural"];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        var presupuestoId = Request.QueryString["presupuestoId"];
        var centro        = HttpContext.Current.Session["user"] as ApplicationUser;
        var polizaId      = Request.QueryString["polizaId"];
        var poliza        = Poliza.ById(polizaId);
        var dictionary    = ApplicationDictionary.Load("es");

        var path = HttpContext.Current.Request.PhysicalApplicationPath;

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

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}.pdf",
            dictionary["Item_Prespuesto"],
            Guid.NewGuid());

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

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

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

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

        document.Open();

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

        document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
        document.Add(new Paragraph("N.I.F: " + centro.NIF, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph(centro.CP + ", " + centro.Poblacion, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph("Telf.: " + centro.Telefono1, FontFactory.GetFont(FontFactory.HELVETICA, 8)));

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

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

        table.SetWidths(new float[] { 30f, 30f });
        var labelFont = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL);
        var totalFont = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.NORMAL);
        var dataFont  = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD);

        var presupuestoCodigo = string.Empty;
        var presupuestoFecha  = string.Empty;

        var aseguradoNombre    = poliza.AseguradoNombre;
        var aseguradoDireccion = string.Empty;
        var aseguradoCP        = string.Empty;
        var aseguradoPoblacion = string.Empty;
        var aseguradoProvincia = string.Empty;
        var aseguradoNIF       = poliza.AseguradoNIF;
        var observaciones      = string.Empty;

        // Linea Total
        string  impuestoText = dictionary["PDF_IVA"] + " " + ConfigurationManager.AppSettings["IVA"].ToString() + "%";
        decimal impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["IVA"].ToString());

        if (centro.Provincia.IndexOf("tenerife", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("canaria", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("las palmas", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_IGIC"] + " " + ConfigurationManager.AppSettings["IGIC"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["IGIC"].ToString());
        }

        if (centro.Provincia.IndexOf("melilla", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_Melilla"] + " " + ConfigurationManager.AppSettings["Melilla"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["Melilla"].ToString());
        }

        if (centro.Provincia.IndexOf("ceuta", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_Ceuta"] + " " + ConfigurationManager.AppSettings["Ceuta"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["Ceuta"].ToString());
        }

        var tableObservaciones = new PdfPTable(2)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        var tableCostsAspad = new PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 10f
        };

        var tableCostsPropios = new PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 10f,
            SpacingAfter        = 20f
        };

        tableObservaciones.SetWidths(new float[] { 1f, 3f });
        tableCostsAspad.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f });
        tableCostsPropios.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f });

        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Especialidad"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Concepto"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Cantidad"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Base"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Dto"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Importe"]));

        /* CREATE PROCEDURE ASPADLAND_GetPresupuestoPendienteByPresupuestoId
         *   @PresupuestoId uniqueidentifier,
         *   @CentroId nvarchar(50) */
        bool    propios            = false;
        bool    hasObservaciones   = false;
        decimal totalBaseCost      = 0;
        decimal totalBaseCostASPAD = 0;

        using (var cmd = new SqlCommand("ASPADLAND_Salesforce_GetPresupuestoPendienteByPresupuestoId"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString))
            {
                cmd.Connection = cnn;
                cmd.Parameters.Add(DataParameter.Input("@PresupuestoId", presupuestoId));
                cmd.Parameters.Add(DataParameter.Input("@CentroId", centro.Id));
                try
                {
                    cmd.Connection.Open();
                    using (var rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            observaciones     = rdr.GetString(9);
                            presupuestoCodigo = rdr.GetString(1);
                            presupuestoFecha  = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", rdr.GetDateTime(7));

                            string amountText        = string.Empty;
                            string totalRowText      = string.Empty;
                            string actoObservaciones = rdr.GetString(10);
                            var    especialidad      = rdr.GetString(4);

                            decimal finalAmount = 0M;
                            if (!rdr.IsDBNull(5))
                            {
                                finalAmount = rdr.GetDecimal(5);

                                if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                                {
                                    finalAmount = finalAmount / (1 + impuesto / 100);
                                }

                                amountText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");

                                totalRowText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");
                            }

                            var dto = string.Empty;
                            if (!rdr.IsDBNull(6))
                            {
                                decimal dtoAmount = rdr.GetDecimal(6);
                                finalAmount = finalAmount / (1 + impuesto / 100);

                                amountText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");

                                finalAmount = finalAmount * (100 - dtoAmount) / 100;
                                dto         = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} %",
                                    dtoAmount).Replace(",", ".");
                                totalRowText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");
                            }

                            if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                            {
                                totalBaseCost += finalAmount;
                            }
                            else
                            {
                                totalBaseCostASPAD += finalAmount;
                            }

                            if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                            {
                                if (!propios)
                                {
                                    tableCostsPropios.AddCell(new PdfPCell(new Phrase(dictionary["PDF_Actospropios"], ToolsPdf.TimesBold))
                                    {
                                        Border              = ToolsPdf.BorderBottom,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0,
                                        Colspan             = 6
                                    });
                                }

                                tableCostsPropios.AddCell(ToolsPdf.DataCell(especialidad, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(1, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(amountText, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dto, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont));
                                propios = true;

                                if (!string.IsNullOrEmpty(actoObservaciones))
                                {
                                    hasObservaciones = true;
                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });

                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });
                                }
                            }
                            else
                            {
                                tableCostsAspad.AddCell(ToolsPdf.DataCell(especialidad, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(1, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(amountText, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dto, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont));

                                if (!string.IsNullOrEmpty(actoObservaciones))
                                {
                                    hasObservaciones = true;
                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });

                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (cmd.Connection.State != ConnectionState.Closed)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }

        var la1 = new Chunk(dictionary["PDF_Albaran"] + ": ", labelFont);
        var la2 = new Chunk(presupuestoCodigo + Environment.NewLine, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD));
        var la3 = new Chunk(dictionary["PDF_Fecha"] + ": ", labelFont);
        var la4 = new Chunk(presupuestoFecha, dataFont);

        var p1 = new Paragraph
        {
            la1,
            la2,
            la3,
            la4
        };

        document.Add(new Paragraph(Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine));

        var lb1 = new Chunk(aseguradoNombre + Environment.NewLine, dataFont);
        var lb2 = new Chunk(dictionary["PDF_Poliza"] + ": ", labelFont);
        var lb3 = new Chunk(poliza.Numero + Environment.NewLine, dataFont);

        var p2 = new Paragraph
        {
            lb1,
            lb2,
            lb3
        };

        var cell1 = new PdfPCell {
            Border = ToolsPdf.BorderNone
        };
        var cell2 = new PdfPCell {
            Border = ToolsPdf.BorderNone
        };

        cell1.AddElement(p1);
        cell2.AddElement(p2);


        table.AddCell(cell1);
        table.AddCell(cell2);

        document.Add(table);

        decimal baseIvaASPAD     = totalBaseCostASPAD * impuesto / 100;
        string  baseIvaTextASPAD = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIvaASPAD).Replace(",", ".");
        string  totalASPAD       = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD + baseIvaASPAD).Replace(",", ".");

        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"] + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD).Replace(",", "."), totalFont));

        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(baseIvaTextASPAD, totalFont));

        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalASPAD, totalFont));
        document.Add(tableCostsAspad);

        if (propios)
        {
            decimal baseIva     = totalBaseCost * impuesto / 100;
            string  baseIvaText = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIva).Replace(",", ".");
            string  total       = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva).Replace(",", ".");

            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"], labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost).Replace(",", "."), totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(baseIvaText, totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(total, totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));

            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(dictionary["PDF_Total"] + ":"));
            string superTotal = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva + totalBaseCostASPAD + baseIvaASPAD).Replace(",", ".");
            tableCostsPropios.AddCell(TotalCell(superTotal));

            document.Add(tableCostsPropios);
        }

        if (!string.IsNullOrEmpty(observaciones))
        {
            document.Add(new Paragraph("Observaciones", ToolsPdf.TimesBold));
            document.Add(new Paragraph(observaciones, labelFont));
        }

        if (hasObservaciones)
        {
            document.Add(tableObservaciones);
        }

        document.Add(new Phrase(dictionary["Item_Presupuesto_Print_Caducity"], ToolsPdf.TimesLittle));

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }