SetWidths() public method

public SetWidths ( float relativeWidths ) : void
relativeWidths float
return void
        protected virtual void WriteTOC(List<PdfContentParameter> contents, PdfWriter writer, Document document)
        {
            document.NewPage();
            PdfPTable t = new PdfPTable(2);
            t.WidthPercentage = 100;
            t.SetWidths(new float[] { 98f, 2f });
            t.TotalWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
            t.AddCell(new PdfPCell(
                new Phrase(GlobalStringResource.TableOfContents,
                    FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16))
                ) { Colspan = 2, Border = Rectangle.NO_BORDER, PaddingBottom = 25 });

            foreach (PdfContentParameter item in contents)
            {
                if (!string.IsNullOrEmpty(item.Header))
                {
                    t.AddCell(
                        new PdfPCell(
                                new Phrase(item.Header,
                                    FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8)
                                    )
                            ) { Border = Rectangle.NO_BORDER, NoWrap = false, FixedHeight = 15, }
                        );

                    PdfPCell templateCell = new PdfPCell(Image.GetInstance(item.Template));
                    templateCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    templateCell.Border = Rectangle.NO_BORDER;
                    t.AddCell(templateCell);
                }
            }
            float docHeight = document.PageSize.Height - heightOffset;
            document.Add(t);
        }
Example #2
0
        public void AddTable(List <CellRow> tableRows, float[] cellWidths)
        {
            iPdf.PdfPTable table = new iPdf.PdfPTable(cellWidths.Length);
            for (int i = 0; i < cellWidths.Length; i++)
            {
                table.AbsoluteWidths[i] = cellWidths[i];
            }
            table.WidthPercentage = 100F;
            table.SetWidths(cellWidths);
            table.SpacingBefore      = 10F;
            table.SpacingAfter       = 10F;
            table.SplitRows          = false;
            table.SplitLate          = false;
            table.DefaultCell.Border = 0;             //

            foreach (CellRow row in tableRows)
            {
                for (int i = 0; i < row.CellTexts.Length; i++)
                {
                    iText.Chunk cellChunk = new iText.Chunk(row.CellTexts[i]);
                    cellChunk.Font = iText.FontFactory.GetFont(baseFont, row.IsRowImportant ? leadSize : normalSize, row.CellBolds[i] ? iText.Font.BOLD : iText.Font.NORMAL);
                    iPdf.PdfPCell cell = new iPdf.PdfPCell(new iText.Phrase(cellChunk));
                    //cell.Width = (float)(cellWidths[i] * (document.PageSize.Width / 100));
                    cell.Border = iText.Rectangle.NO_BORDER;
                    cell.NoWrap = false;
                    table.AddCell(cell);
                }
            }
            table.SetWidths(cellWidths);
            document.Add(table);
        }
Example #3
0
 public void GenerarDocumento(Document document)
 {
     int i, j;
     PdfPTable datatable = new PdfPTable(dataGridView1.ColumnCount);
     datatable.DefaultCell.Padding = 3;
     float[] headerwidths = GetTamañoColumnas(dataGridView1);
     datatable.SetWidths(headerwidths);
     datatable.WidthPercentage = 100;
     datatable.DefaultCell.BorderWidth = 2;
     datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
     for (i = 0; i < dataGridView1.ColumnCount; i++)
     {
         datatable.AddCell(dataGridView1.Columns[i].HeaderText);
     }
     datatable.HeaderRows = 1;
     datatable.DefaultCell.BorderWidth = 1;
     for (i = 0; i < dataGridView1.Rows.Count; i++)
     {
         for (j = 0; j < dataGridView1.Columns.Count; j++)
         {
             if (dataGridView1[j, i].Value != null)
             {
                 datatable.AddCell(new Phrase(dataGridView1[j, i].Value.ToString()));//En esta parte, se esta agregando un renglon por cada registro en el datagrid
             }
         }
         datatable.CompleteRow();
     }
     document.Add(datatable);
 }
 public void CreatePdf(String dest)
 {
     Document document = new Document();
     PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create));
     document.Open();
     PdfPTable table = new PdfPTable(5);
     table.SetWidths(new int[] {1, 2, 2, 2, 1});
     PdfPCell cell;
     cell = new PdfPCell(new Phrase("S/N"));
     cell.Rowspan = 2;
     table.AddCell(cell);
     cell = new PdfPCell(new Phrase("Name"));
     cell.Colspan = 3;
     table.AddCell(cell);
     cell = new PdfPCell(new Phrase("Age"));
     cell.Rowspan = 2;
     table.AddCell(cell);
     table.AddCell("SURNAME");
     table.AddCell("FIRST NAME");
     table.AddCell("MIDDLE NAME");
     table.AddCell("1");
     table.AddCell("James");
     table.AddCell("Fish");
     table.AddCell("Stone");
     table.AddCell("17");
     document.Add(table);
     document.Close();
 }
