Inheritance: Rectangle, IAccessibleElement
        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);
        }
        private void CreatePdf(FileStream outputStream)
        {
            var doc = new Document(PageSize.A4);

            PdfWriter.GetInstance(doc, outputStream);

            doc.Open();

            WriteFrontPage(doc);
            doc.NewPage();
            WriteSpecification(doc);

            foreach (var representation in _report.Representations)
            {
                doc.NewPage();
                doc.Add(new Paragraph("Representation"));
            }

            PdfPTable table = new PdfPTable(2);
            table.AddCell(new PdfPCell { Colspan = 1 });
            PdfPCell cell = new PdfPCell { Colspan = 1, HorizontalAlignment = 1, Phrase = new Phrase("REPRESENTATIONSKOSTNADER") };
            table.AddCell(cell);
            table.AddCell("Col 1 Row 1");
            table.AddCell("Col 2 Row 1");
            table.AddCell("Col 3 Row 1");
            table.AddCell("Col 1 Row 2");
            table.AddCell("Col 2 Row 2");
            table.AddCell("Col 3 Row 2");
            doc.Add(table);
            doc.Close();
        }
        private static void GenerateRow(PdfPTable table, PlayerInfo player, Font font, BaseColor backgroundColor)
        {
            var jpg = Image.GetInstance(player.PictureUrl);
            table.AddCell(jpg);

            PdfPCell cell;

            cell = new PdfPCell(new Phrase(player.JerseyNumber, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.Name, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            if (table.NumberOfColumns == NumberColsWithPosition)
            {
                cell = new PdfPCell(new Phrase(player.Position, font)) {BackgroundColor = backgroundColor};
                table.AddCell(cell);
            }

            cell = new PdfPCell(new Phrase(player.Height, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.Weight, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.DateOfBirth, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.Age, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.BirthPlace, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);
        }
 public void TestKeepTogether(bool tagged, bool keepTogether) {
     Document document = new Document();
     String file = "tagged_" + tagged + "-keeptogether_" + keepTogether + ".pdf";
     PdfWriter writer = PdfWriter.GetInstance(document, File.Create(outFolder + file));
     if (tagged)
         writer.SetTagged();
     document.Open();
     int columns = 3;
     int tables = 3;
     for (int tableCount = 0; tableCount < tables; tableCount++) {
         PdfPTable table = new PdfPTable(columns);
         for (int rowCount = 0; rowCount < 50; rowCount++) {
             PdfPCell cell1 = new PdfPCell(new Paragraph("t" + tableCount + " r:" + rowCount));
             PdfPCell cell2 = new PdfPCell(new Paragraph("t" + tableCount + " r:" + rowCount));
             PdfPCell cell3 = new PdfPCell(new Paragraph("t" + tableCount + " r:" + rowCount));
             table.AddCell(cell1);
             table.AddCell(cell2);
             table.AddCell(cell3);
         }
         table.SpacingAfter = 10f;
         table.KeepTogether = keepTogether;
         document.Add(table);
     }
     document.Close();
 }
 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();
 }
        private static void AddDayHeader(PdfPTable table, DateTime date)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            PdfPCell dayHeader = new PdfPCell(new Phrase(string.Format("Date: {0}", date.ToString("dd-MMM-yyyy"))));
            dayHeader.Colspan = table.NumberOfColumns;
            dayHeader.BackgroundColor = BaseColor.LIGHT_GRAY;

            table.AddCell(dayHeader);

            string[] columnHeaders = new string[]
            {
                "Product",
                "Quantity",
                "UnitPrice",
                "Location",
                "Sum",
            };

            foreach (var header in columnHeaders)
            {
                PdfPCell columnHeader = new PdfPCell(new Phrase(header, new Font(Font.FontFamily.UNDEFINED, 12, 1)));
                columnHeader.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(columnHeader);
            }
        }
		public void CreateDocument( List< ScanDetails > info, string path )
		{
			var doc = new Document( PageSize.A4 );
			PdfWriter.GetInstance( doc, new FileStream( path, FileMode.Create ) );

			doc.Open();
			doc.Add( new Paragraph() );

			PdfPTable table = new PdfPTable( 4 ) { WidthPercentage = 100 };
			//header
			PdfPCell cell = new PdfPCell { BackgroundColor = BaseColor.LIGHT_GRAY, Phrase = new Phrase( "URL" ) };
			table.AddCell( cell );

			cell.Phrase = new Phrase( "Response" );
			table.AddCell( cell );

			cell.Phrase = new Phrase( "Size" );
			table.AddCell( cell );

			cell.Phrase = new Phrase( "Page Title" );
			table.AddCell( cell );

			//rows
			foreach( var item in info )
			{
				table.AddCell( item.Url.ToString() );
				table.AddCell( item.Response );
				table.AddCell( item.Size.ToString() );
				table.AddCell( item.PageTitle );
			}

			doc.Add( table );

			doc.Close();
		}
        protected void MakePdfButton_Click(object sender, EventArgs e)
        {
            PdfPTable pdfTable = new PdfPTable(GridView1.HeaderRow.Cells.Count);

            foreach (TableCell headeCell in GridView1.HeaderRow.Cells)
            {
                PdfPCell pdfPCell = new PdfPCell(new Phrase(headeCell.Text));
                pdfTable.AddCell(pdfPCell);
            }

            foreach (GridViewRow gridViewRow in GridView1.Rows)
            {
                foreach (TableCell tableCell in gridViewRow.Cells)
                {
                    PdfPCell pdfPCell = new PdfPCell(new Phrase(tableCell.Text));
                    pdfTable.AddCell(pdfPCell);
                }
            }

            Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);
            pdfDocument.Open();
            pdfDocument.Add(pdfTable);
            pdfDocument.Close();

            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-disposition", "Attachment;filename=Employee.pdf");
            Response.Write(pdfDocument);
            Response.Flush();
            Response.End();
        }
        protected void generatePDFButton_Click(object sender, EventArgs e)
        {
            PdfPTable pdfPTable = new PdfPTable(CreatedStudentInformationGridView.HeaderRow.Cells.Count);

            foreach (TableCell headerCell in CreatedStudentInformationGridView.HeaderRow.Cells)
            {
                PdfPCell pfdPCell = new PdfPCell(new Phrase(headerCell.Text));
                //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                pdfPTable.AddCell(pfdPCell);
            }

            foreach (GridViewRow gridViewRow in CreatedStudentInformationGridView.Rows)
            {
                foreach (TableCell tableCell in gridViewRow.Cells)
                {

                    PdfPCell pfdPCell = new PdfPCell(new Phrase(tableCell.Text));
                    //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                    pdfPTable.AddCell(pfdPCell);
                }
            }
            Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

            pdfDocument.Open();
            pdfDocument.Add(pdfPTable);
            pdfDocument.Close();

            Response.ContentType = "application/pdf";
            Response.AppendHeader("content-disposition", "attachment;filename=NewCenter.pdf");
            Response.Write(pdfDocument);
            Response.Flush();
            Response.End();
        }
 protected void btndownload_Click(object sender, EventArgs e)
 {
     PdfPTable pdftable = new PdfPTable(gvtimetable.HeaderRow.Cells.Count);
     foreach(TableCell headercell in gvtimetable.HeaderRow.Cells)
     {
         Font font = new Font();
         font.Color = new BaseColor(gvtimetable.HeaderStyle.ForeColor);
         PdfPCell pdfcell = new PdfPCell(new Phrase(headercell.Text, font));
         pdfcell.BackgroundColor = new BaseColor(gvtimetable.HeaderStyle.BackColor);
         pdftable.AddCell(pdfcell);
     }
     foreach(GridViewRow gridviewrow in gvtimetable.Rows)
     {
         foreach(TableCell tablecell in gridviewrow.Cells)
         {
             Font font = new Font();
             font.Color = new BaseColor(gvtimetable.RowStyle.ForeColor);
             PdfPCell pdfcell = new PdfPCell(new Phrase(tablecell.Text));
             //pdfcell.BackgroundColor = ;
             pdftable.AddCell(pdfcell);
         }
     }
     Document pdfdocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
     PdfWriter.GetInstance(pdfdocument, Response.OutputStream);
     pdfdocument.Open();
     pdfdocument.Add(pdftable);
     pdfdocument.Close();
     Response.ContentType = "application/pdf";
     Response.AppendHeader("content-disposition", "attachment;filename=Student_Timetable.pdf");
     Response.Write(pdfdocument);
     Response.Flush();
     Response.End();
 }
        public PdfPCell RenderingCell(CellAttributes attributes)
        {
            var pdfCell = new PdfPCell();
            var table = new PdfGrid(1) { RunDirection = PdfWriter.RUN_DIRECTION_LTR };

            var filePath = System.IO.Path.Combine(AppPath.ApplicationPath, "Images\\" + _rnd.Next(1, 5).ToString("00") + ".png");
            var photo = PdfImageHelper.GetITextSharpImageFromImageFile(filePath);
            table.AddCell(new PdfPCell(photo, fit: false)
            {
                Border = 0,
                VerticalAlignment = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            var name = attributes.RowData.TableRowData.GetSafeStringValueOf("User");
            table.AddCell(new PdfPCell(attributes.BasicProperties.PdfFont.FontSelector.Process(name))
            {
                Border = 0,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            pdfCell.AddElement(table);

            return pdfCell;
        }
        /// <summary>
        /// Using iTextSharp's limited HTML to PDF capabilities.
        /// </summary>
        public PdfPCell RenderHtml()
        {
            var pdfCell = new PdfPCell
            {
                UseAscender = true,
                UseDescender = true,
                VerticalAlignment = Element.ALIGN_MIDDLE
            };

            applyStyleSheet();

            var tags = setCustomTags();

            using (var reader = new StringReader(Html))
            {
                var parsedHtmlElements = HTMLWorker.ParseToList(reader, StyleSheet, tags, null);

                foreach (var htmlElement in parsedHtmlElements)
                {
                    applyRtlRunDirection(htmlElement);
                    pdfCell.AddElement(htmlElement);
                }

                return pdfCell;
            }
        }
        private static void ConfigurarConteudo(List<Tarefa> tarefas, Document document)
        {
            foreach (Tarefa tarefa in tarefas)
            {
                PdfPTable table = new PdfPTable(2);

                PdfPCell cell = new PdfPCell(new Phrase( tarefa.ToString()));
                cell.Colspan = 2;
                cell.BackgroundColor = BaseColor.GRAY;
                cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                table.AddCell(cell);

                PdfPCell cellSubitem = new PdfPCell(new Phrase("Subitem"));
                cellSubitem.BackgroundColor = BaseColor.LIGHT_GRAY;
                cellSubitem.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right

                PdfPCell cellPercentual = new PdfPCell(new Phrase("Percentual"));
                cellPercentual.BackgroundColor = BaseColor.LIGHT_GRAY;
                cellPercentual.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right

                table.AddCell(cellSubitem);
                table.AddCell(cellPercentual);

                foreach (Subitem subitem in tarefa.Subitens)
                {
                    table.AddCell(subitem.Titulo);
                    table.AddCell(subitem.Percentual.ToString());
                }

                document.Add(table);

                document.Add(new Paragraph(" "));
            }
        }
        // to generate the report call the GeneratePDFReport static method.
        // The pdf file will be generated in the SupermarketChain.ConsoleClient folder
        // TODO measures are missing
        // TODO code refactoring to limitr repeated chunks
        public static void GeneratePDFReport()
        {
            Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 40, 35);
            string filePath = @"..\..\..\..\Reports\salesReports.pdf";
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
            doc.Open();
            PdfPTable table = new PdfPTable(5);

            Font verdana = FontFactory.GetFont("Verdana", 16, Font.BOLD);
            Font verdana2 = FontFactory.GetFont("Verdana", 12, Font.BOLD);

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report", verdana));
            header.Colspan = 5;
            header.HorizontalAlignment = 1;
            table.AddCell(header);

            double totalSales = PourReportData(table);

            PdfPCell totalSum = new PdfPCell(new Phrase("Grand total:"));
            totalSum.Colspan = 4;
            totalSum.HorizontalAlignment = 2;
            totalSum.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSum);

            PdfPCell totalSumNumber = new PdfPCell(new Phrase(String.Format("{0:0.00}", totalSales), verdana));
            totalSumNumber.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSumNumber);

            doc.Add(table);
            doc.Close();

            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            Console.WriteLine("Pdf report generated.");
            Console.WriteLine("File:  {0}", directoryInfo.FullName);
        }
        private static PDF.PdfPCell GetFormattedCell(TableCell cell)
        {
            PDF.PdfPCell formattedCell = new PDF.PdfPCell();

            Element[] cellElements = cell.SubElements;

            foreach (Element temp in cellElements)
            {
                switch (temp.GetElementType())
                {
                    //TODO: Add other enum values
                    case ElementType.Text:
                        IT.Phrase phrase = new IT.Phrase(TextFormatter.GetFormattedText((Text)temp));
                        formattedCell.AddElement(phrase);
                        break;

                    case ElementType.Paragraph:
                        formattedCell.AddElement(ParagraphFormatter.GetFormattedParagraph((Paragraph)temp));
                        break;

                    case ElementType.Table:
                        formattedCell.AddElement(TableFormatter.GetFormattedTable((Table)temp));
                        break;

                    case ElementType.Image:
                        formattedCell.AddElement(ImageFormatter.GetFormattedImage((Image)temp));
                        break;
                }

            }

            return formattedCell;
        }
 private void InstantialiseCell()
 {
     cell = new PdfPCell();
     //cell.BorderWidth = 0f;
     cell.PaddingTop = 7.5f;    // 10px http://www.unitconversion.org/typography/postscript-points-to-pixels-x-conversion.html
     cell.PaddingBottom = 7.5f;
 }
 /**
  * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(
  *      com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle,
  *      com.lowagie.text.pdf.PdfContentByte[])
  */
 public void CellLayout(
   PdfPCell cell, Rectangle rect, PdfContentByte[] canvas
 )
 {
     PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
     cb.SaveState();
     if (duration < 90)
     {
         cb.SetRGBColorFill(0x7C, 0xFC, 0x00);
     }
     else if (duration > 120)
     {
         cb.SetRGBColorFill(0x8B, 0x00, 0x00);
     }
     else
     {
         cb.SetRGBColorFill(0xFF, 0xA5, 0x00);
     }
     cb.Rectangle(
       rect.Left, rect.Bottom,
       rect.Width * duration / 240, rect.Height
     );
     cb.Fill();
     cb.RestoreState();
 }
 /**
  * @see com.itextpdf.text.pdf.PdfPCellEvent#cellLayout(com.itextpdf.text.pdf.PdfPCell,
  *      com.itextpdf.text.Rectangle, com.itextpdf.text.pdf.PdfContentByte[])
  */
 virtual public void CellLayout(PdfPCell cell, Rectangle position,
         PdfContentByte[] canvases) {
     float effectivePadding = styleValues.BorderWidthLeft/2 + styleValues.HorBorderSpacing;
     float x1 = position.Left + effectivePadding;
     if (styleValues.IsLastInRow){
         effectivePadding = styleValues.BorderWidthRight/2 + styleValues.HorBorderSpacing;
     } else {
         effectivePadding = styleValues.BorderWidthRight/2;
     }
     float x2 = position.Right - effectivePadding;
     effectivePadding = styleValues.BorderWidthTop/2 + styleValues.VerBorderSpacing;
     float y1 = position.Top - effectivePadding;
     effectivePadding = styleValues.BorderWidthBottom/2;
     float y2 = position.Bottom + effectivePadding;
     PdfContentByte cb = canvases[PdfPTable.LINECANVAS];
     BaseColor color = styleValues.Background;
     if (color != null) {
         cb.SetColorStroke(color);
         cb.SetColorFill(color);
         cb.Rectangle(x1, y1, x2-x1, y2-y1);
         cb.Fill();
     }
     BaseColor borderColor = styleValues.BorderColorLeft;
     float width = styleValues.BorderWidthLeft;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x1, y1); // start leftUpperCorner
         cb.LineTo(x1, y2); // left
         cb.Stroke();
     }
     borderColor = styleValues.BorderColorBottom;
     width = styleValues.BorderWidthBottom;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x1, y2); // left
         cb.LineTo(x2, y2); // bottom
         cb.Stroke();
     }
     borderColor = styleValues.BorderColorRight;
     width = styleValues.BorderWidthRight;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x2, y2); // bottom
         cb.LineTo(x2, y1); // right
         cb.Stroke();
     }
     borderColor = styleValues.BorderColorTop;
     width = styleValues.BorderWidthTop;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x2, y1); // right
         cb.LineTo(x1, y1); // top
         cb.Stroke();
     }
     cb.ResetRGBColorStroke();
 }
        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;
        }
        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;
        }