Example #5
0
        public virtual void Rowspan_Test() {
            String file = "rowspantest.pdf";

            string fileE = CMP_FOLDER + file;
            Console.Write(File.Exists(fileE));
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OUTPUT_FOLDER + file, FileMode.Create));
            document.Open();
            PdfContentByte contentByte = writer.DirectContent;

            Rectangle rect = document.PageSize;

            PdfPTable table = new PdfPTable(4);

            table.TotalWidth = rect.Right - rect.Left + 1;
            table.LockedWidth = true;

            float[] widths = new float[] {
                0.1f, 0.54f, 0.12f, 0.25f
            };

            table.SetWidths(widths);

            PdfPCell cell_1_1 = new PdfPCell(new Phrase("1-1"));
            cell_1_1.Colspan = 4;
            table.AddCell(cell_1_1);

            PdfPCell cell_2_1 = new PdfPCell(new Phrase("2-1"));
            cell_2_1.Rowspan = 2;
            table.AddCell(cell_2_1);

            PdfPCell cell_2_2 = new PdfPCell(new Phrase("2-2"));
            cell_2_2.Colspan = 2;
            table.AddCell(cell_2_2);

            PdfPCell cell_2_4 = new PdfPCell(new Phrase("2-4"));
            cell_2_4.Rowspan = 3;
            table.AddCell(cell_2_4);

            PdfPCell cell_3_2 = new PdfPCell(new Phrase("3-2"));
            table.AddCell(cell_3_2);

            PdfPCell cell_3_3 = new PdfPCell(new Phrase("3-3"));
            table.AddCell(cell_3_3);

            PdfPCell cell_4_1 = new PdfPCell(new Phrase("4-1"));
            cell_4_1.Colspan = 3;
            table.AddCell(cell_4_1);

            table.WriteSelectedRows(0, -1, rect.Left, rect.Top, contentByte);

            document.Close();

            // compare
            CompareTool compareTool = new CompareTool(OUTPUT_FOLDER + file, CMP_FOLDER + file);
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
        private void GenerateData(Document document, TravelAgencyDbContext dbContext)
        {
            var excursions = dbContext
                .Excursions
                .Select(x => new ReportExcursion()
                {
                    ExcName = x.Name,
                    Destination = x.Destination.Country,
                    Distance = x.Destination.Distance.ToString(),
                    ClientCount = x.Clients,
                    StartDate = x.StartDate,
                    EndDate = x.EndDate,
                    Guide = x.Guide.Name,
                    Experience = x.Guide.Experience
                })
                .ToList();

            PdfPTable table = new PdfPTable(5);

            int[] widths = new int[] { 20, 20, 20, 15, 11 };

            table.SetWidths(widths);

            table.AddCell(this.CreateCell(new Phrase("Excursion name"), true));
            table.AddCell(this.CreateCell(new Phrase("Destination"), true));
            table.AddCell(this.CreateCell(new Phrase("Clients count"), true));
            table.AddCell(this.CreateCell(new Phrase("Clients satisfaction"), true));
            table.AddCell(this.CreateCell(new Phrase("Duration in days"), true));

            this.InputData(excursions, table);

            document.Add(table);
        }
        private static PdfPTable CreateTable()
        {
            PdfPTable table = new PdfPTable(2);
            //actual width of table in points
            table.TotalWidth = 216f;
            //fix the absolute width of the table
            table.LockedWidth = true;

            //relative col widths in proportions - 1/3 and 2/3
            float[] widths = new float[] { 1f, 2f };
            table.SetWidths(widths);
            table.HorizontalAlignment = 0;
            //leave a gap before and after the table
            table.SpacingBefore = 20f;
            table.SpacingAfter = 30f;

            PdfPCell cell = new PdfPCell(new Phrase("Products"));
            cell.Colspan = 2;
            cell.Border = 0;
            cell.HorizontalAlignment = 1;
            table.AddCell(cell);

            // Seed data:
            for (int i = 0; i < DummySeed.Info.Count; i++)
            {
                table.AddCell(DummySeed.Info[i].Id.ToString());
                table.AddCell(DummySeed.Info[i].Name);
            }

            return table;
        }
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            PdfPTable footer = new PdfPTable(3);
            footer.SetWidths(new float[] { 88f, 7f, 5f });
            footer.WidthPercentage = 100;
            footer.TotalWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);

            PdfPCell emptycell = new PdfPCell();
            emptycell.Border = 0;
            footer.AddCell(emptycell);

            Chunk text = new Chunk(string.Format(GlobalStringResource.PageOfFooter,
                document.PageNumber), FontFactory.GetFont(FontFactory.HELVETICA, 8));

            PdfPCell footerCell = new PdfPCell(new Phrase(text));
            footerCell.Border = 0;
            footerCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            footer.AddCell(footerCell);

            PdfPCell cell = new PdfPCell(iTextSharp.text.Image.GetInstance(total));
            cell.Border = 0;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            footer.AddCell(cell);
            footer.WriteSelectedRows(0, -1, 50, (document.BottomMargin - 10), writer.DirectContent);
        }
        public string ExportToPdf(DateTime startDate, DateTime endDate)
        {
            DataTable dt = this.CreateTableForReport(startDate, endDate);
            Document document = new Document();
            var exportPath = this.exportFileName;
            PdfWriter.GetInstance(document, new FileStream(exportPath, FileMode.Create));
            document.Open();
            Font font7 = FontFactory.GetFont(FontFactory.HELVETICA, 7);
            Font font7bold = FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.BOLD);
            Font font10 = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD);

            PdfPTable table = new PdfPTable(dt.Columns.Count);
            float[] widths = new float[] { 2f, 4f, 3f, 3f, 4f, 3f };

            table.SetWidths(widths);

            table.WidthPercentage = 100;
            PdfPCell cell = new PdfPCell(new Phrase("Products"));

            cell.Colspan = dt.Columns.Count;

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report", font10));
            header.Colspan = 6;
            header.HorizontalAlignment = 1;
            header.VerticalAlignment = 1;
            header.PaddingTop = 10;
            header.PaddingBottom = 10;
            table.AddCell(header);

            foreach (DataColumn c in dt.Columns)
            {
                table.AddCell(new PdfPCell(new Phrase(c.ColumnName, font7bold)) { BackgroundColor = new BaseColor(250, 200, 140), Padding = 2 });
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    table.AddCell(new PdfPCell(new Phrase(r[0].ToString(), font7bold))
                    {
                        Colspan = 6,
                        BackgroundColor = new BaseColor(250, 230, 200),
                        Padding = 2
                    });
                    table.AddCell(new Phrase(""));
                    table.AddCell(new Phrase(r[1].ToString(), font7));
                    table.AddCell(new Phrase(r[2].ToString(), font7));
                    table.AddCell(new Phrase(r[3].ToString(), font7));
                    table.AddCell(new Phrase(r[4].ToString(), font7));
                    table.AddCell(new PdfPCell(new Phrase(r[5].ToString(), font7))
                    {
                        BackgroundColor = new BaseColor(250, 200, 140),
                        Padding = 2
                    });
                }
            }
            document.Add(table);
            document.Close();
            return ExportPdfReportSuccess;
        }
        public FileStreamResult AttendByRank(int tournamentId)
        {
            InitDocument();

            document.Open();

            PdfPTable headerTable = new PdfPTable(2);
            headerTable.HorizontalAlignment = Element.ALIGN_LEFT;
            headerTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            headerTable.DefaultCell.Border = Rectangle.NO_BORDER;
            headerTable.WidthPercentage = 100f;
            headerTable.SetWidths(new float[] { 10, 90 });

            headerTable.AddCell(Image.GetInstance(Server.MapPath("/Content/images/reportLogo.gif")));
            headerTable.AddCell(new Phrase("Attendance By Rank", fontH1));

            document.Add(headerTable);

            Font fontRank = new Font(baseFont, 12, Font.BOLD);
            Font fontAgeGroup = new Font(baseFont, 10, Font.BOLD);

            IEnumerable<CompetitorDivision> competitorDivisions = db.CompetitorDivisions.Where(m => m.Competitor.TournamentId == tournamentId).OrderBy(m => m.Division.RankId).ThenBy(m => m.Division.AgeGroupId);

            foreach (IGrouping<int, CompetitorDivision> rankDivisions in competitorDivisions.ToLookup(m => m.Division.RankId))
            {
                PdfPTable rankTable = new PdfPTable(4);
                rankTable.SpacingBefore = 10f;
                rankTable.HorizontalAlignment = Element.ALIGN_LEFT;
                rankTable.WidthPercentage = 100f;
                rankTable.DefaultCell.Border = Rectangle.NO_BORDER;
                rankTable.SetWidths(new float[] { 70, 10, 10, 10 });

                Rank rank = rankDivisions.First().Division.Rank;

                rankTable.AddCell(new Phrase(rank.Description, fontRank));
                rankTable.AddCell(new Phrase("Total", fontRank));
                rankTable.AddCell(new Phrase("M", fontRank));
                rankTable.AddCell(new Phrase("F", fontRank));

                foreach (IGrouping<int, CompetitorDivision> ageGroupDivisions in rankDivisions.Where(m => !m.Division.AgeGroup.IsSparringGroup).ToLookup(m => m.Division.AgeGroupId))
                {
                    AgeGroup ageGroup = ageGroupDivisions.First().Division.AgeGroup;
                    PdfPCell ageGroupCell = iTextSharpHelper.CreateCell(ageGroup.Description, fontAgeGroup, 0, Element.ALIGN_LEFT, null);
                    ageGroupCell.Colspan = 4;
                    rankTable.AddCell(ageGroupCell);

                    fillAttendByRankTable(ageGroupDivisions.Where(m => !m.Division.AgeGroup.IsSparringGroup).ToLookup(m => m.DivisionId), rankTable);

                    // Include child age groups for sparring
                    fillAttendByRankTable(db.CompetitorDivisions.Where(m => m.Competitor.TournamentId == tournamentId && m.Division.RankId == rank.RankId & m.Division.AgeGroup.ParentAgeGroupId == ageGroup.AgeGroupId).ToLookup(m => m.DivisionId), rankTable);
                }

                document.Add(rankTable);
            }

            document.Close();

            return getFileStreamResult(ms, "attendancebyrank.pdf");
        }
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         document.Add(new Paragraph("Movies:"));
         IEnumerable<Movie> movies = PojoFactory.GetMovies();
         foreach (Movie movie in movies)
         {
             PdfPTable table = new PdfPTable(2);
             table.SetWidths(new int[] { 1, 4 });
             PdfPCell cell;
             cell = new PdfPCell(new Phrase(movie.Title, FilmFonts.BOLD));
             cell.HorizontalAlignment = Element.ALIGN_CENTER;
             cell.Colspan = 2;
             table.AddCell(cell);
             if (!string.IsNullOrEmpty(movie.OriginalTitle))
             {
                 cell = new PdfPCell(PojoToElementFactory.GetOriginalTitlePhrase(movie));
                 cell.Colspan = 2;
                 cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                 table.AddCell(cell);
             }
             List<Director> directors = movie.Directors;
             cell = new PdfPCell(new Phrase("Directors:"));
             cell.Rowspan = directors.Count;
             cell.VerticalAlignment = Element.ALIGN_MIDDLE;
             table.AddCell(cell);
             int count = 0;
             foreach (Director pojo in directors)
             {
                 cell = new PdfPCell(PojoToElementFactory.GetDirectorPhrase(pojo));
                 cell.Indent = (10 * count++);
                 table.AddCell(cell);
             }
             table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
             table.AddCell("Year:");
             table.AddCell(movie.Year.ToString());
             table.AddCell("Run length:");
             table.AddCell(movie.Duration.ToString());
             List<Country> countries = movie.Countries;
             cell = new PdfPCell(new Phrase("Countries:"));
             cell.Rowspan = countries.Count;
             cell.VerticalAlignment = Element.ALIGN_BOTTOM;
             table.AddCell(cell);
             table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
             foreach (Country country in countries)
             {
                 table.AddCell(country.Name);
             }
             document.Add(table);
         }
     }
 }
Example #12
0
        /// <summary>
        /// This metod create table in the pdf file
        /// </summary>
        public void CreateTable()
        {
            table = new PdfPTable(1);

            table.WidthPercentage = 100;

            table.SetWidths(new float[] { 812 });
        }
        //private void LoadNonFinancialAccountStatement()
        //{
        //    var xSwitch = new Business.XSwitch();
        //    NonFinHistoryGridView.DataSource = xSwitch.getNonFinHistory(Global.ConnectionString, Session["UserId"].ToString());
        //    NonFinHistoryGridView.DataBind();
        //}

        public byte[] ExportToPdf(DataTable dt)
        {
            try
            {
                using (var ms = new MemoryStream())
                {
                    Document document = new Document();
                    var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    document.Open();
                    iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

                    PdfPTable table = new PdfPTable(dt.Columns.Count);
                    PdfPRow row = null;
                    float[] widths = new float[] { 4f, 4f, 4f, 4f, 4f };

                    table.SetWidths(widths);

                    table.WidthPercentage = 100;
                    int iCol = 0;
                    string colname = "";
                    PdfPCell cell = new PdfPCell(new Phrase("Products"));

                    cell.Colspan = dt.Columns.Count;

                    foreach (DataColumn c in dt.Columns)
                    {

                        table.AddCell(new Phrase(c.ColumnName, font5));
                    }

                    foreach (DataRow r in dt.Rows)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            table.AddCell(new Phrase(r[0].ToString(), font5));
                            table.AddCell(new Phrase(r[1].ToString(), font5));
                            table.AddCell(new Phrase(r[2].ToString(), font5));
                            table.AddCell(new Phrase(r[3].ToString(), font5));
                            table.AddCell(new Phrase(r[4].ToString(), font5));
                        }
                    }
                    document.Add(table);
                    document.Close();
                    return ms.ToArray();
                }
               
            }
            catch (Exception ex)
            {
                Master.ErrorMessage = "Error: PDF Creation Failed.";
                Response.Redirect(Request.RawUrl);
                return null;
            }
        }
 public static PdfPTable Table(int column, float[] ratio)
 {
     PdfPTable table = new PdfPTable(column);
     table.TotalWidth = 560f;
     table.LockedWidth = true;
     table.SetWidths(ratio);
     table.HorizontalAlignment = 1;
     table.SpacingBefore = 10f;
     table.SpacingAfter = 10f;
     return table;
 }
Example #15
0
 private PdfPTable CreateAirlineReportsTable()
 {
     PdfPTable table = new PdfPTable(PdfTableSize);
     table.WidthPercentage = 100;
     table.LockedWidth = false;
     float[] widths = new float[] { 3f, 3f, 3f, 3f };
     table.SetWidths(widths);
     table.HorizontalAlignment = 0;
     table.SpacingBefore = 20f;
     table.SpacingAfter = 30f;
     return table;
 }
Example #16
0
        private void btnPrint_Click(object sender, EventArgs e)
        {
            // Create a Document object
            var document = new Document(PageSize.A4, 50, 50, 25, 25);

            string file = "Choo.pdf";
            // Create a new PdfWriter object, specifying the output stream
            var output = new MemoryStream();
            //var writer = PdfWriter.GetInstance(document, output);
            var writer = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create));

            // Open the Document for writing
            document.Open();

            var titleFont = FontFactory.GetFont("Arial", 18);
            var subTitleFont = FontFactory.GetFont("Arial", 14);
            var boldTableFont = FontFactory.GetFont("Arial", 12);
            var endingMessageFont = FontFactory.GetFont("Arial", 10);
            var bodyFont = FontFactory.GetFont("Arial", 12);

            //document.Add(new Paragraph("Northwind Traders Receipt", titleFont);
            Paragraph tit = new Paragraph();
            Chunk c1 = new Chunk("  Ingresos Diarios \n", titleFont);
            Chunk c2 = new Chunk("Ciclo Escolar 2012 - 2013 \n");
            Chunk c3 = new Chunk("Dia consultado : 25/01/2013");
            tit.Add(c1);
            tit.Add(c2);
            tit.Add(c3);
            tit.IndentationLeft = 200f;
            document.Add(tit);

            PdfContentByte cb = writer.DirectContent;
            cb.MoveTo(50, document.PageSize.Height / 2);
            cb.LineTo(document.PageSize.Width - 50, document.PageSize.Height / 2);
            cb.Stroke();

            var orderInfoTable = new PdfPTable(2);
            orderInfoTable.HorizontalAlignment = 0;
            orderInfoTable.SpacingBefore = 10;
            orderInfoTable.SpacingAfter = 10;
            orderInfoTable.DefaultCell.Border = 0;
            orderInfoTable.SetWidths(new int[] { 1, 4 });

            orderInfoTable.AddCell(new Phrase("Order:", boldTableFont));
            orderInfoTable.AddCell("textorder");
            orderInfoTable.AddCell(new Phrase("Price:", boldTableFont));
            orderInfoTable.AddCell(Convert.ToDecimal(444444).ToString("c"));

            document.Add(orderInfoTable);
            document.Close();
            System.Diagnostics.Process.Start(file);
        }
        private PdfPTable GetAllInfoTable()
        {
            PdfPTable table = new PdfPTable(4);
            table.WidthPercentage = 100f;
            table.SetWidths(new int[] { 1, 3, 2, 18 });

            PdfPCell cell;
            Paragraph p;
            int rowNum = 0;
            int textColumNum = 3;

            using (TextFieldParser parser = new TextFieldParser("../../Data/screen.csv", UTF8Encoding.UTF8, true))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();
                    if (rowNum > 0)
                    {
                        for (int i = 0; i < textColumNum; i++)
                        {
                            p = new Paragraph(fields[i], new Font(BF_Light, 10));
                            cell = new PdfPCell(p);
                            cell.Border = Rectangle.NO_BORDER;
                            table.AddCell(cell);
                        }

                        string fileName = string.Format("../../Data/{0}.csv", fields[1]);
                        float yMax = float.Parse(fields[3]);
                        float yScale = float.Parse(fields[4]);

                        cell = new PdfPCell(new Phrase(""));
                        cell.MinimumHeight = 55f;
                        cell.Border = Rectangle.NO_BORDER;
                        //画图的类,和cell关联
                        ResolutionChart chart = new ResolutionChart(fileName, yMax, yScale);
                        cell.CellEvent = chart;
                        table.AddCell (cell);
                        rowNum++;

                    }
                    else
                    {
                        rowNum++;
                    }
                }
            }

            return table;
        }
        public static void CreateCustom(Document document, SimpleInvoiceDetails simpleInvoiceDetails, InvoiceEntity invoiceEntity)
        {
            var table = new PdfPTable(4) { WidthPercentage = 100 };
            var colWidthPercentages = new[] { 1f, 3f, 1f, 1f };
            table.SetWidths(colWidthPercentages);

            var subTotal = simpleInvoiceDetails.Quantity * simpleInvoiceDetails.UnitPrice;

            AddHeader(table);
            AddCustomCost(table, simpleInvoiceDetails, subTotal);
            AddSummary(table, subTotal, subTotal * 0.2);

            document.Add(table);
        }
        public static void CreateWeekly(Document document, WeeklyInvoiceDetails wid, InvoiceEntity invoiceEntity, DateTime now)
        {
            var table = new PdfPTable(4) { WidthPercentage = 100 };
            var colWidthPercentages = new[] { 1f, 3f, 1f, 1f };
            table.SetWidths(colWidthPercentages);

            var subTotal = wid.ChargeableHours * wid.HourlyRate;

            AddHeader(table);
            AddWeekWorkCost(table, wid, invoiceEntity,now);
            AddSummary(table, subTotal, subTotal * 0.2);

            document.Add(table);
        }