Exemple #21
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Table(PdfPTable table,
                                                                 iTextSharp.text.Paragraph para, string align)
        {
            const string METHOD_NAME = "AddText2Table";

            try {
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(para);
                cell.BorderWidth = 0;

                switch (align.ToLower())
                {
                case "left":
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    break;

                case "center":
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    break;

                case "right":
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    break;
                }

                table.AddCell(cell);

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
        /// <summary>
        /// Save a pdf file in  "../../test.pdf".
        /// </summary>
        /// <param name="deals">Expect Collection of objects that have Name, Address, ProductName and formula.</param>
        public void GenerateReport(IEnumerable<PdfReportModel> deals)
        {
            FileStream fileStream = new FileStream(ReportsPath, FileMode.Create, FileAccess.Write, FileShare.None);
            Rectangle pageSize = new Rectangle(PageSize.A4);
            Document reportDocument = new Document(pageSize);
            PdfWriter pdfWriter = PdfWriter.GetInstance(reportDocument, fileStream);
            var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 17);

            reportDocument.Open();

            PdfPTable reportTable = new PdfPTable(6);
            reportTable.HorizontalAlignment = Element.ALIGN_LEFT;
            PdfPCell headerCell = new PdfPCell(new Phrase("Produced products information", boldFont));
            headerCell.Colspan = 6;
            headerCell.HorizontalAlignment = 0;
            reportTable.AddCell(headerCell);

            this.PutHeadCells(reportTable);

            foreach (var deal in deals)
            {
                reportTable.AddCell(deal.ProductName);
                reportTable.AddCell(deal.Quantity);
                reportTable.AddCell(deal.PricePerUnit);
                reportTable.AddCell(deal.Formula);
                reportTable.AddCell(deal.Address);
                reportTable.AddCell(deal.Total);
            }

            reportDocument.Add(reportTable);
            reportDocument.Close();
        }
        private static PdfPTable GenerateReportTable(DayReport report)
        {
            PdfPTable table = new PdfPTable(5);
            
            string[] headerTitles = {"Product", "Quantity", "Unit Price", "Location", "Sum"};
            foreach (var title in headerTitles)
            {
                Phrase phrase = new Phrase(title);
                phrase.Font = FontFactory.GetFont("Arial", 14, Font.BOLD);
                PdfPCell cell = new PdfPCell(phrase);
                cell.BackgroundColor = new BaseColor(175, 166, 166);
                table.AddCell(cell);
                cell.Padding = 0;
            }

            foreach (var sale in report.Sales)
            {
                table.AddCell(sale.ProductName);
                table.AddCell(sale.MeasureFormatted);
                table.AddCell(sale.UnitPrice.ToString());
                table.AddCell(sale.Supermarket);
                table.AddCell(sale.Sum.ToString());
            }

            PdfPCell footerCell = new PdfPCell(new Phrase("Total sum for " + report.FormattedDate + ": "));
            footerCell.Colspan = 4;
            footerCell.HorizontalAlignment = 2;
            table.AddCell(footerCell);
            table.AddCell(new Phrase(report.TotalSum.ToString()));
            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);
        }