Example #20
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;

            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");
            var doc = new Document(PageSize.LETTER, 36, 36, 36, 42);
            var w = PdfWriter.GetInstance(doc, Response.OutputStream);

            var scheduletext = string.Empty;
            var sdt = Organization.GetDateFromScheduleId(model.ScheduleId ?? 0);
            if (sdt.HasValue)
                scheduletext = sdt.Value.ToString("dddd h:mm tt");

            var headtext = $"Checkin Control Report {scheduletext}";
            w.PageEvent = new HeadFoot(headtext);


            var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8);

            doc.Open();

            var t = new PdfPTable(5);
            t.HeaderRows = 1;
            t.WidthPercentage = 100;
            t.SetWidths(new[] {20, 30, 10, 10, 15});

            var font = FontFactory.GetFont(FontFactory.HELVETICA, 8);
            t.AddCell(new Phrase("Name", boldfont));
            t.AddCell(new Phrase("Organization", boldfont));
            t.AddCell(new Phrase("Location", boldfont));
            t.AddCell(new Phrase("MeetingTime", boldfont));
            t.AddCell(new Phrase("Member Type", boldfont));

            foreach (var m in model.list())
            {
                t.AddCell(new Phrase(m.Name, font));
                t.AddCell(new Phrase(m.Organization, font));
                t.AddCell(new Phrase(m.Location, font));
                t.AddCell(new Phrase(m.MeetingTime.ToShortTimeString(), font));
                t.AddCell(new Phrase(m.AttendType, font));
            }
            if (t.Rows.Count > 1)
                doc.Add(t);
            else
                doc.Add(new Phrase("no data"));
            doc.Close();
        }
 public override void OnEndPage(PdfWriter writer, Document document)
 {
     PdfPTable table = new PdfPTable(2);
     table.SetWidths(new float[] { 48, 2 });
     table.TotalWidth = document.PageSize.Width - document.RightMargin - document.LeftMargin;
     table.LockedWidth = true;
     table.DefaultCell.FixedHeight = 20;
     table.DefaultCell.Border = Rectangle.NO_BORDER;
     table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
     table.AddCell(new Phrase(String.Format("Página {0} de", writer.CurrentPageNumber), ffont));
     PdfPCell cell = new PdfPCell(Image.GetInstance(pageCount));
     cell.Border = Rectangle.NO_BORDER;
     table.AddCell(cell);
     table.WriteSelectedRows(0, -1, 34, document.PageSize.Height - (document.TopMargin - 20), writer.DirectContent);
 }
Example #22
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            var document = new Document(PageSize.LETTER);
            document.SetMargins(36f, 36f, 33f, 36f);
            var w = PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();
            dc = w.DirectContent;

            var cols = new float[3 * 2 - 1];
            var twid = 0f;
            var t = new PdfPTable(cols.Length);
            for (var i = 0; i < cols.Length; i++)
                if (i % 2 == 1)
                    cols[i] = GAP * 72f;
                else
                    cols[i] = W * 72f;
            foreach (var wid in cols)
                twid += wid;

            t.TotalWidth = twid;
            t.SetWidths(cols);
            t.HorizontalAlignment = Element.ALIGN_CENTER;
            t.LockedWidth = true;
            t.DefaultCell.Border = PdfPCell.NO_BORDER;

            var q = DbUtil.Db.PeopleQuery(qid);
            var q2 = from p in q
                    orderby p.Name2
                    select new
                    {
                        First = p.PreferredName,
                        Last = p.LastName,
                        PeopleId = p.PeopleId,
                        Phone = p.CellPhone ?? p.HomePhone
                    };
            if (!q2.Any())
                document.Add(new Phrase("no data"));
			else
				foreach (var m in q2)
					AddRow(t, m.First, m.Last, m.Phone, m.PeopleId);
            document.Add(t);

            document.Close();
        }
Example #23
0
        public PdfEngine(IPageLayout layout, string ourCallsign, int firstPageOffset)
        {
            m_OurCallsign = ourCallsign;
            m_Layout = layout;
            m_MainTable = new PdfPTable(m_Layout.Columns);
            m_MainTable.TotalWidth = mm2p(196);
            int[] widths = new int[m_Layout.Columns];
            for (int i = 0; i < m_Layout.Columns; i++)
                widths[i] = 1;
            m_MainTable.SetWidths(widths);

            // Offset the first page by an appropriate number of cells
            for (int i = 0; i < firstPageOffset; i++)
                m_MainTable.AddCell(PopulateCell(new LabelEntry()));
            m_LabelsUsed += firstPageOffset;
        }
        private static void AddPaymentDetails(Document document, InvoiceEntity invoiceEntity)
        {
            var table = new PdfPTable(3) { WidthPercentage = 45 };
            var colWidthPercentages = new[] { 4f, 1f, 5f };
            table.SetWidths(colWidthPercentages);

            table.AddCell(ElementFactory.CreateCell("Name of Account", Element.ALIGN_LEFT, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell(":", Element.ALIGN_CENTER, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell(invoiceEntity.AccountDetails.Name, Element.ALIGN_LEFT, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell("Account Number:", Element.ALIGN_LEFT, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell(":", Element.ALIGN_CENTER, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell(invoiceEntity.AccountDetails.Number, Element.ALIGN_LEFT, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell("Sort Code", Element.ALIGN_LEFT, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell(":", Element.ALIGN_CENTER, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            table.AddCell(ElementFactory.CreateCell(invoiceEntity.AccountDetails.SortCode, Element.ALIGN_LEFT, -1, BaseColor.WHITE, 1, ElementFactory.Fonts.Footer));
            document.Add(table);
        }
Example #25
0
// ---------------------------------------------------------------------------    
    /**
     * Creates a table; widths are set with setWidths().
     * @return a PdfPTable
     * @throws DocumentException
     */
    public static PdfPTable CreateTable1() {
      PdfPTable table = new PdfPTable(3);
      table.WidthPercentage  =288 / 5.23f;
      table.SetWidths(new int[]{2, 1, 1});
      PdfPCell cell;
      cell = new PdfPCell(new Phrase("Table 1"));
      cell.Colspan = 3;
      table.AddCell(cell);
      cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
      cell.Rowspan = 2;
      table.AddCell(cell);
      table.AddCell("row 1; cell 1");
      table.AddCell("row 1; cell 2");
      table.AddCell("row 2; cell 1");
      table.AddCell("row 2; cell 2");
      return table;
    }
 protected void AddHeader(Document doc)
 {
     Font headerFont = FontFactory.GetFont("Arial", 16, Color.GRAY);
     PdfPTable table = new PdfPTable(2);
     table.SetWidths(new float[] { 15f, 85f });
     table.WidthPercentage = 100;
     table.DefaultCell.Border = Rectangle.BOX;
     table.DefaultCell.BorderColor = Color.GRAY;
     table.DefaultCell.HorizontalAlignment = Table.ALIGN_CENTER;
     table.DefaultCell.VerticalAlignment = Table.ALIGN_MIDDLE;
     table.SpacingAfter = 10f;
     //table.DefaultCell. = 20;
     table.AddCell(new Phrase(docSerial, headerFont));
     table.DefaultCell.Border = Rectangle.NO_BORDER;
     table.AddCell(new Phrase(documentName.ToUpper() + "\n(GENERIC RISK ASSESSMENT)",headerFont));
     doc.Add(table);
 }
Example #27
0
// ---------------------------------------------------------------------------    
    /**
     * Creates a table; widths are set with setWidths().
     * @return a PdfPTable
     * @throws DocumentException
     */
    public static PdfPTable CreateTable2() {
      PdfPTable table = new PdfPTable(3);
      table.TotalWidth = 288;
      table.LockedWidth = true;
      table.SetWidths(new float[]{2, 1, 1});
      PdfPCell cell;
      cell = new PdfPCell(new Phrase("Table 2"));
      cell.Colspan = 3;
      table.AddCell(cell);
      cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
      cell.Rowspan = 2;
      table.AddCell(cell);
      table.AddCell("row 1; cell 1");
      table.AddCell("row 1; cell 2");
      table.AddCell("row 2; cell 1");
      table.AddCell("row 2; cell 2");
      return table;
    }
Example #28
0
		public static PdfPCell GetImageTextCell(string imageSource, string text, float partial, BaseColor background = null)
		{
			var image = GetImage(imageSource);
			var nestedTable = new PdfPTable(2);
			nestedTable.SetWidths(new float[] { 1f, partial });
			nestedTable.DefaultCell.Border = 0;
			if (image == null)
				nestedTable.AddCell("");
			else
				nestedTable.AddCell(image);
			nestedTable.AddCell(new Phrase(text, PDFStyle.NormalFont));

			return new PdfPCell(nestedTable)
			{
				Padding = 0,
				BackgroundColor = background
			};
		}
Example #29
0
 // ---------------------------------------------------------------------------   
 /**
  * Create a table with information about a movie.
  * @param screening a Screening
  * @return a table
  */
 private PdfPTable GetTable(Screening screening)
 {
     // Create a table with 4 columns
     PdfPTable table = new PdfPTable(4);
     table.SetWidths(new int[] { 1, 5, 10, 10 });
     // Get the movie
     Movie movie = screening.movie;
     // A cell with the title as a nested table spanning the complete row
     PdfPCell cell = new PdfPCell();
     // nesting is done with addElement() in this example
     cell.AddElement(FullTitle(screening));
     cell.Colspan = 4;
     cell.Border = PdfPCell.NO_BORDER;
     BaseColor color = WebColors.GetRGBColor(
       "#" + movie.entry.category.color
     );
     cell.BackgroundColor = color;
     table.AddCell(cell);
     // empty cell
     cell = new PdfPCell();
     cell.Border = PdfPCell.NO_BORDER;
     cell.UseAscender = true;
     cell.UseDescender = true;
     table.AddCell(cell);
     // cell with the movie poster
     cell = new PdfPCell(GetImage(movie.Imdb));
     cell.Border = PdfPCell.NO_BORDER;
     table.AddCell(cell);
     // cell with the list of directors
     cell = new PdfPCell();
     cell.AddElement(PojoToElementFactory.GetDirectorList(movie));
     cell.Border = PdfPCell.NO_BORDER;
     cell.UseAscender = true;
     cell.UseDescender = true;
     table.AddCell(cell);
     // cell with the list of countries
     cell = new PdfPCell();
     cell.AddElement(PojoToElementFactory.GetCountryList(movie));
     cell.Border = PdfPCell.NO_BORDER;
     cell.UseAscender = true;
     cell.UseDescender = true;
     table.AddCell(cell);
     return table;
 }
 public override void OnEndPage(PdfWriter writer, Document document)
 {
     PdfPTable table = new PdfPTable(3);
     try
     {
         table.SetWidths(new int[] { 24, 24, 2 });
         table.TotalWidth = 527;
         table.LockedWidth = true;
         table.DefaultCell.FixedHeight = 20;
         table.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
         table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
         table.AddCell(string.Format("{0}", writer.PageNumber));
         table.WriteSelectedRows(0, -1, 34, 803, writer.DirectContent);
     }
     catch (DocumentException de)
     {
         throw de;
     }
 }
Example #31
0
        private static void SetTable(Document doc, string title, Dictionary <string, string> rowItems)
        {
            var table = new iTextSharp.text.pdf.PdfPTable(2);

            table.WidthPercentage = 100;

            float[] widths = new float[] { 2f, 1f };
            table.SetWidths(widths);

            // table title
            var titleCell = new PdfPCell(new Phrase(title, fontTableHeader))
            {
                Colspan             = 2,
                MinimumHeight       = 28f,
                BackgroundColor     = lightblue,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(titleCell);

            // table rows
            var itemsCount = 0;

            foreach (var item in rowItems)
            {
                var color = itemsCount % 2 == 0
                        ? BaseColor.WHITE : lightblue;

                SetRowCell(table, item.Key, Element.ALIGN_LEFT, color);

                SetRowCell(table, string.IsNullOrEmpty(item.Value) ? "-" : item.Value, Element.ALIGN_RIGHT, color);

                itemsCount++;
            }

            doc.Add(table);

            // Empty rows after title
            doc.Add(new Paragraph(" "));
        }
Example #32
0
        public void SetHeader(DateTime data, string casa, string tipoEvento, string homenageados, int pax, string horario, string cerimonial, string produtor, string contatoProdutor, string assessoria, string contatoAssessoria, string responsavel, string contatoResponsavel, string perfil)
        {
            header = new iPdf.PdfPTable(3);
            header.WidthPercentage = 100F;
            header.SetWidths(new float[] { 1F, 1F, 1F });
            header.SpacingBefore = 10F;
            header.SpacingAfter  = 10F;

            iText.Chunk headChunk = new iText.Chunk(
                string.Format("{0} > {1} > {2} > {3}", data.ToString("dd/MM/yyyy"), casa, tipoEvento, homenageados));
            headChunk.Font = iText.FontFactory.GetFont(baseFont, leadSize, iText.Font.BOLD);
            iPdf.PdfPCell headerCell = new iPdf.PdfPCell(new iText.Phrase(headChunk));
            headerCell.Colspan = 3;
            header.AddCell(headerCell);

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Pax: ", string.Format("{0} +10% ({1})", pax, (int)(pax * 1.1)))));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Horário:", horario)));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Cerimonial: ", cerimonial)));

            iPdf.PdfPCell detailCell = new iPdf.PdfPCell(MakePhrase("Observações: ", perfil));
            detailCell.Rowspan = 3;
            header.AddCell(new iPdf.PdfPCell(detailCell));

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Produtor(a): ", produtor)));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Contato: ", contatoProdutor)));

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Assessoria: ", assessoria)));
            if (string.IsNullOrEmpty(contatoAssessoria))
            {
                header.AddCell(new iPdf.PdfPCell(new iText.Phrase("")));
            }
            else
            {
                header.AddCell(new iPdf.PdfPCell(MakePhrase("Contato: ", contatoAssessoria)));
            }

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Responsável(a): ", responsavel)));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Contato: ", contatoResponsavel)));
        }
Example #33
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);
    }
Example #34
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);
    }
Example #35
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);
    }
Example #36
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);
    }
        protected void btnExportToPdf_Click(object sender, EventArgs e)
        {
            try
            {
                grdLandRelatedDoc.AllowPaging = false;
                grdLandRelatedDoc.DataBind();

                BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, true);

                iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(grdLandRelatedDoc.Columns.Count);
                int[] widths = new int[grdLandRelatedDoc.Columns.Count];
                for (int x = 0; x < grdLandRelatedDoc.Columns.Count; x++)
                {
                    widths[x] = (int)grdLandRelatedDoc.Columns[x].ItemStyle.Width.Value;
                    string cellText = Server.HtmlDecode(grdLandRelatedDoc.HeaderRow.Cells[x].Text);

                    //Set Font and Font Color
                    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                    font.Color = new iTextSharp.text.BaseColor(Color.Black);
                    iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

                    //Set Header Row BackGround Color
                    cell.BackgroundColor = new iTextSharp.text.BaseColor(Color.White);


                    table.AddCell(cell);
                }
                table.SetWidths(widths);

                for (int i = 0; i < grdLandRelatedDoc.Rows.Count; i++)
                {
                    if (grdLandRelatedDoc.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        {
                            for (int j = 0; j < grdLandRelatedDoc.Columns.Count; j++)
                            {
                                string cellText = Server.HtmlDecode(grdLandRelatedDoc.Rows[i].Cells[j].Text);

                                //Set Font and Font Color
                                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                                font.Color = new iTextSharp.text.BaseColor(Color.Black);
                                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

                                //Set Color of row
                                if (i % 2 == 0)
                                {
                                    //Set Row BackGround Color
                                    cell.BackgroundColor = new iTextSharp.text.BaseColor(Color.White);
                                }

                                table.AddCell(cell);
                            }
                        }
                    }
                }

                //Create the PDF Document
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                pdfDoc.Add(table);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #38
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);
    }