Exemple #25
0
        public static bool generate(User user, string path)
        {
            document = new Document(PageSize.A4, 50, 50, 25, 25);

            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, new FileStream(path + "/BS-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-" + user.Firstname + "-" + user.Lastname + ".pdf", FileMode.Create));

            document.Open();

            // création du logo
            Image logo = iTextSharp.text.Image.GetInstance("logo.png");
            logo.ScaleAbsoluteWidth(200);
            logo.ScaleAbsoluteHeight(50);
            PdfPCell cellLogo = new PdfPCell(logo);
            cellLogo.Border = Rectangle.NO_BORDER;
            cellLogo.PaddingBottom = 8;

            // création du titre
            var title = new Paragraph("BULLETIN DE SALAIRE", titleFont);
            title.Alignment = Element.ALIGN_RIGHT;
            PdfPCell cellTitle = new PdfPCell(title);
            cellTitle.Border = Rectangle.NO_BORDER;
            cellTitle.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right

            // création du tableau
            PdfPTable tableTitle = new PdfPTable(2);
            tableTitle.DefaultCell.Border = Rectangle.NO_BORDER;
            tableTitle.WidthPercentage = 100;

            PdfPCell cellAdresseSuperp = new PdfPCell(new Paragraph("89, quais des Chartrons \n33000 BORDEAUX", subTitleFont));
            cellAdresseSuperp.HorizontalAlignment = 0;
            cellAdresseSuperp.Border = Rectangle.NO_BORDER;

            PdfPCell cellDUMec = new PdfPCell(new Paragraph(user.Lastname + " " + user.Firstname + "\n" + user.Address, subTitleFont));
            cellDUMec.HorizontalAlignment = 2;
            cellDUMec.Border = Rectangle.NO_BORDER;

            // ajout de la cell du logo
            tableTitle.AddCell(cellLogo);

            // ajout de la cell du titre
            tableTitle.AddCell(cellTitle);

            tableTitle.AddCell(cellAdresseSuperp);
            tableTitle.AddCell(cellDUMec);

            // Ajout du titre principal
            tableTitle.AddCell(getTitle());

            //******************************************************************************/
            //***********************   ABSENCES   *****************************************/
            //******************************************************************************/

            generateAbsences(tableTitle, user);

            generateTableSalary(user);

            document.Close();
            return true;
        }
Exemple #26
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);
            }
        }
        public static void GeneratePdfReport(string filepath)
        {
            FileStream fileStream = new FileStream(filepath, FileMode.Create);
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
            document.SetPageSize(PageSize.A3);
            document.Open();

            var paragraph = new Paragraph("Aggregated Sales Report",
                FontFactory.GetFont("Arial", 19, Font.BOLD));
            paragraph.SpacingAfter = 20.0f;
            paragraph.Alignment = 1;

            document.Add(paragraph);

            PdfPTable mainTable = new PdfPTable(1);
            var reports = GetDayReports();
            foreach (var dayReport in reports)
            {
                var headerCell = new PdfPCell(new Phrase("Date: " + dayReport.FormattedDate));
                headerCell.BackgroundColor = new BaseColor(175, 166, 166);
                mainTable.AddCell(headerCell);
                var table = GenerateReportTable(dayReport);
                mainTable.AddCell(table);
            }

            document.Add(mainTable);
            document.Close();
        }
Exemple #28
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        int columnsCount = GridView1.HeaderRow.Cells.Count;
        // Create the PDF Table specifying the number of columns
        PdfPTable pdfTable = new PdfPTable(columnsCount);

        // Loop thru each cell in GrdiView header row
        foreach(TableCell gridViewHeaderCell in GridView1.HeaderRow.Cells)
        {
        // Create the Font Object for PDF document
        Font font = new Font();
        // Set the font color to GridView header row font color
        font.Color = new BaseColor(GridView1.HeaderStyle.ForeColor);

        // Create the PDF cell, specifying the text and font
        PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font));

        // Set the PDF cell backgroundcolor to GridView header row BackgroundColor color
        pdfCell.BackgroundColor = new BaseColor(GridView1.HeaderStyle.BackColor);

        // Add the cell to PDF table
        pdfTable.AddCell(pdfCell);
        }

        // Loop thru each datarow in GrdiView
        foreach (GridViewRow gridViewRow in GridView1.Rows)
        {
        if (gridViewRow.RowType == DataControlRowType.DataRow)
        {
            // Loop thru each cell in GrdiView data row
            foreach (TableCell gridViewCell in gridViewRow.Cells)
            {
                Font font = new Font();
                font.Color = new BaseColor(GridView1.RowStyle.ForeColor);

                PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font));

                pdfCell.BackgroundColor = new BaseColor(GridView1.RowStyle.BackColor);

                pdfTable.AddCell(pdfCell);
            }
        }
        }

        // Create the PDF document specifying page size and margins
        Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

        PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

        pdfDocument.Open();
        pdfDocument.Add(pdfTable);
        pdfDocument.Close();

        Response.ContentType = "application/pdf";
        Response.AppendHeader("content-disposition",
        "attachment;filename=Employees.pdf");
        Response.Write(pdfDocument);
        Response.Flush();
        Response.End();
    }
Exemple #29
0
        /// <summary>
        /// Create pdf table.
        /// </summary>
        /// <returns>The PDF table.</returns>
        private iTextSharp.text.pdf.PdfPTable CreateTable()
        {
            // A table with three colums
            iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(3);

            // The cell
            iTextSharp.text.pdf.PdfPCell cell = null;

            // Add a cell with colspan 3
            cell         = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase("Cell with colspan 3"));
            cell.Colspan = 3;
            table.AddCell(cell);

            // Add a cell with colspan 2
            cell         = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase("Cell with colspan 2"));
            cell.Colspan = 2;
            table.AddCell(cell);

            // Add the four remaining cells.
            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 the table.
            return(table);
        }
Exemple #30
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);
        }