Example #39
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);
    }
Example #40
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);
    }
Example #41
0
        public void AddImage(Dictionary <string, string> images)
        {
            //if (images.Count == 0)
            //	return;
            //iPdf.PdfPTable table = new iPdf.PdfPTable(2);
            //table.SplitLate = true;
            //table.KeepTogether = true;
            //table.WidthPercentage = 100F;
            //table.SetWidths(new float[] { 50F, 50F });
            //table.SpacingBefore = 10F;
            //table.SpacingAfter = 10F;
            //table.DefaultCell.Border = iText.Rectangle.NO_BORDER;
            //foreach(string path in images.Keys)
            //{
            //	iPdf.PdfPTable imageTable = new iPdf.PdfPTable(1);
            //	imageTable.WidthPercentage = 100F;
            //	imageTable.SetWidths(new float[] { 1F });
            //	imageTable.SpacingBefore = 2F;
            //	imageTable.SpacingAfter = 2F;
            //	imageTable.SplitLate = true;

            //	iText.Image image = iText.Image.GetInstance(path);
            //	image.Alignment = iText.Image.ALIGN_LEFT;
            //	iPdf.PdfPCell imageCell = new iPdf.PdfPCell(image, true);
            //	imageTable.AddCell(imageCell);

            //	iText.Chunk chunk = new iText.Chunk(images[path]);
            //	chunk.Font = iText.FontFactory.GetFont(baseFont, normalSize, iText.BaseColor.DARK_GRAY);
            //	iPdf.PdfPCell titleCell = new iPdf.PdfPCell(new iText.Phrase(chunk));
            //	imageTable.AddCell(titleCell);

            //	table.AddCell(imageTable);
            //}
            //table.AddCell("");
            //document.Add(table);
            if (images.Count == 0)
            {
                return;
            }
            foreach (string path in images.Keys)
            {
                iPdf.PdfPTable imageTable = new iPdf.PdfPTable(1);
                imageTable.WidthPercentage = 55F;
                imageTable.SetWidths(new float[] { 1F });
                imageTable.SpacingBefore      = 0F;
                imageTable.SpacingAfter       = 0F;
                imageTable.SplitLate          = true;
                imageTable.KeepTogether       = true;
                imageTable.DefaultCell.Border = iText.Rectangle.NO_BORDER;

                iText.Image image = iText.Image.GetInstance(path);
                image.Alignment = iText.Image.ALIGN_LEFT;
                iPdf.PdfPCell imageCell = new iPdf.PdfPCell(image, true);
                imageTable.AddCell(imageCell);

                iText.Chunk chunk = new iText.Chunk(images[path]);
                chunk.Font = iText.FontFactory.GetFont(baseFont, normalSize, iText.BaseColor.DARK_GRAY);
                iPdf.PdfPCell titleCell = new iPdf.PdfPCell(new iText.Phrase(chunk));
                imageTable.AddCell(titleCell);
                imageTable.AddCell(" ");
                document.Add(imageTable);
            }
        }
Example #42
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var alignRight  = Element.ALIGN_RIGHT;

        long oportunityId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId    = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company      = new Company(companyId);
        var  res          = ActionResult.NoAction;
        var  user         = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary   = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  oportunity   = Oportunity.ById(oportunityId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

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

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

        var alignLeft = Element.ALIGN_LEFT;

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

        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

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

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

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

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

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

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

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

        table.AddCell(TitleCell(dictionary["Item_BusinessRisk_Tab_Basic"], 4));

        table.AddCell(TitleLabel(dictionary["Item_BusinessRisk_LabelField_DateStart"]));
        table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", oportunity.DateStart)));

        table.AddCell(TitleLabel(dictionary["Item_Process"]));
        table.AddCell(TitleData(oportunity.Process.Description));

        table.AddCell(TitleLabel(dictionary["Item_Rule"]));
        table.AddCell(TitleData(oportunity.Rule.Description));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        string costText = oportunity.Cost.ToString();
        if (costText == "0")
        {
            costText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(costText));

        string impactText = oportunity.Impact.ToString();
        if (impactText == "0")
        {
            impactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(impactText));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Description"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Description, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Causes, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Control"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Control, ToolsPdf.BorderAll, alignLeft, 4));

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

        table.AddCell(SeparationRow());

        table.AddCell(TitleCell(dictionary["Item_Oportunity_Tab_Graphics"], 4));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        string finalCostText = oportunity.FinalCost.ToString();
        if (finalCostText == "0")
        {
            finalCostText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(finalCostText));

        string finalImpactText = oportunity.FinalImpact.ToString();
        if (finalImpactText == "0")
        {
            finalImpactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(finalImpactText));

        document.Add(table);
        #endregion

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

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

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

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

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

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

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

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

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

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

            #region Historico acciones
            var historico = IncidentAction.ByOportunityCode(oportunity.Code, company.Id).Where(ia => ia.Oportunity.Id != oportunity.Id).OrderBy(incidentAction => incidentAction.WhatHappenedOn).ToList();
            if (historico.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

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

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

                tableHistoric.SetWidths(new float[] { 20f, 30f, 120f, 20f, 20f });

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

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"]));

                int cont = 0;
                foreach (var accion in historico)
                {
                    string statusText = dictionary["Item_Incident_Status1"];

                    if (accion.CausesOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status2"];
                    }

                    if (accion.ActionsOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status3"];
                    }

                    if (accion.ClosedOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status4"];
                    }

                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.WhatHappenedOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(statusText, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(accion.Description, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ActionsOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ClosedOn, ToolsPdf.LayoutFonts.Times));

                    cont++;
                }

                tableHistoric.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 5,
                    Padding = 8f
                });

                document.Add(tableHistoric);
            }
            #endregion

            #region Costes
            var costs = IncidentActionCost.ByOportunityId(oportunity.Id, company.Id);
            if (costs.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

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

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

                tableCost.SetWidths(new float[] { 90f, 40f, 30f, 60f, 20f });

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

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

                int     cont      = 0;
                decimal costTotal = 0;
                foreach (var cost in costs)
                {
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Description, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount * cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Responsible.FullName, ToolsPdf.LayoutFonts.Times));

                    costTotal += cost.Amount * cost.Quantity;
                    cont++;
                }

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 2,
                    Padding = 8f
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(costTotal), ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });



                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                document.Add(tableCost);
            }

            #endregion
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
        protected void GenerateReport(BarcodeGenerateModel model)
        {
            var img = (from p in db.tbl_RawMaterials  where p.RawMaterialId == model.RawMaterialsId select p).SingleOrDefault();

            string imgPath = Server.MapPath("~/barcodes/" + img.barcode + ".png");

            Font   Font15          = FontFactory.GetFont("Verdana", 12, Font.BOLDITALIC);
            string str_pdffilename = "barcode.pdf";
            string str_pdfpath     = Server.MapPath("~/barcodes/") + str_pdffilename;

            Document  doc    = new Document(PageSize.A4, 50, 50, 55, 25);
            PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);

            doc.Open();

            PdfPTable table = new iTextSharp.text.pdf.PdfPTable(4);

            table.WidthPercentage = 100;
            float[] intwidth = new float[4] {
                1, 1, 1, 1
            };
            table.SetWidths(intwidth);
            table.DefaultCell.BorderColor = new BaseColor(0, 0, 0, 0);
            table.DefaultCell.BorderWidth = 1;
            table.SpacingAfter            = 1;
            table.HorizontalAlignment     = Element.ALIGN_CENTER;

            PdfPCell cellPdf1 = new PdfPCell();

            cellPdf1                   = new PdfPCell(new Phrase(img.Name, Font15));
            cellPdf1.Border            = 0;
            cellPdf1.Colspan           = 4;
            cellPdf1.BorderWidthBottom = 1F;
            cellPdf1.BorderWidthLeft   = 0;
            cellPdf1.BorderWidthRight  = 0;
            cellPdf1.BorderWidthTop    = 0;
            cellPdf1.SetLeading(.5F, .5F);
            cellPdf1.BorderWidthBottom   = 0;
            cellPdf1.HorizontalAlignment = Element.ALIGN_MIDDLE;
            cellPdf1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            table.AddCell(cellPdf1);

            for (int i = 0; i < model.NoOfBarcode; i++)
            {
                Image    png     = Image.GetInstance(imgPath);
                PdfPCell cellPdf = new PdfPCell((Image.GetInstance(png)));
                png.ScaleToFit(1F, 2F);
                png.SpacingBefore      = 0F;
                png.Alignment          = Element.ALIGN_MIDDLE;
                cellPdf.Border         = 0;
                cellPdf.Colspan        = 0;
                cellPdf.Rowspan        = 1;
                cellPdf.BorderWidthTop = 0;
                cellPdf.SetLeading(0F, 0F);
                cellPdf.BorderWidthBottom   = 0;
                cellPdf.HorizontalAlignment = Element.ALIGN_MIDDLE;
                cellPdf.VerticalAlignment   = Element.ALIGN_MIDDLE;
                table.AddCell(cellPdf);
            }



            doc.Add(table);

            writer.CloseStream = false;
            doc.Close();
            Response.Buffer      = true;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + img.Name + " - Barcode.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(doc);
            Response.End();
            string script = string.Format(@"showDialogfile('{0}')", str_pdffilename);
            //ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        long equipmentId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId   = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company     = new Company(companyId);
        var  res         = ActionResult.NoAction;
        var  user        = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary  = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  equipment   = Equipment.ById(equipmentId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

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



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

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

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

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

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

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

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

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

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

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

        table.AddCell(new PdfPCell(new Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", equipment.Code, equipment.Description), descriptionFont))
        {
            Colspan             = 3,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 20f,
            PaddingBottom       = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        table.AddCell(TitleCell(dictionary["Item_Equipment_Tab_Basic"], 3));
        table.AddCell(TitleLabel(dictionary["Item_Equipment_Field_TradeMark_Label"]));
        table.AddCell(TitleData(equipment.Trademark));

        if (!string.IsNullOrEmpty(equipment.Image))
        {
            string equipmentImagePath = pathFonts + "images\\equipments\\" + equipment.Id + ".jpg";
            if (File.Exists(equipmentImagePath))
            {
                var myImage   = iTextSharp.text.Image.GetInstance(equipmentImagePath);
                var cellPhoto = new PdfPCell();
                cellPhoto.AddElement(myImage);
                cellPhoto.Rowspan             = 7;
                cellPhoto.Border              = Rectangle.NO_BORDER;
                cellPhoto.HorizontalAlignment = Element.ALIGN_CENTER;
                cellPhoto.VerticalAlignment   = Element.ALIGN_TOP;
                table.AddCell(cellPhoto);
            }
            else
            {
                var cellPhoto = new PdfPCell(new Phrase("no image"))
                {
                    Rowspan             = 7,
                    Border              = Rectangle.NO_BORDER,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_TOP
                };
                table.AddCell(cellPhoto);
            }
        }
        else
        {
            var cellPhoto = new PdfPCell(new Phrase("no image"))
            {
                Rowspan             = 7,
                Border              = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_TOP
            };
            table.AddCell(cellPhoto);
        }


        table.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Model_Label"]));
        table.AddCell(TitleData(equipment.Model));

        table.AddCell(TitleLabel(dictionary["Item_Equipment_Field_SerialNumber_Label"]));
        table.AddCell(TitleData(equipment.SerialNumber));

        table.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Location_Label"]));
        table.AddCell(TitleData(equipment.Location));

        table.AddCell(TitleLabel(dictionary["Item_Equipment_Field_ScaleDivision_Label"]));
        table.AddCell(TitleData(equipment.ScaleDivisionValue.Value + " " + equipment.MeasureUnit.Description));

        table.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Responsible_Label"]));
        table.AddCell(TitleData(equipment.Responsible.FullName));

        table.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Notes_Label"]));
        table.AddCell(TitleData(equipment.Observations));

        document.Add(table);
        #endregion

        #region Configuració interna
        if (equipment.InternalCalibration.Id > 0)
        {
            var tableConfigurationInt = new PdfPTable(4)
            {
                SpacingAfter        = 30f,
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableConfigurationInt.SetWidths(new float[] { 25f, 30f, 25f, 40f });
            tableConfigurationInt.AddCell(this.TitleCell(dictionary["Item_EquipmentCalibration_Label_Internal"]));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Operation"]));
            tableConfigurationInt.AddCell(this.TitleData(equipment.InternalCalibration.Description, 3));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Periodicity"]));
            tableConfigurationInt.AddCell(this.TitleData(equipment.InternalCalibration.Periodicity + " " + dictionary["Common_Days"], 3));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Uncertainty"]));
            tableConfigurationInt.AddCell(this.TitleData(equipment.InternalCalibration.Uncertainty.ToString()));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Range"]));
            tableConfigurationInt.AddCell(this.TitleData(equipment.InternalCalibration.Range));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Pattern"]));
            tableConfigurationInt.AddCell(this.TitleData(equipment.InternalCalibration.Pattern));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Cost"]));
            tableConfigurationInt.AddCell(this.TitleData(string.Format(CultureInfo.InvariantCulture, "{0:#0.00} €", equipment.InternalCalibration.Cost)));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Responsible"]));
            tableConfigurationInt.AddCell(this.TitleData(equipment.InternalCalibration.Responsible.FullName, 3));
            tableConfigurationInt.AddCell(this.TitleLabel(dictionary["Item_Equipment_Field_Calibration_Notes"]));
            tableConfigurationInt.AddCell(this.TitleData(equipment.InternalCalibration.Notes, 3));
            document.Add(tableConfigurationInt);
        }
        #endregion

        #region Configuració externa
        if (equipment.ExternalCalibration.Id > 0)
        {
            var tableConfigurationExt = new PdfPTable(4)
            {
                SpacingAfter        = 30f,
                KeepTogether        = true,
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableConfigurationExt.SetWidths(new float[] { 25f, 30f, 25f, 40f });
            tableConfigurationExt.AddCell(TitleCell(dictionary["Item_EquipmentCalibration_Label_External"]));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Operation"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Description, 3));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Periodicity"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Periodicity + " " + dictionary["Common_Days"], 3));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Uncertainty"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Uncertainty.ToString()));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Range"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Range));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Pattern"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Pattern));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Cost"]));
            tableConfigurationExt.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:#0.00} €", equipment.ExternalCalibration.Cost)));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Responsible"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Responsible.FullName, 3));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Provider"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Provider.Description, 3));
            tableConfigurationExt.AddCell(TitleLabel(dictionary["Item_Equipment_Field_Calibration_Notes"]));
            tableConfigurationExt.AddCell(TitleData(equipment.ExternalCalibration.Notes, 3));
            document.Add(tableConfigurationExt);
        }
        #endregion

        #region Verificació interna
        if (equipment.InternalVerification.Id > 0)
        {
            var tableVerificationInt = new PdfPTable(4)
            {
                SpacingAfter        = 30f,
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableVerificationInt.SetWidths(new float[] { 25f, 30f, 25f, 40f });
            tableVerificationInt.AddCell(this.TitleCell(dictionary["Item_EquipmentVerification_Label_Internal"]));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Operation"]));
            tableVerificationInt.AddCell(this.TitleData(equipment.InternalVerification.Description, 3));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Periodicity"]));
            tableVerificationInt.AddCell(this.TitleData(equipment.InternalVerification.Periodicity + " " + dictionary["Common_Days"], 3));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Uncertainty"]));
            tableVerificationInt.AddCell(this.TitleData(equipment.InternalVerification.Uncertainty.ToString()));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Range"]));
            tableVerificationInt.AddCell(this.TitleData(equipment.InternalVerification.Range));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Pattern"]));
            tableVerificationInt.AddCell(this.TitleData(equipment.InternalVerification.Pattern));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Cost"]));
            tableVerificationInt.AddCell(this.TitleData(string.Format(CultureInfo.InvariantCulture, "{0:#0.00} €", equipment.InternalVerification.Cost)));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Responsible"]));
            tableVerificationInt.AddCell(this.TitleData(equipment.InternalVerification.Responsible.FullName, 3));
            tableVerificationInt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Notes"]));
            tableVerificationInt.AddCell(this.TitleData(equipment.InternalVerification.Notes, 3));
            document.Add(tableVerificationInt);
        }
        #endregion

        #region Verificació externa
        if (equipment.ExternalVerification.Id > 0)
        {
            var tableVerificationExt = new PdfPTable(4)
            {
                SpacingAfter        = 30f,
                KeepTogether        = true,
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableVerificationExt.SetWidths(new float[] { 25f, 30f, 25f, 40f });
            tableVerificationExt.AddCell(this.TitleCell(dictionary["Item_EquipmentVerification_Label_External"]));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Operation"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Description, 3));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Periodicity"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Periodicity + " " + dictionary["Common_Days"], 3));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Uncertainty"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Uncertainty.ToString()));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Range"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Range));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Pattern"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Pattern));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Cost"]));
            tableVerificationExt.AddCell(this.TitleData(string.Format(CultureInfo.InvariantCulture, "{0:#0.00} €", equipment.ExternalVerification.Cost)));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Responsible"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Responsible.FullName, 3));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Provider"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Provider.Description, 3));
            tableVerificationExt.AddCell(this.TitleLabel(dictionary["Item_EquipmentVerification_Field_Notes"]));
            tableVerificationExt.AddCell(this.TitleData(equipment.ExternalVerification.Notes, 3));
            document.Add(tableVerificationExt);
        }
        #endregion

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

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

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

            tableMaintenance.SetWidths(new float[] { 90f, 40f, 30f, 60f, 20f });

            var cellMaintenanceDescription = new PdfPCell(new Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", equipment.Code, equipment.Description), descriptionFont))
            {
                Colspan             = 5,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            };
            tableMaintenance.AddCell(cellMaintenanceDescription);

            var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
            tableMaintenance.AddCell(new PdfPCell(new Phrase(dictionary["Item_EquipmentMaintenanceDefinition_Plurar"].ToUpperInvariant(), valueFont))
            {
                Colspan             = 5,
                HorizontalAlignment = Element.ALIGN_LEFT,
                Padding             = 8,
                PaddingTop          = 6,
                Border = Rectangle.NO_BORDER
            });

            tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_EquipmentMaintenanceDefinition_Header_Operation"].ToUpperInvariant(), headerFontFinal))
            {
                Border              = ToolsPdf.BorderAll,
                BackgroundColor     = backgroundColor,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 8
            });

            tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_EquipmentMaintenanceDefinition_Header_Type"].ToUpperInvariant(), headerFontFinal))
            {
                Border              = ToolsPdf.BorderAll,
                BackgroundColor     = backgroundColor,
                HorizontalAlignment = iTS.Element.ALIGN_CENTER,
                Padding             = 8
            });

            tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_EquipmentMaintenanceDefinition_Header_Periodicity_PDF"].ToUpperInvariant(), headerFontFinal))
            {
                PaddingBottom       = 6f,
                Border              = ToolsPdf.BorderAll,
                BackgroundColor     = backgroundColor,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 8
            });

            tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_EquipmentMaintenanceDefinition_Header_Accesories"].ToUpperInvariant(), headerFontFinal))
            {
                Border              = ToolsPdf.BorderAll,
                BackgroundColor     = backgroundColor,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 8
            });

            tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_EquipmentMaintenanceDefinition_Header_Cost"].ToUpperInvariant(), headerFontFinal))
            {
                Border              = ToolsPdf.BorderAll,
                BackgroundColor     = backgroundColor,
                HorizontalAlignment = iTS.Element.ALIGN_RIGHT,
                Padding             = 8
            });

            int     borderFirst = iTS.Rectangle.TOP_BORDER;
            int     cont        = 0;
            var     data        = Equipment.ByCompany(companyId);
            bool    pair        = false;
            var     times       = new iTS.Font(arial, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
            var     timesBold   = new iTS.Font(arial, 8, iTS.Font.BOLD, iTS.BaseColor.BLACK);
            decimal cost        = 0;
            foreach (EquipmentMaintenanceDefinition maintenance in EquipmentMaintenanceDefinition.ByCompany(equipment.Id, equipment.CompanyId))
            {
                int border         = 0;
                var lineBackground = pair ? rowEven : rowPair;

                tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(maintenance.Description, times))
                {
                    Border          = border,
                    BackgroundColor = lineBackground,
                    Padding         = 6f,
                    PaddingTop      = 4f
                });

                string typeText = dictionary["Common_Internal"];
                if (maintenance.MaintenanceType == 1)
                {
                    typeText = dictionary["Common_External"];
                }

                tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(typeText, times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    Padding             = 6f,
                    PaddingTop          = 4f
                });

                tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(maintenance.Periodicity + " " + dictionary["Common_Days"], times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 6f,
                    PaddingTop          = 4f
                });

                tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(maintenance.Accessories, times))
                {
                    Border          = border,
                    BackgroundColor = lineBackground,
                    Padding         = 6f,
                    PaddingTop      = 4f
                });

                tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", maintenance.Cost), times))
                {
                    Border              = border,
                    BackgroundColor     = lineBackground,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 6f,
                    PaddingTop          = 4f
                });

                cont++;
                if (maintenance.Cost.HasValue)
                {
                    cost += maintenance.Cost.Value;
                }
            }

            // TotalRow
            tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", timesBold))
            {
                Border = borderFirst,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                Colspan             = 4,
                Padding             = 8f
            });

            tableMaintenance.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cost), timesBold))
            {
                Border = borderFirst,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                Colspan             = 1,
                Padding             = 8f
            });

            document.Add(tableMaintenance);
        }
        #endregion

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

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

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

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

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

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

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

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

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

        writer.PageEvent = pageEventHandler;

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

        document.Open();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        document.Add(table);
        #endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

        document.Add(tableAssistants);
        #endregion

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Example #49
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);
        }