Exemple #31
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Table(PdfPTable table,
                                                                 string text, iTextSharp.text.Font font, string align, int colSpan)
        {
            const string METHOD_NAME = "AddText2Table";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;
                cell.Colspan     = colSpan;

                switch (align.ToLower())
                {
                case "left":
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    break;

                case "center":
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    break;

                case "right":
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    break;
                }

                table.AddCell(cell);

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #32
0
        /// <summary>
        /// 创建测试者信息和测试信息表格
        /// </summary>
        /// <param name="tableEle"></param>
        /// <param name="columnCount"></param>
        protected void CreateTestInfoTable(XElement tableEle, int columnCount)
        {
            string    remark         = tableEle.Attribute("remark").Value;
            Paragraph parTableRemark = new Paragraph(remark, fontTableRemark);

            parTableRemark.IndentationLeft = 24;
            parTableRemark.SpacingBefore   = 20;
            pdfDoc.Add(parTableRemark);

            PdfPTable      table   = new iTextSharp.text.pdf.PdfPTable(columnCount);
            List <PdfPRow> rowList = new List <iTextSharp.text.pdf.PdfPRow>();

            foreach (XElement rowEle in tableEle.Elements())
            {
                List <PdfPCell> cellList = new List <iTextSharp.text.pdf.PdfPCell>();
                foreach (XElement cellEle in rowEle.Elements())
                {
                    string label = cellEle.Attribute("label").Value;
                    string value = cellEle.Attribute("value").Value;
                    if (value.Trim().Equals(""))
                    {
                        value = "/";
                    }

                    iTextSharp.text.pdf.PdfPCell cellLabel = new iTextSharp.text.pdf.PdfPCell(new Phrase(label, fontLabel));
                    cellLabel.FixedHeight         = 24;
                    cellLabel.Padding             = 4;
                    cellLabel.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    cellLabel.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;

                    PdfPCell cellContent = new iTextSharp.text.pdf.PdfPCell(new Phrase(value, fontContent));
                    cellContent.FixedHeight       = 24;
                    cellContent.PaddingTop        = 4;
                    cellContent.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                    XAttribute colSpanAtt = cellEle.Attribute("colspan");
                    if (colSpanAtt != null)
                    {
                        string colspan = colSpanAtt.Value;
                        if (colspan != "")
                        {
                            cellContent.Colspan = int.Parse(colspan);
                        }
                    }
                    cellList.Add(cellLabel);
                    cellList.Add(cellContent);
                }
                PdfPRow row = new iTextSharp.text.pdf.PdfPRow(cellList.ToArray <PdfPCell>());
                rowList.Add(row);
            }
            table.Rows.AddRange(rowList);
            table.KeepTogether  = true;
            table.SpacingBefore = 10;
            table.TotalWidth    = 750;
            table.LockedWidth   = true;
            Paragraph pTable = new Paragraph();

            pTable.Add(table);
            pdfDoc.Add(pTable);
        }
Exemple #33
0
        public override void AddTableCell(string content, IFont font, TextAlignment alignment)
        {
            itCell cell = new itCell(new Phrase(content, ((FontHandler)font).Handle));

            cell.HorizontalAlignment = iAlignments[(int)alignment];
            //cell.GrayFill
            fTable.AddCell(cell);
        }
        public void BuildContractDumpHeader(Document document, float[] layout)
        {
            PdfPTable table = PdfReports.CreateTable(layout, 0);

            //--------------------------------
            // HEADER
            //--------------------------------
            Color borderColor   = Color.BLACK;  //new Color(255, 0, 0);
            float borderWidth   = 1.0F;
            int   borderTypeAll = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
            float fPadding      = 2;

            iTextSharp.text.pdf.PdfPCell cell = PdfReports.AddText2Cell("Cnt #", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                                        fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Station", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Field Desc.", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Landowner", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Final Net Tons", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Tons / Acre", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Sugar %", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Tare %", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("SLM %", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Lbs Ext. Sugar / Ton", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("Plant Pop", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                           fPadding, borderWidth, borderTypeAll, borderColor);
            table.AddCell(cell);

            PdfReports.AddTableNoSplit(document, this, table);
        }
Exemple #35
0
        private void AddPatronStockHeader(ref PdfPTable table)
        {
            table = PdfReports.CreateTable(_patronStockLayout, 0);

            iTextSharp.text.pdf.PdfPCell cell =
                PdfReports.AddText2Cell("Patron Preferred Stock", _labelFont, "left", _patronStockLayout.Length);
            cell.BackgroundColor = Color.LIGHT_GRAY;
            table.AddCell(cell);
        }
Exemple #36
0
        private void FinishFinancingData(PdfWriter writer, Document document, ref PdfPTable table, EQStmtEvent pgEvent)
        {
            PdfReports.AddText2Table(table, " ", _normalFont, _equityFinancingLayout.Length);

            iTextSharp.text.pdf.PdfPCell cell = PdfReports.AddText2Cell("Total", _labelFont, "center");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell(" ", _labelFont, "center");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            if (_financingPaid < 0)
            {
                cell = PdfReports.AddText2Cell("($" + Math.Abs(_financingPaid).ToString("#,##0.00") + ")", _labelFont, "right");
            }
            else
            {
                cell = PdfReports.AddText2Cell("$" + _financingPaid.ToString("#,##0.00"), _labelFont, "right");
            }
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            if (_financingInterest < 0)
            {
                cell = PdfReports.AddText2Cell("($" + Math.Abs(_financingInterest).ToString("#,##0.00") + ")", _labelFont, "right");
            }
            else
            {
                cell = PdfReports.AddText2Cell("$" + _financingInterest.ToString("#,##0.00"), _labelFont, "right");
            }
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            if (_financingBalance < 0)
            {
                cell = PdfReports.AddText2Cell("($" + Math.Abs(_financingBalance).ToString("#,##0.00") + ")", _labelFont, "right");
            }
            else
            {
                cell = PdfReports.AddText2Cell("$" + _financingBalance.ToString("#,##0.00"), _labelFont, "right");
            }
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            PdfReports.AddText2Table(table, " ", _normalFont, 2);

            PdfReports.AddText2Table(table, " ", _normalFont, _equityFinancingLayout.Length);
            PdfReports.AddTableNoSplit(document, pgEvent, table);
            table = null;
        }
Exemple #37
0
        private void AddCommonHeader(ref PdfPTable table)
        {
            table = PdfReports.CreateTable(_commonStockLayout, 0);
            iTextSharp.text.pdf.PdfPCell cell =
                PdfReports.AddText2Cell("Common Stock Purchase", _labelFont, "left", _commonStockLayout.Length);
            cell.BackgroundColor = Color.LIGHT_GRAY;
            table.AddCell(cell);

            PdfReports.AddText2Table(table, " ", _normalFont);
            PdfReports.AddText2Table(table, "Shares", _labelFont, "center");
            PdfReports.AddText2Table(table, "Date", _labelFont, "center");
            PdfReports.AddText2Table(table, "Price", _labelFont, "center");
            PdfReports.AddText2Table(table, "Value", _labelFont, "center");
            PdfReports.AddText2Table(table, " ", _normalFont);
        }
Exemple #38
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(iTextSharp.text.Phrase phrase)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #39
0
        public static iTextSharp.text.pdf.PdfPCell AddImage2Table(PdfPTable table, iTextSharp.text.Image img)
        {
            const string METHOD_NAME = "AddImage2Table";

            try {
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(img);
                cell.BorderWidth         = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                table.AddCell(cell);
                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #40
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(iTextSharp.text.Paragraph para, int colSpan)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(para);
                cell.BorderWidth = 0;
                cell.Colspan     = colSpan;

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #41
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Table(PdfPTable table,
                                                                 iTextSharp.text.Paragraph para)
        {
            const string METHOD_NAME = "AddText2Table";

            try {
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(para);
                cell.BorderWidth = 0;
                table.AddCell(cell);

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #42
0
        private void FinishPatronStockData(PdfWriter writer, Document document, ref PdfPTable table, EQStmtEvent pgEvent)
        {
            PdfReports.AddText2Table(table, " ", _normalFont, _patronStockLayout.Length);

            iTextSharp.text.pdf.PdfPCell cell = PdfReports.AddText2Cell("Total Shares Owned", _labelFont, "center");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell(_patronStockShares.ToString("#,##0"), _labelFont, "center");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            PdfReports.AddText2Table(table, " ", _normalFont, _patronStockLayout.Length - 2);
            PdfReports.AddText2Table(table, " ", _normalFont, _patronStockLayout.Length);
            PdfReports.AddTableNoSplit(document, pgEvent, table);
            table = null;
        }
Exemple #43
0
        private void AddFinancingHeader(ref PdfPTable table)
        {
            table = PdfReports.CreateTable(_equityFinancingLayout, 0);

            iTextSharp.text.pdf.PdfPCell cell =
                PdfReports.AddText2Cell("Equity Financing", _labelFont, "left", _equityFinancingLayout.Length);
            cell.BackgroundColor = Color.LIGHT_GRAY;
            table.AddCell(cell);

            PdfReports.AddText2Table(table, " ", _normalFont);
            PdfReports.AddText2Table(table, "Date", _labelFont, "center");
            PdfReports.AddText2Table(table, "Principal Paid", _labelFont, "center");
            PdfReports.AddText2Table(table, "Interest", _labelFont, "center");
            PdfReports.AddText2Table(table, "Balance", _labelFont, "center");
            PdfReports.AddText2Table(table, " ", _normalFont);
            PdfReports.AddText2Table(table, " ", _normalFont);
        }
Exemple #44
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(string text, iTextSharp.text.Font font, int colSpan)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;
                cell.Colspan     = colSpan;

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #45
0
        private void AddUnitRetainHeader(ref PdfPTable table)
        {
            table = PdfReports.CreateTable(_unitRetainsLayout, 0);

            iTextSharp.text.pdf.PdfPCell cell =
                PdfReports.AddText2Cell("Unit Retains", _labelFont, "left", _unitRetainsLayout.Length);
            cell.BackgroundColor = Color.LIGHT_GRAY;
            table.AddCell(cell);

            PdfReports.AddText2Table(table, "Crop Year", _labelFont, "center");
            PdfReports.AddText2Table(table, "Date", _labelFont, "center");
            PdfReports.AddText2Table(table, "Tons Delivered", _labelFont, "center");
            PdfReports.AddText2Table(table, "$/Ton", _labelFont, "center");
            PdfReports.AddText2Table(table, "Amount", _labelFont, "center");
            PdfReports.AddText2Table(table, "$ Paid", _labelFont, "center");
            PdfReports.AddText2Table(table, "Balance", _labelFont, "center");
            PdfReports.AddText2Table(table, " ", _normalFont);
        }
Exemple #46
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Table(PdfPTable table,
                                                                 string text, iTextSharp.text.Font font)
        {
            const string METHOD_NAME = "AddText2Table";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;
                table.AddCell(cell);

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #47
0
        private void AddPatronageRefundHeader(ref PdfPTable table)
        {
            table = PdfReports.CreateTable(_patronageRefundLayout, 0);

            iTextSharp.text.pdf.PdfPCell cell =
                PdfReports.AddText2Cell("Patronage Refunds", _labelFont, "left", _patronageRefundLayout.Length);
            cell.BackgroundColor = Color.LIGHT_GRAY;
            table.AddCell(cell);

            PdfReports.AddText2Table(table, "Crop Year", _labelFont, "center");
            PdfReports.AddText2Table(table, "Date", _labelFont, "center");
            PdfReports.AddText2Table(table, "Tons Delivered", _labelFont, "center");
            PdfReports.AddText2Table(table, "$/Ton", _labelFont, "center");
            PdfReports.AddText2Table(table, "Amount", _labelFont, "center");
            PdfReports.AddText2Table(table, "Initial Pay", _labelFont, "center");
            PdfReports.AddText2Table(table, "Crop Loss Allocation/Pmt", _labelFont, "center");
            PdfReports.AddText2Table(table, "Certificate Paid", _labelFont, "center");
            PdfReports.AddText2Table(table, "Balance", _labelFont, "center");
        }
Exemple #48
0
        private void FinishUnitRetainData(PdfWriter writer, Document document, ref PdfPTable table, EQStmtEvent pgEvent)
        {
            PdfReports.AddText2Table(table, " ", _normalFont, _unitRetainsLayout.Length);

            iTextSharp.text.pdf.PdfPCell cell = PdfReports.AddText2Cell("Total", _labelFont, "center");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            // Date
            cell = PdfReports.AddText2Cell(" ", _labelFont, "right");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell(_unitRetainTons.ToString("#,##0.0000"), _labelFont, "right");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell(" ", _labelFont, "center");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("$" + _unitRetainAmount.ToString("#,##0.00"), _labelFont, "right");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("$" + _unitRetainPaid.ToString("#,##0.00"), _labelFont, "right");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell("$" + _unitRetainBalance.ToString("#,##0.00"), _labelFont, "right");
            cell.BackgroundColor = cell.BackgroundColor = Color_Highlight;
            table.AddCell(cell);

            cell = PdfReports.AddText2Cell(" ", _labelFont, "right");
            table.AddCell(cell);

            PdfReports.AddText2Table(table, " ", _normalFont, _unitRetainsLayout.Length);

            PdfReports.AddTableNoSplit(document, pgEvent, table);
            table = null;
        }
Exemple #49
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(string text, iTextSharp.text.Font font, int hAlign, int vAlign, float fPadding, float borderWidth, int borderType, Color borderColor)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);

                cell.HorizontalAlignment = hAlign;
                cell.VerticalAlignment   = vAlign;
                cell.Padding             = fPadding;
                cell.BorderWidth         = borderWidth;
                cell.Border      = borderType;
                cell.BorderColor = borderColor;

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #50
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)));
        }
        public ActionResult SavePDFOnDirectory()
        {
            var    FileTime     = DateTime.Now.ToFileTime();
            string pdfFilePath  = Server.MapPath("~/Rotativa/PDF");
            string FileName     = FileTime + ".pdf";
            string fullFilePath = pdfFilePath + "\\" + FileName;

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var Imagefile = Request.Files[i];
                var fileName  = Path.GetFileName(Imagefile.FileName + ".png");
                var Imagepath = Path.Combine(Server.MapPath("~/Rotativa/blob"), fileName);
                Imagefile.SaveAs(Imagepath);
                Guid      guid   = Guid.NewGuid();
                Document  doc    = new Document(PageSize.A4_LANDSCAPE, 10f, 10f, 5f, 10f);
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
                doc.Open();
                try
                {
                    Paragraph                     paragraph = new Paragraph("Calender Event Details");
                    iTextSharp.text.Image         Png       = iTextSharp.text.Image.GetInstance(Imagepath);
                    iTextSharp.text.pdf.PdfPCell  cell      = new iTextSharp.text.pdf.PdfPCell(Png);
                    iTextSharp.text.pdf.PdfPTable table     = new iTextSharp.text.pdf.PdfPTable(1);
                    cell.FixedHeight         = 250;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment   = Element.ALIGN_CENTER;
                    Png.ScaleAbsolute(550, 350);
                    table.AddCell(cell);
                    doc.Add(paragraph);
                    doc.Add(Png);
                    doc.Close();
                }
                catch (Exception ex)
                { return(RedirectToAction("Index", "Login", new { ReturnUrl = "/BoomRoom" })); }
            }
            return(Json(new { fileName = FileName }, JsonRequestBehavior.AllowGet));
        }
Exemple #52
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Table(PdfPTable table,
                                                                 string text, iTextSharp.text.Font font, string align)
        {
            const string METHOD_NAME = "AddText2Table";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;
                // debug: comment out above and uncomment below to see cell borders.
                //cell.BorderWidth = 1.0F;
                //cell.BorderColor = Color.BLACK;

                switch (align.ToLower())
                {
                case "left":
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    break;

                case "center":
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    break;

                case "right":
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    break;
                }
                table.AddCell(cell);

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Exemple #53
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);
    }