Example #50
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);
    }
Example #51
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);
    }
 public void GenerarDocumento(Document document)
 {
     //se crea un objeto PdfTable con el numero de columnas del dataGridView
     PdfPTable datatable = new PdfPTable(dgRegistroKARDEX.ColumnCount);
     //asignanos algunas propiedades para el diseño del pdf
     datatable.DefaultCell.Padding = 1;
     float[] headerwidths = GetTamañoColumnas(dgRegistroKARDEX);
     datatable.SetWidths(headerwidths);
     datatable.WidthPercentage = 80;
     datatable.DefaultCell.BorderWidth = 1;
     datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
     //SE GENERA EL ENCABEZADO DE LA TABLA EN EL PDF
     for (int i = 0; i < dgRegistroKARDEX.ColumnCount; i++)
     {
         datatable.AddCell(dgRegistroKARDEX.Columns[i].HeaderText);
     }
     datatable.HeaderRows = 1;
     datatable.DefaultCell.BorderWidth = 1;
     //SE GENERA EL CUERPO DEL PDF
     for (int i = 0; i < dgRegistroKARDEX.RowCount - 1; i++)
     {
         for (int j = 0; j < dgRegistroKARDEX.ColumnCount; j++)
         {
             datatable.AddCell(dgRegistroKARDEX[j, i].Value.ToString());
         }
         datatable.CompleteRow();
     }
     //SE AGREGAR LA PDFPTABLE AL DOCUMENTO
     document.Add(datatable);
 }