Exemple #54
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);
    }
Exemple #55
0
        public void GenerarReporte(DataGridView dgv, string cmbestado, string cabeceratitulo, string usuarioactivo, string buscar, string parametro, string estado)
        {
            iTextSharp.text.Image img = Image.GetInstance(Application.StartupPath + @"\images\logo2.png");

            Document doc = new Document(PageSize.LETTER, 30, 20, 40, 60);
            //'indicamos donde vamos a guardar el documento
            string filename = @"C:\ReporteReservas.pdf";
            var    writer   = PdfWriter.GetInstance(doc,
                                                    new FileStream(filename, FileMode.Create));

            writer.PageEvent = new creporteevento(usuarioactivo, buscar, parametro, estado);

            // 'abrimos el archivo
            doc.Open();
            img.SetAbsolutePosition(40, 711);
            img.ScalePercent(40);
            doc.Add(img);

            PdfContentByte rectangulo;                           // 'declaración del rectángulo

            rectangulo = writer.DirectContent;                   // 'código necesario antes de dar coordenadas del rectángulo

            rectangulo.SetLineWidth(1);                          //'configurando el ancho de linea
            rectangulo.SetColorStroke(BaseColor.BLACK);          //'dar color a trazo. Sin esto el rectángulo se dibuja con el ultimo color de trazo configurado
            rectangulo.Rectangle(33.0F, 763.0F, 555.0F, -84.0F); // '100.0F, 580.0F, coordenada punto de inicio
            rectangulo.Stroke();

            iTextSharp.text.Font _FontTitulo     = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 16, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font _cabeceraTitulo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 7, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

            iTextSharp.text.Font _FontCabecera = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            iTextSharp.text.Font _FontDetalle  = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 6, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            iTextSharp.text.Font _FontLogotipo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 6, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            PdfPTable datatable = new PdfPTable(dgv.ColumnCount);

            //'se asignan algunas propiedades para que el diseño del pdf
            datatable.DefaultCell.Padding = 3;
            float[] headerwith = new float[dgv.ColumnCount + 1];
            headerwith = GetColumnsZise(dgv);
            datatable.SetWidths(headerwith);

            datatable.WidthPercentage         = 98;
            datatable.DefaultCell.BorderWidth = 3;

            datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
            datatable.DefaultCell.Border = Rectangle.NO_BORDER;
            //'Se crea el encabezado del pdf
            Paragraph encabezado = new Paragraph(cabeceratitulo, _FontTitulo);

            encabezado.Alignment = Element.ALIGN_CENTER;
            // 'se crea el texto abajo del encabezado
            Paragraph telefono_ = new Paragraph("     TEL. 700-000001 - 3123456", _FontLogotipo);

            telefono_.Alignment = Element.ALIGN_LEFT;

            Paragraph direccion_ = new Paragraph("     Zona Equipetrol Av San Martin #77", _FontLogotipo);

            direccion_.Alignment = Element.ALIGN_LEFT;

            Paragraph correo_ = new Paragraph("     [email protected]" + "   ", _FontLogotipo);

            correo_.Alignment = Element.ALIGN_LEFT;

            Paragraph espacio_ = new Paragraph("" + "   ", _FontLogotipo);

            espacio_.Alignment = Element.ALIGN_LEFT;

            Paragraph totalregistro = new Paragraph("          TOTAL DE REGISTROS: <<  " + dgv.RowCount + "  >> ", _FontCabecera);

            totalregistro.Alignment = Element.ALIGN_LEFT;

            Paragraph linea = new Paragraph("————————————————————————————————————————————");

            //'linea.Add(New Chunk(DGV.RowCount.ToString, _FontCabecera));

            linea.Alignment = Element.ALIGN_CENTER;

            // 'Se capturan los nombres del encabezado del datagridview
            for (int i = 0; i < dgv.ColumnCount; i++)
            {
                string cadena = dgv.Columns[i].HeaderText.ToString();
                iTextSharp.text.pdf.PdfPCell celda = new iTextSharp.text.pdf.PdfPCell(new Phrase(dgv.Columns[i].HeaderText, _cabeceraTitulo));
                celda.Colspan             = 1;
                celda.Padding             = 5;
                celda.BackgroundColor     = iTextSharp.text.pdf.ExtendedColor.LIGHT_GRAY;
                celda.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
                celda.VerticalAlignment   = iTextSharp.text.Element.ALIGN_TOP;
                celda.FixedHeight         = 20.0F;
                //'celda.Width = 100
                celda.Border = 0;
                datatable.AddCell(celda);
            }

            datatable.HeaderRows = 1;
            datatable.DefaultCell.BorderWidth = 1;
            for (int i = 0; i < dgv.RowCount; i++)
            {
                for (int j = 0; j < dgv.ColumnCount; j++)
                {
                    iTextSharp.text.pdf.PdfPCell celda = new iTextSharp.text.pdf.PdfPCell(new Phrase(dgv[j, i].Value.ToString(), _FontDetalle));
                    celda.Colspan             = 1;
                    celda.Padding             = 5;
                    celda.BackgroundColor     = iTextSharp.text.pdf.ExtendedColor.WHITE;
                    celda.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
                    celda.VerticalAlignment   = iTextSharp.text.Element.ALIGN_TOP;
                    celda.Border = 0;
                    datatable.AddCell(celda);
                }
                datatable.CompleteRow();
            }

            //'se agrega el datatable al pdf
            //'doc.SetMargins(40, 40, 40, 100)
            doc.Add(espacio_);
            doc.Add(espacio_);

            doc.Add(encabezado);

            //'doc.Add(Chunk.NEWLINE)
            doc.Add(telefono_);
            doc.Add(direccion_);
            doc.Add(correo_);
            doc.Add(espacio_);
            doc.Add(datatable);
            doc.Add(linea);
            doc.Add(totalregistro);

            PdfPTable tblPrueba = new PdfPTable(3);

            tblPrueba.WidthPercentage = 100;

            doc.Close();
            writer.Close();
            Process.Start(filename);
        }
        public ActionResult Print()
        {
            var students = db.Students.Include(s => s.educationalQualification).Include(s => s.faculty).Include(s => s.year).ToList();

            if (Session["searchString"] != null)
            {
                SearchViewModel x = (SearchViewModel)Session["searchString"];

                if (!String.IsNullOrEmpty(x.searchString1))
                {
                    students = students.Where(s => s.firstName.Contains(x.searchString1) ||
                                              s.secondName.Contains(x.searchString1)).ToList();
                }
                else if (!String.IsNullOrEmpty(x.searchString2))
                {
                    students = students.Where(s => s.socialSecurityNumber.Contains(x.searchString2)).ToList();
                }
                else if (!String.IsNullOrEmpty(x.searchString3))
                {
                    students = students.Where(s => s.phoneNumber.Contains(x.searchString3)).ToList();
                }
            }


            //First you create a Document and a PdfWriter and open the Document.
            Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 15);

            pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
            PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

            pdfDoc.Open();

            //Adding double border
            var content         = pdfWriter.DirectContent;
            var pageBorderRect  = new iTextSharp.text.Rectangle(pdfDoc.PageSize);
            var pageBorderRect2 = new iTextSharp.text.Rectangle(pdfDoc.PageSize);

            pageBorderRect.Left   += pdfDoc.LeftMargin;
            pageBorderRect.Right  -= pdfDoc.RightMargin;
            pageBorderRect.Top    -= pdfDoc.TopMargin;
            pageBorderRect.Bottom += pdfDoc.BottomMargin;

            pageBorderRect2.Left   += pdfDoc.LeftMargin - 5;
            pageBorderRect2.Right  -= pdfDoc.RightMargin - 5;
            pageBorderRect2.Top    -= pdfDoc.TopMargin - 5;
            pageBorderRect2.Bottom += pdfDoc.BottomMargin - 5;

            content.SetColorStroke(BaseColor.BLACK);
            content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);
            content.Rectangle(pageBorderRect2.Left, pageBorderRect2.Bottom, pageBorderRect2.Width, pageBorderRect2.Height);
            content.Stroke();


            //ColumnText.ShowTextAligned(pdfWriter.DirectContent,Element.ALIGN_CENTER, new Phrase("asdasd علي"), 421, 545, 0,PdfWriter.RUN_DIRECTION_RTL,0);

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

            iTextSharp.text.Font fontt  = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.UNDERLINE);
            iTextSharp.text.Font fontt2 = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);

            ColumnText column  = new ColumnText(pdfWriter.DirectContent);
            ColumnText column2 = new ColumnText(pdfWriter.DirectContent);

            column.SetSimpleColumn(0, 520, 470, 570);
            column.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            column.AddElement(new Paragraph("كشف اسماء طلبة جامعة عين شمس", fontt));
            column.Go();


            column.SetSimpleColumn(0, 520, 810, 570);
            column.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            column.AddElement(new Paragraph("قيادة قوات الدفاع الشعبي و العسكري", fontt));
            column.AddElement(new Paragraph("ادارة التربيه العسكريه", fontt));
            string dateNow = DateTime.Now.ToString("dd dddd , MMMM, yyyy", new CultureInfo("ar-AE"));

            column.AddElement(new Paragraph(dateNow, fontt2));
            column.Go();

            column.SetSimpleColumn(0, 0, 200, 80);
            column.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            column.AddElement(new Paragraph("التوقيع (                        ) ", fontt2));
            column.AddElement(new Paragraph("مقدم / مصطفي عبدالله", fontt2));
            column.AddElement(new Paragraph("مدير ادارة التربية العسكرية", fontt2));
            column.Go();

            ////Table
            PdfContentByte pcb   = pdfWriter.DirectContent;
            PdfPTable      table = new PdfPTable(5);

            table.TotalWidth = 782f;

            iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);

            iTextSharp.text.pdf.PdfPCell name    = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "الاسم", font));
            iTextSharp.text.pdf.PdfPCell ssn     = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "الرقم القومي", font));
            iTextSharp.text.pdf.PdfPCell phone   = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "التليفون", font));
            iTextSharp.text.pdf.PdfPCell address = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "العنوان", font));
            iTextSharp.text.pdf.PdfPCell faculty = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "الكلية", font));

            name.RunDirection    = PdfWriter.RUN_DIRECTION_RTL;
            ssn.RunDirection     = PdfWriter.RUN_DIRECTION_RTL;
            phone.RunDirection   = PdfWriter.RUN_DIRECTION_RTL;
            address.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            faculty.RunDirection = PdfWriter.RUN_DIRECTION_RTL;

            table.AddCell(phone);
            table.AddCell(ssn);
            table.AddCell(faculty);
            table.AddCell(address);
            table.AddCell(name);

            for (int i = 0; i < students.Count; i++)
            {
                string cellText5 = students[i].phoneNumber;
                string cellText4 = students[i].socialSecurityNumber;
                string cellText6 = students[i].faculty.facultyName;
                string cellText3 = students[i].address;
                string cellText2 = students[i].firstName + " " + students[i].secondName + " " + students[i].thirdName + " " + students[i].fourthName;

                iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText5, font));
                iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText4, font));
                iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText6, font));
                iTextSharp.text.pdf.PdfPCell cell3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText3, font));
                iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText2, font));


                cell2.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                cell3.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                cell4.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                cell5.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                cell6.RunDirection = PdfWriter.RUN_DIRECTION_RTL;

                table.AddCell(cell5);
                table.AddCell(cell4);
                table.AddCell(cell6);
                table.AddCell(cell3);
                table.AddCell(cell2);
            }

            table.WriteSelectedRows(0, -1, 30, 515, pcb);
            //pdfDoc.Add(table);


            //Chunk c1 = new Chunk("A chunk represents an isolated string. ");
            //font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
            //Chunk c2 = new Chunk("علي صبري",font);


            //column.SetSimpleColumn(30, 30, 810, 515);
            //column.AddElement(table);
            //column.Go();



            //To create a Pdf use the below code and place it on the end.
            pdfWriter.CloseStream = false;
            pdfDoc.Close();
            Response.Buffer      = true;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=StudentEventReport.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();

            return(View());
        }
        private static void ReportBuilder(int cropYear, ArrayList shidList, string busName, ArrayList growerPerformanceList, ArrayList regionCodeList, ArrayList areaCodeList,
                                          ArrayList regionNameList, ArrayList areaNameList, string logoUrl, string filePath, System.IO.FileStream fs)
        {
            const string METHOD_NAME = "ReportBuilder: ";
            const string CharBlank   = " ";
            const string CharAffirm  = "X";

            Document  document = null;
            PdfWriter writer   = null;
            PdfPTable table    = null;
            ShareholderSummaryEvent pgEvent = null;

            iTextSharp.text.Image imgLogo = null;

            int    iShid               = 0;
            string areaCode            = "";
            string regionCode          = "";
            string regionName          = "";
            string areaName            = "";
            int    growerPerformanceID = 0;

            string rptTitle = "Western Sugar Cooperative\nShareholder Summary for " + cropYear.ToString() + " Crop Year";

            string okFertility  = "";
            string okIrrigation = "";
            string okStand      = "";
            string okWeed       = "";
            string okDisease    = "";
            string okVariety    = "";

            string descFertility  = "";
            string descIrrigation = "";
            string descStand      = "";
            string descWeed       = "";
            string descDisease    = "";
            string descVariety    = "";

            // Build the contract information.
            try {
                for (int j = 0; j < shidList.Count; j++)
                {
                    string shid = shidList[j].ToString();
                    iShid = Convert.ToInt32(shid);

                    if (growerPerformanceList.Count == 0)
                    {
                        busName = "";
                        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BeetConn"].ToString())) {
                            using (SqlDataReader dr = WSCField.SharholderSummaryGetAreas(conn, cropYear, iShid)) {
                                while (dr.Read())
                                {
                                    growerPerformanceList.Add(dr["GrowerPerformanceID"].ToString());
                                    regionCodeList.Add(dr["RegionCode"].ToString());
                                    areaCodeList.Add(dr["AreaCode"].ToString());
                                    regionNameList.Add(dr["RegionName"].ToString());
                                    areaNameList.Add(dr["AreaName"].ToString());
                                    if (busName.Length == 0)
                                    {
                                        busName = dr["BusName"].ToString();
                                    }
                                }
                            }
                        }
                    }

                    // ---------------------------------------------------------------------------------------------------------
                    // Given all of the pieces, crop year, shid, growerPerformanceID, region, and area, generate the report
                    // ---------------------------------------------------------------------------------------------------------
                    if (areaCodeList.Count > 0)
                    {
                        for (int i = 0; i < areaCodeList.Count; i++)
                        {
                            growerPerformanceID = Convert.ToInt32(growerPerformanceList[i]);
                            regionCode          = regionCodeList[i].ToString();
                            areaCode            = areaCodeList[i].ToString();
                            regionName          = regionNameList[i].ToString();
                            areaName            = areaNameList[i].ToString();

                            // ------------------------------------------------
                            // Collect the data: Get the report card.
                            // ------------------------------------------------
                            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BeetConn"].ToString())) {
                                using (SqlDataReader dr = WSCField.GrowerAdviceGetBySHID(conn, growerPerformanceID)) {
                                    if (dr.Read())
                                    {
                                        //busName = dr["gadBusinessName"].ToString();
                                        okFertility  = dr["gadGoodFertilityManagement"].ToString();
                                        okIrrigation = dr["gadGoodIrrigationManagement"].ToString();
                                        okStand      = dr["gadGoodStandEstablishment"].ToString();
                                        okWeed       = dr["gadGoodWeedControl"].ToString();
                                        okDisease    = dr["gadGoodDiseaseControl"].ToString();
                                        okVariety    = dr["gadGoodVarietySelection"].ToString();

                                        descFertility  = dr["gadTextFertilityManagement"].ToString();
                                        descIrrigation = dr["gadTextIrrigationManagement"].ToString();
                                        descStand      = dr["gadTextStandEstablishment"].ToString();
                                        descWeed       = dr["gadTextWeedControl"].ToString();
                                        descDisease    = dr["gadTextDiseaseControl"].ToString();
                                        descVariety    = dr["gadTextVarietySelection"].ToString();
                                    }
                                    else
                                    {
                                        //busName = "";
                                        okFertility  = "";
                                        okIrrigation = "";
                                        okStand      = "";
                                        okWeed       = "";
                                        okDisease    = "";
                                        okVariety    = "";

                                        descFertility  = "";
                                        descIrrigation = "";
                                        descStand      = "";
                                        descWeed       = "";
                                        descDisease    = "";
                                        descVariety    = "";
                                    }
                                }
                            }

                            if (document == null)
                            {
                                // IF YOU CHANGE MARGINS, CHANGE YOUR TABLE LAYOUTS !!!
                                //  ***  US LETTER: 612 X 792  ***
                                //document = new Document(iTextSharp.text.PageSize.LETTER, 36, 36, 54, 72);
                                document = new Document(PortraitPageSize.PgPageSize, PortraitPageSize.PgLeftMargin,
                                                        PortraitPageSize.PgRightMargin, PortraitPageSize.PgTopMargin, PortraitPageSize.PgBottomMargin);

                                // we create a writer that listens to the document
                                // and directs a PDF-stream to a file
                                writer = PdfWriter.GetInstance(document, fs);

                                imgLogo = PdfReports.GetImage(logoUrl, 127, 50, iTextSharp.text.Element.ALIGN_CENTER);

                                // Attach my override event handler(s)
                                //busName = dr["Business Name"].ToString();
                                pgEvent = new ShareholderSummaryEvent();
                                pgEvent.FillEvent(cropYear, shid, busName, rptTitle, regionName, areaName, imgLogo);

                                writer.PageEvent = pgEvent;

                                // Open the document
                                document.Open();
                            }
                            else
                            {
                                // everytime thru kick out a new page because we're on a different shid/region/area combination.
                                pgEvent.FillEvent(cropYear, shid, busName, rptTitle, regionName, areaName, imgLogo);
                                document.NewPage();
                            }

                            // -----------------------------------------------------
                            // Create the report card
                            // -----------------------------------------------------
                            table = PdfReports.CreateTable(_adviceTableLayout, 1);

                            Color borderColor   = Color.BLACK;  //new Color(255, 0, 0);
                            float borderWidth   = 1.0F;
                            int   borderTypeAll = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
                            float fPadding      = 3;

                            // HEADER
                            iTextSharp.text.pdf.PdfPCell cell = PdfReports.AddText2Cell("Okay", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                                                        fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Opportunity\nfor\nImprovement", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Big Six Growing Practices", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            /// ----------------------------------------
                            // TBODY
                            /// ----------------------------------------
                            // Fertility
                            cell = PdfReports.AddText2Cell((okFertility == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okFertility == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Fertility Management", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Irrigation
                            cell = PdfReports.AddText2Cell((okIrrigation == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okIrrigation == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Irrigation Water Management", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Stand
                            cell = PdfReports.AddText2Cell((okStand == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okStand == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Stand Establishment (Harvest Plant Population)", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Weed
                            cell = PdfReports.AddText2Cell((okWeed == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okWeed == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Weed Control", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Disease
                            cell = PdfReports.AddText2Cell((okDisease == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okDisease == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Disease & Insect Control", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Varitey
                            cell = PdfReports.AddText2Cell((okVariety == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okVariety == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Proper Variety Selection", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            PdfReports.AddText2Table(table, " ", _normalFont, 3);

                            PdfReports.AddTableNoSplit(document, pgEvent, table);

                            // ==========================================================
                            // Recommendations for Improvement.
                            // ==========================================================
                            table = PdfReports.CreateTable(_adviceTableLayout, 1);

                            // Caption
                            iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase("Recommendations for Improvement", _labelFont);
                            cell         = new iTextSharp.text.pdf.PdfPCell(phrase);
                            cell.Colspan = 3;

                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.VerticalAlignment   = PdfPCell.ALIGN_BOTTOM;
                            cell.Padding             = fPadding;
                            cell.BorderWidth         = borderWidth;
                            cell.Border      = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER;
                            cell.BorderColor = borderColor;
                            table.AddCell(cell);

                            // Content
                            phrase = new iTextSharp.text.Phrase((descFertility.Length > 0 ? descFertility + "\n\n" : "") +
                                                                (descIrrigation.Length > 0 ? descIrrigation + "\n\n" : "") +
                                                                (descStand.Length > 0 ? descStand + "\n\n" : "") +
                                                                (descWeed.Length > 0 ? descWeed + "\n\n" : "") +
                                                                (descDisease.Length > 0 ? descDisease + "\n\n" : "") +
                                                                (descVariety.Length > 0 ? descVariety + "\n\n" : ""), _normalFont);

                            cell         = new iTextSharp.text.pdf.PdfPCell(phrase);
                            cell.Colspan = 3;

                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.VerticalAlignment   = PdfPCell.ALIGN_BOTTOM;
                            cell.Padding             = fPadding;
                            cell.BorderWidth         = borderWidth;
                            cell.Border      = Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
                            cell.BorderColor = borderColor;
                            table.AddCell(cell);

                            PdfReports.AddText2Table(table, " ", _normalFont, table.NumberOfColumns);
                            PdfReports.AddText2Table(table, " ", _normalFont, table.NumberOfColumns);

                            PdfReports.AddTableNoSplit(document, pgEvent, table);

                            // ------------------------------------------------
                            // Create the contract dump.
                            // ------------------------------------------------
                            ArrayList cntPerfs;
                            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BeetConn"].ToString())) {
                                cntPerfs = WSCField.ShareholderSummaryContracts(conn, iShid, cropYear, regionCode, areaCode);
                            }

                            // =======================================
                            // HEADER
                            // =======================================
                            table = PdfReports.CreateTable(_contractTableLayout, 0);
                            pgEvent.BuildContractDumpHeader(document, _contractTableLayout);
                            pgEvent.ContractTableLayout = _contractTableLayout;

                            // DATA
                            for (int k = 0; k < cntPerfs.Count; k++)
                            {
                                ContractPerformanceState perf = (ContractPerformanceState)cntPerfs[k];

                                switch (perf.RowType)
                                {
                                case 1:

                                    table = PdfReports.CreateTable(_contractTableLayout, 0);

                                    PdfReports.AddText2Table(table, perf.ContractNumber, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.ContractStation, _normalFont);
                                    PdfReports.AddText2Table(table, perf.FieldDescription, _normalFont);
                                    PdfReports.AddText2Table(table, perf.LandownerName, _normalFont);
                                    PdfReports.AddText2Table(table, perf.HarvestFinalNetTons, _normalFont, "right");
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    PdfReports.AddTableNoSplit(document, pgEvent, table);

                                    break;

                                case 2:

                                    table = PdfReports.CreateTable(_contractTableLayout, 0);

                                    PdfReports.AddText2Table(table, " ", _normalFont, _contractTableLayout.Length);
                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, "Overall Average", _labelFont, 3);
                                    PdfReports.AddText2Table(table, perf.HarvestFinalNetTons, _normalFont, "right");
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    break;

                                case 3:

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, "Top 20% Area Average", _labelFont, 4);
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    break;

                                case 4:

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, "Your Rankings", _labelFont, 10);

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, areaName, _labelFont, 4);
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    break;

                                case 5:

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, regionName, _labelFont, 4);
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    PdfReports.AddTableNoSplit(document, pgEvent, table);

                                    break;
                                }
                            }

                            pgEvent.ContractTableLayout = null;
                        }
                    }

                    // --------------------------------------------
                    // --------  reset for next iteration  --------
                    // --------------------------------------------
                    growerPerformanceList.Clear();
                    regionCodeList.Clear();
                    areaCodeList.Clear();
                    regionNameList.Clear();
                    areaNameList.Clear();
                }

                // ======================================================
                // Close document
                // ======================================================
                if (document != null)
                {
                    pgEvent.IsDocumentClosing = true;
                    document.Close();
                    document = null;
                }
                if (writer == null)
                {
                    // Warn that we have no data.
                    WSCIEMP.Common.CWarning warn = new WSCIEMP.Common.CWarning("No records matched your report criteria.");
                    throw (warn);
                }
            }
            catch (Exception ex) {
                string errMsg = "document is null: " + (document == null).ToString() + "; " +
                                "writer is null: " + (writer == null).ToString();
                WSCIEMP.Common.CException wscex = new WSCIEMP.Common.CException(MOD_NAME + METHOD_NAME + errMsg, ex);
                throw (wscex);
            }
            finally {
                if (document != null)
                {
                    pgEvent.IsDocumentClosing = true;
                    document.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Exemple #58
-1
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document(PageSize.A5.Rotate())) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        writer.PdfVersion = PdfWriter.VERSION_1_5;
        writer.ViewerPreferences = PdfWriter.PageModeFullScreen;
        writer.PageEvent = new TransitionDuration();        
        // step 3
        document.Open();
        // step 4
        IEnumerable<Movie> movies = PojoFactory.GetMovies();
        Image img;
        PdfPCell cell;
        PdfPTable table = new PdfPTable(6);
        string RESOURCE = Utility.ResourcePosters;
        foreach (Movie movie in movies) {
          img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"));
          cell = new PdfPCell(img, true);
          cell.Border = PdfPCell.NO_BORDER;
          table.AddCell(cell);
        }
        document.Add(table);
      }
    }
        public override void OnStartPage(PdfWriter writer, iTextSharp.text.Document document)
        {
            iTextSharp.text.Image header = iTextSharp.text.Image.GetInstance(PathResolver.MapPath("images/ADB_Logo.gif"));

            PdfPTable tableHeader = new PdfPTable(2);
            tableHeader.WidthPercentage = 100;

            PdfPCell imageHeaderCell = new PdfPCell(header);
            imageHeaderCell.Rowspan = 2;
            imageHeaderCell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            imageHeaderCell.Border = 0;
            imageHeaderCell.PaddingBottom = 3;
            tableHeader.AddCell(imageHeaderCell);

            Font helvetica20 = FontFactory.GetFont(FontFactory.HELVETICA, 16);
            PdfPCell typeNameCell = new PdfPCell(new Phrase(TypesReader.GetDiagramName(this.type), helvetica20));
            typeNameCell.HorizontalAlignment = 2;
            typeNameCell.Border = 0;
            tableHeader.AddCell(typeNameCell);

            PdfPCell adbCell = new PdfPCell(new Phrase(GlobalStringResource.ADB, helvetica20));
            adbCell.HorizontalAlignment = 2;
            adbCell.Border = 0;
            tableHeader.AddCell(adbCell);

            PdfPCell lineCell = new PdfPCell();
            lineCell.Colspan = 2;
            lineCell.Border = 1;
            lineCell.PaddingBottom = 5;
            tableHeader.AddCell(lineCell);

            document.Add(tableHeader);
        }
        private static void HeaderGeneration(PdfPTable table, DateTime d)
        {
            string date = d.Date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);
            Font verdana2 = FontFactory.GetFont("Verdana", 12, Font.BOLD);

            d = d.Date;
            PdfPCell dateCell = new PdfPCell(new Phrase("Date: " + date));
            dateCell.Colspan = 5;
            dateCell.BackgroundColor = new BaseColor(242, 242, 242);
            table.AddCell(dateCell);

            BaseColor color = new BaseColor(217, 217, 217);

            PdfPCell product = new PdfPCell(new Phrase("Product", verdana2));
            product.BackgroundColor = color;
            table.AddCell(product);

            PdfPCell quantity = new PdfPCell(new Phrase("Quantity", verdana2));
            quantity.BackgroundColor = color;
            table.AddCell(quantity);

            PdfPCell unitPrice = new PdfPCell(new Phrase("Unit Price", verdana2));
            unitPrice.BackgroundColor = color;
            table.AddCell(unitPrice);

            PdfPCell location = new PdfPCell(new Phrase("Location", verdana2));
            location.BackgroundColor = color;
            table.AddCell(location);

            PdfPCell sum = new PdfPCell(new Phrase("Sum", verdana2));
            sum.BackgroundColor = color;
            table.AddCell(sum);
        }