Base class for Color, serves as wrapper class for T:Android.Graphics.Color to allow extension.
 // 函数描述:设置字体的样式
 public static Font BaseFontAndSize(string fontName, int size, int style, BaseColor baseColor)
 {
     BaseFont.AddToResourceSearch("iTextAsian.dll");
     BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
     string fileName;
     switch (fontName)
     {
         case "黑体":
             fileName = "SIMHEI.TTF";
             break;
         case "华文中宋":
             fileName = "STZHONGS.TTF";
             break;
         case "宋体":
             fileName = "simsun_1.ttf";
             break;
         default:
             fileName = "simsun_1.ttf";
             break;
     }
     var baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + fileName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
     var fontStyle = style < -1 ? Font.NORMAL : style;
     var font = new Font(baseFont, size, fontStyle, baseColor);
     return font;
 }
        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);
        }
示例#3
0
 /**
 * Creates a new instance of the LineSeparator class.
 * @param lineWidth      the thickness of the line
 * @param percentage the width of the line as a percentage of the available page width
 * @param color          the color of the line
 * @param align          the alignment
 * @param offset     the offset of the line relative to the current baseline (negative = under the baseline)
 */
 public LineSeparator(float lineWidth, float percentage, BaseColor lineColor, int align, float offset) {
     this.lineWidth = lineWidth;
     this.percentage = percentage;
     this.lineColor = lineColor;
     this.alignment = align;
     this.offset = offset;
 }
        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);
        }
示例#5
0
        public CustomFontFactory(
            string defaultFontFilePath,
            string defaultFontEncoding = BaseFont.IDENTITY_H,
            bool defaultFontEmbedding = BaseFont.EMBEDDED,
            float? defaultFontSize = null,
            int? defaultFontStyle = null,
            BaseColor defaultFontColor = null,
            bool automaticalySetReplacementForNullables = true)
        {
            //set default font properties
            DefaultFontPath = defaultFontFilePath;
            DefaultFontEncoding = defaultFontEncoding;
            DefaultFontEmbedding = defaultFontEmbedding;
            DefaultFontColor = defaultFontColor ?? DEFAULT_FONT_COLOR;
            DefaultFontSize = defaultFontSize ?? DEFAULT_FONT_SIZE;
            DefaultFontStyle = defaultFontStyle ?? DEFAULT_FONT_STYLE;

            //set default replacement options
            ReplaceFontWithDefault = false;
            ReplaceEncodingWithDefault = true;
            ReplaceEmbeddingWithDefault = false;

            if (automaticalySetReplacementForNullables)
            {
                ReplaceSizeWithDefault = defaultFontSize.HasValue;
                ReplaceStyleWithDefault = defaultFontStyle.HasValue;
                ReplaceColorWithDefault = defaultFontColor != null;
            }

            //define default font
            DefaultBaseFont = BaseFont.CreateFont(DefaultFontPath, DefaultFontEncoding, DefaultFontEmbedding);

            //register system fonts
            FontFactory.RegisterDirectories();
        }
示例#6
0
 protected void SetColorSpace(BaseColor color) {
     cspace = color;
     int type = ExtendedColor.GetType(color);
     PdfObject colorSpace = null;
     switch (type) {
         case ExtendedColor.TYPE_GRAY: {
             colorSpace = PdfName.DEVICEGRAY;
             break;
         }
         case ExtendedColor.TYPE_CMYK: {
             colorSpace = PdfName.DEVICECMYK;
             break;
         }
         case ExtendedColor.TYPE_SEPARATION: {
             SpotColor spot = (SpotColor)color;
             colorDetails = writer.AddSimple(spot.PdfSpotColor);
             colorSpace = colorDetails.IndirectReference;
             break;
         }
         case ExtendedColor.TYPE_PATTERN:
         case ExtendedColor.TYPE_SHADING: {
             ThrowColorSpaceError();
             break;
         }
         default:
             colorSpace = PdfName.DEVICERGB;
             break;
     }
     shading.Put(PdfName.COLORSPACE, colorSpace);
 }
示例#7
0
 internal PdfPatternPainter(PdfWriter wr, BaseColor defaultColor) : this(wr) {
     stencil = true;
     if (defaultColor == null)
         this.defaultColor = BaseColor.GRAY;
     else
         this.defaultColor = defaultColor;
 }
示例#8
0
		public static PdfPCell GetCell(string content, Font font, int horizontalAlignment, BaseColor background = null)
		{
			return new PdfPCell(new Phrase(content, font))
			{
				BackgroundColor = background,
				HorizontalAlignment = horizontalAlignment,
			};
		}
 private PdfPCell CreatePdfCell(string cellInfo, Font font, BaseColor backgroundColor, int colSpan = 0, int horizontalAligment = 0)
 {
     var cell = new PdfPCell(new Phrase(cellInfo, font));
     cell.BackgroundColor = backgroundColor;
     cell.Colspan = colSpan;
     cell.HorizontalAlignment = horizontalAligment;
     return cell;
 }
示例#10
0
        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);
        }
示例#11
0
 public override Font GetFont(String fontname, String encoding, bool embedded, float size, int style,
                              BaseColor color)
 {
     Font font = GetFont(fontname, encoding, size, style);
     if (color != null) {
         font.SetColor(color.R, color.G, color.B);
     }
     return font;
 }
        public static void CreateReport()
        {
            string directoryCreating = "..\\..\\..\\SalesReports.pdf";
            if (File.Exists(directoryCreating))
            {
                File.Delete(directoryCreating);
            }
            Document pdfReport = new Document();
            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfReport,
                new System.IO.FileStream(directoryCreating, System.IO.FileMode.Create));

            pdfReport.Open();
            using (pdfReport)
            {
                PdfPTable reportTable = new PdfPTable(5);

                AddCellToTable(reportTable, "Aggregated Sales Report", TextAlign.Center, 5);

                using (var supermarketEntities = new SupermarketEntities())
                {
                    var reportsOrderedByDate = supermarketEntities.Reports.OrderBy(x => x.ReportDate);
                    var currentDate = reportsOrderedByDate.First().ReportDate;
                    decimal currentSum = 0;
                    decimal totalSum = 0;
                    var headerColor = new BaseColor(217, 217, 217);
                    AddHeader(reportTable, currentDate, headerColor);
                    // aligment  0 = left, 1 = center, 2 = right

                    foreach (var report in reportsOrderedByDate)
                    {
                        if (currentDate != report.ReportDate)
                        {
                            AddFooter(reportTable, "Total sum for " + currentDate.ToString(), currentSum);
                            currentSum = 0;
                            currentDate = report.ReportDate;
                            AddHeader(reportTable, currentDate, headerColor);
                        }
                        else
                        {
                            AddCellToTable(reportTable, report.Product.ProductName.ToString(), 0);
                            AddCellToTable(reportTable, report.Quantity.ToString(), 0);
                            AddCellToTable(reportTable, report.UnitPrice.ToString(), 0);
                            AddCellToTable(reportTable, report.Supermarket.ToString(), 0);
                            AddCellToTable(reportTable, report.Sum.ToString(), 0);
                            totalSum += (decimal)report.Sum;
                            currentSum += (decimal)report.Sum;
                        }
                    }

                    AddFooter(reportTable, "Total sum for " + currentDate.ToString(), currentSum);
                    AddFooter(reportTable, "Grand total:", totalSum);
                }

                pdfReport.Add(reportTable);
            }
        }
示例#13
0
 /// <summary>
 /// MonthCalendar's attributes.
 /// </summary>
 public CalendarAttributes()
 {
     RelativeColumnWidths = new float[] { 1, 1, 1, 1, 1, 1, 1 };
     BorderColor = BaseColor.LIGHT_GRAY;
     GradientStartColor = new BaseColor(Color.LightGray.ToArgb());
     GradientEndColor = new BaseColor(Color.DarkGray.ToArgb());
     Padding = 5;
     UseLongDayNamesOfWeek = true;
     DayNamesRowBackgroundColor = new BaseColor(Color.WhiteSmoke.ToArgb());
 }
示例#14
0
        private static PdfPCell CreateFooterCell(string cellValue, int colspan = 1, bool isBold = false, BaseColor backgroundColor = null)
        {
            PdfPCell cell = new PdfPCell(new Phrase(cellValue, new Font(DefaultFont, 10f, isBold ? Font.BOLD : Font.NORMAL)));
            cell.Colspan = colspan;
            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            cell.Padding = DefaultCellPadding;
            cell.BackgroundColor = backgroundColor;

            return cell;
        }
示例#15
0
 public static PdfPCell ColoredTxtCell(string content, BaseColor color = null)
 {
     PdfPCell c = new PdfPCell(new Phrase(content));
     //     c.Border = PdfPCell.BOTTOM_BORDER | PdfPCell.TOP_BORDER | PdfPCell.LEFT_BORDER | PdfPCell.RIGHT_BORDER;
     c.Padding = 4;
     c.BorderWidth = 1;
     c.BorderColor = new BaseColor(System.Drawing.Color.Transparent);
     _getColoredCell(c, color);
     return c;
 }
示例#16
0
        /// <summary>
        /// Creates PDF reports and saves them as a PDF file
        /// </summary>
        public static void GeneratePdfReport()
        {
            File.Delete(PdfPath + PdfFileName);
            var repo = new MSSqlRepository();
            var pdfData = repo.GetDataForPdfExport();
            var doc = new Document();

            PdfWriter.GetInstance(doc, new FileStream(PdfPath + PdfFileName, FileMode.Create));

            doc.Open();

            PdfPTable table = new PdfPTable(RowCountInPdfExport);
            table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            table.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

            var headerBackground = new BaseColor(204, 204, 204);
            PdfPCell headerCell = new PdfPCell(new Phrase("Sample PDF Export From the Football Manager"));
            headerCell.Colspan = RowCountInPdfExport;
            headerCell.Padding = 10f;
            headerCell.HorizontalAlignment = 1;
            headerCell.BackgroundColor = headerBackground;
            table.AddCell(headerCell);

            string[] col = { "Date", "Staduim", "Home Team", "Away Team", "Result" };

            for (int i = 0; i < col.Length; ++i)
            {
                PdfPCell columnCell = new PdfPCell(new Phrase(col[i]));
                columnCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                columnCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                columnCell.BackgroundColor = headerBackground;
                table.AddCell(columnCell);
            }

            foreach (var item in pdfData)
            {
                PdfPCell townCell = new PdfPCell(new Phrase(item.Key));
                townCell.Colspan = RowCountInPdfExport;
                townCell.Padding = 10f;
                table.AddCell(townCell);

                foreach (var match in item.Value)
                {
                    table.AddCell(match.Date.Day + "." + match.Date.Month + "." + match.Date.Year);
                    table.AddCell(match.Stadium);
                    table.AddCell(match.HomeTeam);
                    table.AddCell(match.AwayTeam);
                    table.AddCell(match.Result);
                }
            }

            doc.Add(table);
            doc.Close();
            Process.Start(PdfPath);
        }
示例#17
0
 // Public Methods (6)
 /// <summary>
 /// Adds a border to an existing PdfGrid
 /// </summary>
 /// <param name="table">Table</param>
 /// <param name="borderColor">Border's color</param>
 /// <param name="spacingBefore">Spacing before the table</param>
 /// <returns>A new PdfGrid</returns>
 public static PdfGrid AddBorderToTable(this PdfGrid table, BaseColor borderColor, float spacingBefore)
 {
     var outerTable = new PdfGrid(numColumns: 1)
     {
         WidthPercentage = table.WidthPercentage,
         SpacingBefore = spacingBefore
     };
     var pdfCell = new PdfPCell(table) { BorderColor = borderColor };
     outerTable.AddCell(pdfCell);
     return outerTable;
 }
示例#18
0
 public override Font GetFont(String fontname, String encoding, bool embedded, float size, int style, BaseColor color) {
     String substFontName = null;
     Font font = base.GetFont(fontname != null && fontSubstitutionMap.TryGetValue(fontname, out substFontName) ? substFontName : fontname, _baseFontEncoding, false, size, style, color);
     if (font.BaseFont != null) {
         float ascent = Math.Max(font.BaseFont.GetFontDescriptor(BaseFont.ASCENT, 1000f), font.BaseFont.GetFontDescriptor(BaseFont.BBOXURY, 1000f));
         float descent = Math.Min(font.BaseFont.GetFontDescriptor(BaseFont.DESCENT, 1000f), font.BaseFont.GetFontDescriptor(BaseFont.BBOXLLY, 1000f));
         font.BaseFont.SetFontDescriptor(BaseFont.ASCENT, ascent);
         font.BaseFont.SetFontDescriptor(BaseFont.DESCENT, descent);
     }
     return font;
 }
        /*
         * Create a centered cell and insert it on the table.
         *
         * myPhrase -> simple string
         * pFontName -> Font type, it could be "Tahoma", "Arial", "Helvetica", etc.
         * pFontSize -> The size of the letters in pixels.
         * pBackGColor -> The cell background color. Ex: BaseColor.WHITE, BaseColor.LIGHT_GRAY, etc.
         */
        private PdfPCell createCell(String myPhrase, String pFontName, float pfontSize,
                                    iTextSharp.text.BaseColor pBackGColor)
        {
            this.Set_fontStyle(pFontName, pfontSize);
            this._pdfPCell = new PdfPCell(new Phrase(myPhrase, _fontStyle));
            this._pdfPCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            this._pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER;
            this._pdfPCell.BackgroundColor     = pBackGColor;
            _pdfPTable.AddCell(this._pdfPCell);

            return(this._pdfPCell);
        }
示例#20
0
		static PDFStyle()
		{
			var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Arial.TTF");
			BaseFont = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			NormalFont = new Font(BaseFont, Font.DEFAULTSIZE, Font.NORMAL);
			BoldFont = new Font(BaseFont, Font.DEFAULTSIZE, Font.BOLD);

			TextFont = new Font(BaseFont, 12, Font.NORMAL);
			BoldTextFont = new Font(BaseFont, 12, Font.BOLD);
			HeaderFont = new Font(BaseFont, 16, Font.BOLD);
			HeaderBackground = new BaseColor(unchecked((int)0xFFD3D3D3));
		}
示例#21
0
        private String DumpColor(BaseColor col) {
            StringBuilder colBuf = new StringBuilder();
            colBuf.Append("r:");
            colBuf.Append(col.R);
            colBuf.Append(" g:");
            colBuf.Append(col.G);
            colBuf.Append(" b:");
            colBuf.Append(col.B);
            colBuf.Append(" a:");
            colBuf.Append(col.A);

            return colBuf.ToString();
        }
示例#22
0
        public static bool Generate(string filename)
        {
            Document document = new Document(PageSize.A4, 0f, 0f, 0f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
            document.Open();

            PdfContentByte canvas = writer.DirectContent;

            Font font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10);

            string[] captions = { "ATM", "CASH", "WEB", "MOBILE" };
            //double[] values = { 2, 60, 20, 18 };
            double[] values = { 5, 60, 35, 0 };
            PieChart chart = new PieChart(values, captions);
            canvas.DrawPieChart(chart, 110, 730, 100);
            canvas.DrawPieChart(chart, 410, 730, 60);

            string[] captions2 = { "CAPTION 1", "CAPTION 2", "CAPTION 3", "CAPTION 4", "CAPTION 5", "CAPTION 6", "CAPTION 7", "CAPTION 8", "CAPTION 9", "CAPTION 10" };
            double[] values2 = { 100, 80, 60, 40, 50, 60, 30, 0, 90, 40 };
            chart = new PieChart(values2, captions2);
            canvas.DrawPieChart(chart, 110, 520, 100, font);
            canvas.DrawPieChart(chart, 410, 520, 60);

            //string[] captions3 = { "CAPTION 1", "CAPTION 2", "CAPTION 3" };
            //double[] values3 = { 100, 80, 60 };
            //System.Drawing.Color[] colors = new System.Drawing.Color[] { System.Drawing.Color.Black,
            //    System.Drawing.Color.CornflowerBlue,
            //    System.Drawing.Color.Brown };

            //chart = new PieChart(values3, captions3, colors);
            //canvas.DrawPieChart(chart, 110, 300, 100, font);
            //canvas.DrawPieChart(chart, 410, 300, 60);

            string[] captions4 = { "CAPTION 1", "CAPTION 2", "CAPTION 3", "CAPTION 4", "CAPTION 5" };
            double[] values4 = { 100, 80, 60, 50, 50 };
            BaseColor pantome376 = new BaseColor(130, 197, 91);
            BaseColor pantone369 = new BaseColor(95, 182, 85);
            BaseColor pantonecool = new BaseColor(88, 89, 91);
            BaseColor pantone447 = new BaseColor(67, 66, 61);
            BaseColor pantonecoolLight = new BaseColor(173, 216, 230);
            BaseColor[] colors4 = { pantome376, pantone369, pantonecool, pantone447, pantonecoolLight };
            chart = new PieChart(values4, captions4, colors4);
            canvas.DrawPieChart(chart, 110, 300, 100, font);
            canvas.DrawPieChart(chart, 410, 300, 60);

            document.Close();
            return true;
        }
 public static PdfPCell CreateCell(string str, int align = Element.ALIGN_CENTER, float fixedHeight = -1, BaseColor borderColor = null, int colSpan = 1, Fonts font = Fonts.Standard)
 {
     var c = new PdfPCell(GetPhrase(str, font))
     {
         HorizontalAlignment = align,
         VerticalAlignment = Element.ALIGN_TOP,
         Padding = 5,
         BorderColor = borderColor ?? BaseColor.BLACK,
         Colspan = colSpan
     };
     if (fixedHeight > 0)
     {
         c.FixedHeight = fixedHeight;
     }
     c.PaddingTop = 2;
     return c;
 }
示例#24
0
		public static PdfPCell GetImageTextCell(string imageSource, string text, float partial, BaseColor background = null)
		{
			var image = GetImage(imageSource);
			var nestedTable = new PdfPTable(2);
			nestedTable.SetWidths(new float[] { 1f, partial });
			nestedTable.DefaultCell.Border = 0;
			if (image == null)
				nestedTable.AddCell("");
			else
				nestedTable.AddCell(image);
			nestedTable.AddCell(new Phrase(text, PDFStyle.NormalFont));

			return new PdfPCell(nestedTable)
			{
				Padding = 0,
				BackgroundColor = background
			};
		}
示例#25
0
        /// <summary>
        /// Draws a rectangular gradient background color.
        /// </summary>
        /// <param name="position">The coordinates of the cell</param>
        /// <param name="canvases">An array of PdfContentByte to add text or graphics</param>
        /// <param name="startColor">Gradient's Start Color</param>
        /// <param name="endColor">Gradient's End Color</param>
        public static void DrawGradientBackground(this Rectangle position, PdfContentByte[] canvases, BaseColor startColor, BaseColor endColor)
        {
            if (startColor == null || endColor == null) return;

            var cb = canvases[PdfPTable.BACKGROUNDCANVAS];
            cb.SaveState();

            var shading = PdfShading.SimpleAxial(
                                    cb.PdfWriter,
                                    position.Left, position.Top, position.Left, position.Bottom,
                                    startColor, endColor);
            var shadingPattern = new PdfShadingPattern(shading);

            cb.SetShadingFill(shadingPattern);
            cb.Rectangle(position.Left, position.Bottom, position.Width, position.Height);
            cb.Fill();

            cb.RestoreState();
        }
        private static PdfPTable CreateGrandTotalTable(decimal sum)
        {
            var grandTotalTable = new PdfPTable(new float[] { 2, 1, 1.5f, 3.5f, 1 });
            grandTotalTable.WidthPercentage = 100f;
            Font grandTotalTextFont = FontFactory.GetFont("Arial", 11);
            var grandTotalParagraph = new Paragraph("Grand total: ", grandTotalTextFont);
            var grandTotalTextCell = new PdfPCell(grandTotalParagraph);
            grandTotalTextCell.Padding = 5;
            grandTotalTextCell.Colspan = 4;
            var backgroundColor = new BaseColor(88, 186, 209);
            grandTotalTextCell.BackgroundColor = backgroundColor;
            grandTotalTextCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            Font grandSumFont = FontFactory.GetFont("Arial", 11, Font.BOLD);
            var grandSumParagraph = new Paragraph(sum.ToString(), grandSumFont);
            var grandSumCell = new PdfPCell(grandSumParagraph);
            grandSumCell.BackgroundColor = backgroundColor;
            grandSumCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            grandTotalTable.AddCell(grandTotalTextCell);
            grandTotalTable.AddCell(grandSumCell);

            return grandTotalTable;
        }
示例#27
0
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            //base.OnEndPage(writer, document);
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

            iTextSharp.text.Font times    = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            PdfPTable            tbHeader = new PdfPTable(3);

            tbHeader.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbHeader.DefaultCell.Border = 0;
            string path = Directory.GetCurrentDirectory();

            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@path + "\\logo2.PNG");
            img.SetAbsolutePosition(0, 650);
            img.ScaleToFit(30f, 50F);
            tbHeader.AddCell(img);
            // tbHeader.AddCell(new Paragraph());
            PdfPCell _cell = new PdfPCell(new Paragraph("INSTITUTO PARA EL REGISTRO DEL TERRITORIO"));

            _cell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
            _cell.Border = 0;
            tbHeader.AddCell(_cell);
            _cell = new PdfPCell(new Paragraph("DIRECCIÓN DEL REGISTRO PÚBLICO DE LA PROPIEDAD Y DEL COMERCIO", times));
            _cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell.Border = 0;
            tbHeader.AddCell(_cell);
            //         _cell = new PdfPCell(new Paragraph("CERTIFICADO DE EXISTENCIA O INEXISTENCIA DE GRAVAMENES ANTECEDENTES REGISTRALES", times));
            //tbHeader.AddCell(new Paragraph());
            tbHeader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin) + 40, writer.DirectContent);

            //segundo encabezado

            iTextSharp.text.Font times2 = new iTextSharp.text.Font(bfTimes, 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            //var MyFontBold = FontFactory.GetFont(FontFactory.TIMES_BOLD, 8);
            var       FontColour  = new iTextSharp.text.BaseColor(255, 0, 0);
            var       MyFontBold  = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD);
            var       MyArialFont = FontFactory.GetFont("Arial", 8);
            PdfPTable tbHeader2   = new PdfPTable(1);

            tbHeader2.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbHeader2.DefaultCell.Border = 1;
            _cell = new PdfPCell(new Paragraph("___________________________________________________________________________________________________________________", times));
            _cell.HorizontalAlignment = Element.ALIGN_CENTER;
            _cell.Border = 0;
            tbHeader2.AddCell(_cell);
            tbHeader2.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin) - 34, writer.DirectContent);
            PdfPTable tbHeader3 = new PdfPTable(1);

            tbHeader3.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbHeader3.DefaultCell.Border = 0;
            _cell = new PdfPCell(new Paragraph("Dirección General del Registro Público de la Propiedad y el Comercio", times2));
            _cell.HorizontalAlignment = Element.ALIGN_CENTER;
            _cell.Border = 0;
            tbHeader3.AddCell(_cell);
            tbHeader3.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin) - 44, writer.DirectContent);
            //cuarto encabezado
            PdfPTable tbHeader4 = new PdfPTable(1);

            tbHeader4.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbHeader4.DefaultCell.Border = 0;
            tbHeader4.AddCell(new Paragraph());
            _cell = new PdfPCell(new Paragraph("CERTIFICADO DE EXISTENCIA O INEXISTENCIA DE GRAVAMENES \n ANTECEDENTES REGISTRALES", MyFontBold));
            _cell.HorizontalAlignment = Element.ALIGN_CENTER;
            _cell.Border = 0;
            tbHeader4.AddCell(_cell);
            tbHeader4.AddCell(new Paragraph());
            tbHeader4.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin) - 54, writer.DirectContent);
            //quinto encabezado
            PdfPTable tbHeader5 = new PdfPTable(1);

            tbHeader5.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbHeader5.DefaultCell.Border = 0;
            tbHeader5.AddCell(new Paragraph());
            Chunk  T1 = new Chunk("PRELACIÓN:", MyFontBold);
            Chunk  T2 = new Chunk("valor", MyArialFont);
            Chunk  T3 = new Chunk("           FOLIO DE VALIDACÓN:", MyFontBold);
            Chunk  T4 = new Chunk("valor", MyArialFont);
            Phrase p5 = new Phrase();

            p5.Add(T1);
            p5.Add(T2);
            p5.Add(T3);
            p5.Add(T4);
            Paragraph p = new Paragraph();

            p.Add(p5);
            tbHeader5.AddCell(p);
            tbHeader5.AddCell(new Paragraph());
            tbHeader5.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin) - 74, writer.DirectContent);
            // pie de pagina
            PdfPTable tbFooter = new PdfPTable(3);

            tbFooter.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbFooter.DefaultCell.Border = 0;
            tbFooter.AddCell(new Paragraph());
            _cell = new PdfPCell(new Paragraph("Página de Validación: http://www.colima-estado.gob.mx"));
            _cell.HorizontalAlignment = Element.ALIGN_CENTER;
            _cell.Border = 0;
            tbFooter.AddCell(_cell);

            _cell = new PdfPCell(new Paragraph("Pagina  " + writer.PageNumber));
            _cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell.Border = 0;
            tbFooter.AddCell(_cell);

            tbFooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin) - 5, writer.DirectContent);
        }
 public pdfPage(string _SelectedFont, iTextSharp.text.BaseColor _FontColor)
 {
     SelectedFont = _SelectedFont;
     FontColor    = _FontColor;
 }
    /// <summary>
    ///
    /// </summary>
    /// <param name="dt">Input Datatable to Export to PDF</param>
    /// <param name="strFilter">Filter conditions or remarks to display on report header</param>
    /// <param name="dicDataType">(ColumnIndex, XLDatattype)</param>
    /// <param name="lstRepeatColumn">Left most ColumnIndex to repeat on all pages</param>
    /// <param name="lstColumnsDisplay">ColumnIndex to display. Count = 0  or Nothing will Display All columns</param>
    /// <returns></returns>
    /// <remarks></remarks>
    public bool ExportToPDF(DataTable dt, string strFilter, Dictionary <int, Helper.Alignment> dicDataType, List <int> lstRepeatColumn = null, List <int> lstColumnsDisplay = null)
    {
        try {
            ICollection <string> myCol;           // = ICollection<string>;
            //'/Returns the list of all font families included in iTextSharp.
            myCol = iTextSharp.text.FontFactory.RegisteredFamilies;
            //'Returns the list of all fonts included in iTextSharp.
            myCol = iTextSharp.text.FontFactory.RegisteredFonts;

            //FontFactory.Register("F:\Transfer\SEGOEUI.TTF")
            //SelectedFont = FontFactory.GetFont("SEGOEUI")

            // Dim Segoe As Font = FontFactory.GetFont("SegoeUI") ' , BaseFont.IDENTITY_H, 8)
            //Dim bfTimes As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
            //Dim customfont As BaseFont
            //Try
            //    'customfont = BaseFont.CreateFont("F:\Transfer\SEGOEUI.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
            //    ' customfont = BaseFont.CreateFont(Segoe) '"F:\Transfer\SEGOEUI.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
            //    FontFactory.Register("F:\Transfer\SEGOEUI.TTF")
            //Catch ex As Exception
            //    Dim s = ex.Message
            //End Try


            int noOfColumns = dt.Columns.Count;
            int noOfRows    = dt.Rows.Count;
            Dictionary <int, float> dicWidth = new Dictionary <int, float>();

            if ((lstRepeatColumn == null))
            {
                lstRepeatColumn = new List <int>();
            }
            if ((lstColumnsDisplay == null))
            {
                lstColumnsDisplay = new List <int>();
            }
            if ((dicDataType == null))
            {
                dicDataType = new Dictionary <int, Helper.Alignment>();
                for (int icol = 0; icol <= noOfColumns - 1; icol++)
                {
                    dicDataType.Add(icol, Helper.Alignment.Left);
                }
            }

            SelectedFont = "Arial";
            // "Arial"  SEGOEUI COURIER HELVETICA
            HeaderFontColor = iTextSharp.text.BaseColor.BLUE;

            List <iTextSharp.text.pdf.PdfPTable> lstTables = new List <iTextSharp.text.pdf.PdfPTable>();
            // Creates a PDF document
            Document document = null;
            //If LandScape = True Then
            //document = new Document( PageSize.A4.Rotate   , 0.0f, 0.0f, 40.0f, 15.0f);
            document = new Document(new RectangleReadOnly(595, 842, 90), 0.0f, 0.0f, 40.0f, 15.0f);
            //LandScape  (W x H, 842 x 595) points
            //Else
            //'document = New Document(PageSize.A4, 0, 0, 15, 5) 'Portrait (W x H, 595 × 842) points
            //End If

            //dicWidth = GetColumnWidth(dt)
            dicWidth = GetColumnWidth(dt, SelectedFont, ColumnHeaderTextSize);

            Dictionary <int, List <int> > dicColsPerPage = new Dictionary <int, List <int> >();

            dicColsPerPage = GetColumnsPerPageByWidth(dt, dicWidth, lstRepeatColumn, lstColumnsDisplay);

            foreach (int intDt in dicColsPerPage.Keys)
            {
                List <int> lstColumnNums = dicColsPerPage[intDt];

                float[] arrColsrelativeWidths = new float[lstColumnNums.Count];
                dynamic dblTotalWidth         = dicWidth.Sum(t => t.Value);

                int iArrIndex = 0;

                foreach (int iCol in lstColumnNums)
                {
                    arrColsrelativeWidths[iArrIndex] = dicWidth[iCol];
                    //dblTotalWidth = dblTotalWidth + dicWidth(iCol)
                    iArrIndex = iArrIndex + 1;
                }

                iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(arrColsrelativeWidths);

                mainTable.TotalWidth = document.PageSize.Width * 0.9f;

                AddPageHeaderToPDFDataTable(ref mainTable, dt.TableName, strFilter, lstColumnNums.Count - 1);
                AddColumnHeader(dt, ref mainTable, lstColumnNums, dicDataType, lstColumnsDisplay);

                //'  If dblTotalWidth <= A4Dimension.Width * 0.9 - 30 Then mainTable.LockedWidth = True
                Phrase ph = default(Phrase);

                //' Date - centre, Double Right, String Left, INteger centre
                // Reads the gridview rows and adds them to the mainTable


                for (int rowNo = 0; rowNo <= noOfRows - 1; rowNo++)
                {
                    foreach (int iCol in lstColumnNums)
                    {
                        if (lstColumnsDisplay.Count > 0 && lstColumnsDisplay.Contains(iCol) == false)
                        {
                            continue;
                        }
                        if (iCol == 999)
                        {
                            mainTable.AddCell(EmptyCell());
                        }
                        else
                        {
                            string sData = (dt.Rows[rowNo][iCol] == null) ? string.Empty : dt.Rows[rowNo][iCol].ToString().Trim();
                            ph = new Phrase(sData, FontFactory.GetFont(SelectedFont, ReportTextSize, iTextSharp.text.Font.NORMAL));

                            PdfPCell cell = new PdfPCell(ph);
                            //cell.HorizontalAlignment =  GetAlignMent(dicDataType[iCol]);
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Center)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            }
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Right)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            }
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Left)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            }

                            if (lstRepeatColumn.Contains(iCol))
                            {
                                cell.BackgroundColor = iTextSharp.text.BaseColor.YELLOW;
                            }

                            cell.NoWrap            = true;
                            cell.VerticalAlignment = Element.ALIGN_TOP;
                            //Element.ALIGN_TOP
                            mainTable.AddCell(cell);
                        }
                    }

                    mainTable.CompleteRow();
                    // Tells the mainTable to complete the row even if any cell is left incomplete.

                    if (mainTable.TotalHeight >= 595 - 65)                     // A4Dimension.Height - 65) {
                    {
                        lstTables.Add(mainTable);

                        mainTable            = new iTextSharp.text.pdf.PdfPTable(arrColsrelativeWidths);
                        mainTable.TotalWidth = document.PageSize.Width * 0.9f;

                        AddPageHeaderToPDFDataTable(ref mainTable, dt.TableName, strFilter, lstColumnNums.Count - 1);
                        AddColumnHeader(dt, ref mainTable, lstColumnNums, dicDataType, lstColumnsDisplay);
                    }
                }

                mainTable.CompleteRow();
                lstTables.Add(mainTable);
            }
            //Dict

            string strFileName = @"C:\Code\Project\TrailCode\eCatenate" + "\\" + dt.TableName + "_" + DateTime.Now.ToString("yyyyMMdd HHmmss") + ".pdf";

            // Gets the instance of the document created and writes it to the output stream of the Response object.
            PdfWriter pdfWrite = PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
            // Response.OutputStream)
            pdfPage _pdfpage = new pdfPage(SelectedFont, HeaderFontColor);

            pdfWrite.PageEvent = _pdfpage;
            // Creates a footer for the PDF document.
            //Dim pdfFooter As New HeaderFooter(New Phrase("Page : ", FontFactory.GetFont(FontFactory.COURIER, FooterTextSize, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.DARK_GRAY)), True)

            //pdfFooter.Alignment = Element.ALIGN_CENTER
            //pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER

            var _with1 = document;
            //.Footer = pdfFooter
            _with1.Open();

            //document.Add(New Paragraph(strFont, times))

            _with1.AddCreator("ElaiyaKumar");
            _with1.AddAuthor("By ElaiyaKumar");
            foreach (iTextSharp.text.pdf.PdfPTable oMainTable in lstTables)
            {
                _with1.Add(oMainTable);
                _with1.NewPage();
            }
            _with1.Close();

            document = null;
            Console.WriteLine("Any key to save ....");
            Console.ReadKey();
            //Interaction.MsgBox("Report Saved as " + strFileName, MsgBoxStyle.Information, "Export PDF");
            Console.WriteLine(strFileName);
            Console.WriteLine();

            Process.Start(strFileName);
            return(true);
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(false);
    }
示例#30
0
        private static void DrawLine(PdfWriter writer, float x1, float y1, float x2, float y2, iTextSharp.text.BaseColor color)
        {
            PdfContentByte contentByte = writer.DirectContent;

            contentByte.SetColorStroke(color);
            contentByte.MoveTo(x1, y1);
            contentByte.LineTo(x2, y2);
            contentByte.Stroke();
        }
示例#31
0
 /// <summary>
 /// Constructs a Font-object.
 /// </summary>
 /// <param name="fontname">the name of the font</param>
 /// <param name="encoding">the encoding of the font</param>
 /// <param name="embedded">true if the font is to be embedded in the PDF</param>
 /// <param name="size">the size of this font</param>
 /// <param name="style">the style of this font</param>
 /// <param name="color">the BaseColor of this font</param>
 /// <param name="cached">true if the font comes from the cache or is added to the cache if new, false if the font is always created new</param>
 /// <returns>a Font object</returns>
 public static Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
 {
     return(fontImp.GetFont(fontname, encoding, embedded, size, style, color, cached));
 }
示例#32
0
    public static ActionResult PDF(
        long equipmentId,
        int companyId,
        bool calibrationInternal,
        bool calibrationExternal,
        bool verificationInternal,
        bool verificationExternal,
        bool maintenanceInternal,
        bool maintenanceExternal,
        bool repairInternal,
        bool repairExternal,
        DateTime?dateFrom,
        DateTime?dateTo,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

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

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

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

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

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

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

        pdfDoc.Open();

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

        string periode = string.Empty;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            typeText += dictionary["Item_EquipmentRecord_Filter_RepairExternal"];
        }

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

        pdfDoc.Add(criteriatable);

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

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

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

        decimal totalCost = 0;
        int     cont      = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

            cont++;
        }


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

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

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

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

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
示例#33
0
 /** Sets the color and the size of the background <CODE>Chunk</CODE>.
  * @param color the color of the background
  * @param extraLeft increase the size of the rectangle in the left
  * @param extraBottom increase the size of the rectangle in the bottom
  * @param extraRight increase the size of the rectangle in the right
  * @param extraTop increase the size of the rectangle in the top
  * @return this <CODE>Chunk</CODE>
  */
 public Chunk SetBackground(BaseColor color, float extraLeft, float extraBottom, float extraRight, float extraTop)
 {
     return(SetAttribute(BACKGROUND, new Object[] { color, new float[] { extraLeft, extraBottom, extraRight, extraTop } }));
 }
示例#34
0
 /// <summary>
 /// Constructs a Font-object.
 /// </summary>
 /// <param name="fontname">the name of the font</param>
 /// <param name="encoding">the encoding of the font</param>
 /// <param name="embedded">true if the font is to be embedded in the PDF</param>
 /// <param name="size">the size of this font</param>
 /// <param name="style">the style of this font</param>
 /// <param name="color">the BaseColor of this font</param>
 /// <returns>a Font object</returns>
 public virtual Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color)
 {
     return(GetFont(fontname, encoding, embedded, size, style, color, true));
 }
        private void myWriteButton_Click(object sender, RoutedEventArgs e)
        {
            String fileName = SaveFileDialog();

            if (String.IsNullOrWhiteSpace(fileName))
            {
                return;
            }


            System.Drawing.KnownColor backColorToUse = System.Drawing.KnownColor.White;

            int iCardNum = StartNumberingAt;

            foreach (var item in mySelectedVcards.Items)
            {
                (item as Card).CardNumber = iCardNum;

                if (BackgroundMatchesFirstCard)
                {
                    backColorToUse = (item as Card).BorderColor;
                }

                iCardNum++;
            }

            iTextSharp.text.BaseColor backColorToDraw = new iTextSharp.text.BaseColor(WhiteBorderConverter.GetCompatibleColor(backColorToUse)); //new iTextSharp.text.BaseColor(System.Drawing.Color.FromKnownColor(backColorToUse));
            PageEventHandler.PrintingBlackBorder = (backColorToUse == KnownColor.Black);
            PageEventHandler.BackColor           = backColorToDraw;
            PageEventHandler.UsingCubeFeatures   = (myCubeFeaturesCheckbox.IsChecked == true);

            using (WaitDlg dlg = new WaitDlg())
            {
                Document sizeDoc = new Document(PageSize.LETTER);
                iTextSharp.text.Rectangle backgroundRect = new iTextSharp.text.Rectangle(sizeDoc.PageSize);

                Document document;

                if (BackgroundMatchesFirstCard)
                {
                    backgroundRect.BackgroundColor = backColorToDraw;
                    document = new Document(backgroundRect);
                }
                else
                {
                    document = new Document(PageSize.LETTER);
                }


                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
                myEvents         = new PageEventHandler();
                writer.PageEvent = myEvents;



                //document.SetMargins(0, 0, 10, 0);
                // WORKING! document.SetMargins(document.LeftMargin, document.RightMargin, 25, 25);

                //document.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);
                document.SetMargins(document.LeftMargin, document.RightMargin, 15, 10);

                // step 3: we open the document
                document.Open();

                //iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph();
                PdfPTable table = new pdf.PdfPTable(3);
                table.SpacingBefore = 0;
                table.SpacingAfter  = 10;
                //table.TotalWidth = 175.5f * 3.0f + 30f;
                table.TotalWidth        = 179.0f * 3.0f + 20f;
                table.LockedWidth       = true;
                table.AbsoluteWidths[0] = 179.0f + (float)HorizontalSpacing;
                table.AbsoluteWidths[1] = 179.0f + (float)HorizontalSpacing;
                table.AbsoluteWidths[2] = 179.0f + (float)HorizontalSpacing;


                List <Card> smallCards = GetSelectedCards(true, false);
                List <Card> bigCards   = GetSelectedCards(false, true);


                WriteCards(bigCards, table, document, backColorToUse);
                WriteCards(smallCards, table, document, backColorToUse);

                PdfPCell emptyCell = new PdfPCell();
                emptyCell.BackgroundColor = backColorToDraw;
                emptyCell.BorderColor     = backColorToDraw;

                table.AddCell(emptyCell);
                table.AddCell(emptyCell);
                table.AddCell(emptyCell);


                foreach (var row in table.Rows)
                {
                    //pdf.PdfPCell cell = row.GetCells()[0];
                    //float top = row.GetCells()[0].Bottom;

                    //iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(-30,top, 50, top+3);
                    //document.Add(rect);
                }

                document.Add(table);
                document.Close();
            }

            MessageBox.Show("PDF Generation Complete!");
        }
示例#36
0
        /// <summary>
        /// Constructs a Font-object.
        /// </summary>
        /// <param name="fontname">the name of the font</param>
        /// <param name="encoding">the encoding of the font</param>
        /// <param name="embedded">true if the font is to be embedded in the PDF</param>
        /// <param name="size">the size of this font</param>
        /// <param name="style">the style of this font</param>
        /// <param name="color">the BaseColor of this font</param>
        /// <param name="cached">true if the font comes from the cache or is added to the cache if new, false if the font is always created new</param>
        /// <returns>a Font object</returns>
        public virtual Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
        {
            if (fontname == null)
            {
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            string        lowercasefontname = fontname.ToLower(CultureInfo.InvariantCulture);
            List <string> tmp;

            fontFamilies.TryGetValue(lowercasefontname, out tmp);
            if (tmp != null)
            {
                // some bugs were fixed here by Daniel Marczisovszky
                int  fs    = Font.NORMAL;
                bool found = false;
                int  s     = style == Font.UNDEFINED ? Font.NORMAL : style;
                foreach (string f in tmp)
                {
                    string lcf = f.ToLower(CultureInfo.InvariantCulture);
                    fs = Font.NORMAL;
                    if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("bold") != -1)
                    {
                        fs |= Font.BOLD;
                    }
                    if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("italic") != -1 || lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("oblique") != -1)
                    {
                        fs |= Font.ITALIC;
                    }
                    if ((s & Font.BOLDITALIC) == fs)
                    {
                        fontname = f;
                        found    = true;
                        break;
                    }
                }
                if (style != Font.UNDEFINED && found)
                {
                    style &= ~fs;
                }
            }
            BaseFont basefont = null;

            try {
                try {
                    // the font is a type 1 font or CJK font
                    basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null, true);
                }
                catch (DocumentException) {
                }
                if (basefont == null)
                {
                    // the font is a true type font or an unknown font
                    trueTypeFonts.TryGetValue(fontname.ToLower(CultureInfo.InvariantCulture), out fontname);
                    // the font is not registered as truetype font
                    if (fontname == null)
                    {
                        return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
                    }
                    // the font is registered as truetype font
                    basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null);
                }
            }
            catch (DocumentException de) {
                // this shouldn't happen
                throw de;
            }
            catch (System.IO.IOException) {
                // the font is registered as a true type font, but the path was wrong
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            catch {
                // null was entered as fontname and/or encoding
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            return(new Font(basefont, size, style, color));
        }
示例#37
0
 /// <summary>
 /// Constructs a Font-object.
 /// </summary>
 /// <param name="fontname">the name of the font</param>
 /// <param name="size">the size of this font</param>
 /// <param name="style">the style of this font</param>
 /// <param name="color">the BaseColor of this font</param>
 /// <returns>a Font object</returns>
 public virtual Font GetFont(string fontname, float size, int style, BaseColor color)
 {
     return(GetFont(fontname, defaultEncoding, defaultEmbedding, size, style, color));
 }
示例#38
0
 /// <summary>
 /// Constructs a Font-object.
 /// </summary>
 /// <param name="fontname">the name of the font</param>
 /// <param name="size">the size of this font</param>
 /// <param name="color">the BaseColor of this font</param>
 /// <returns>a Font object</returns>
 public virtual Font GetFont(string fontname, float size, BaseColor color)
 {
     return(GetFont(fontname, defaultEncoding, defaultEmbedding, size, Font.UNDEFINED, color));
 }
示例#39
0
 /// <summary>
 /// Sets the color of the background Chunk.
 /// </summary>
 /// <param name="color">the color of the background</param>
 /// <returns>this Chunk</returns>
 public Chunk SetBackground(BaseColor color)
 {
     return(SetBackground(color, 0, 0, 0, 0));
 }
示例#40
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);
            }
        }
示例#41
0
    public static ActionResult PDF(int companyId, string yearFrom, string yearTo, string mode, string listOrder, string textFilter)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

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

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

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

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

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

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

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

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

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

        pdfDoc.Open();

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

        var titleTable = new iTSpdf.PdfPTable(1);

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

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

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

        string periode = string.Empty;

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

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

        string modeText = dictionary["Common_All_Female_Plural"];

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

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

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

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

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

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

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

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

        pdfDoc.Add(criteriatable);

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

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

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

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

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

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

        decimal totalCost = 0;
        int     count     = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

                assist += alumno.Employee.FullName;
            }

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

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

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

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

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

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

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

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

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

            cont++;
        }

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

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

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

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

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

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
        private void genPDF()
        {
            System.Drawing.Font          font = new System.Drawing.Font("Microsoft Sans Serif", 12);
            iTextSharp.text.pdf.BaseFont bfR, bfR1, bfRB;
            iTextSharp.text.BaseColor    clrBlack = new iTextSharp.text.BaseColor(0, 0, 0);
            //MemoryStream ms = new MemoryStream();
            string myFont = Environment.CurrentDirectory + "\\THSarabun.ttf";
            string myFontB = Environment.CurrentDirectory + "\\THSarabun Bold.ttf";
            String hn = "", name = "", doctor = "", fncd = "", birthday = "", dsDate = "", dsTime = "", an = "";

            decimal total = 0;

            bfR  = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            bfR1 = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            bfRB = BaseFont.CreateFont(myFontB, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfR, 12, iTextSharp.text.Font.NORMAL, clrBlack);

            String[] aa = dsDate.Split(',');
            if (aa.Length > 1)
            {
                dsDate = aa[0];
                an     = aa[1];
            }
            String[] bb = dsDate.Split('*');
            if (bb.Length > 1)
            {
                dsDate = bb[0];
                dsTime = bb[1];
            }

            var logo = iTextSharp.text.Image.GetInstance(Environment.CurrentDirectory + "\\LOGO-BW-tran.jpg");

            logo.SetAbsolutePosition(10, PageSize.A4.Height - 90);
            logo.ScaleAbsoluteHeight(70);
            logo.ScaleAbsoluteWidth(70);

            FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");

            iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4, 36, 36, 36, 36);
            try
            {
                FileStream output = new FileStream(Environment.CurrentDirectory + "\\" + txtHn.Text.Trim() + ".pdf", FileMode.Create);
                PdfWriter  writer = PdfWriter.GetInstance(doc, output);
                doc.Open();
                //PdfContentByte cb = writer.DirectContent;
                //ColumnText ct = new ColumnText(cb);
                //ct.Alignment = Element.ALIGN_JUSTIFIED;

                //Paragraph heading = new Paragraph("Chapter 1", fntHead);
                //heading.Leading = 30f;
                //doc.Add(heading);
                //Image L = Image.GetInstance(imagepath + "/l.gif");
                //logo.SetAbsolutePosition(doc.Left, doc.Top - 180);
                doc.Add(logo);

                //doc.Add(new Paragraph("Hello World", fntHead));

                Chunk  c;
                String foobar = "Foobar Film Festival";
                //float width_helv = bfR.GetWidthPoint(foobar, 12);
                //c = new Chunk(foobar + ": " + width_helv, fntHead);
                //doc.Add(new Paragraph(c));

                //if (dt.Rows.Count > 24)
                //{
                //    doc.NewPage();
                //    doc.Add(new Paragraph(string.Format("This is a page {0}", 2)));
                //}
                int i = 0, r = 0, row2 = 0, rowEnd = 24;
                //r = dt.Rows.Count;
                int            next = r / 24;
                int            linenumber = 820, colCenter = 200, fontSize0 = 8, fontSize1 = 14, fontSize2 = 16, fontSize3 = 18;
                PdfContentByte canvas = writer.DirectContent;

                canvas.BeginText();
                canvas.SetFontAndSize(bfR, 12);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "โรงพยาบาล บางนา5  55 หมู่4 ถนนเทพารักษ์ ตำบลบางพลีใหญ่ อำเภอบางพลี จังหวัด สมุทรปราการ 10540", 100, linenumber, 0);
                //canvas.ShowTextAligned(Element.ALIGN_LEFT, "55 หมู่4 ถนนเทพารักษ์ ตำบลบางพลีใหญ่ อำเภอบางพลี จังหวัด สมุทรปราการ 10540", 100, 780, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "BANGNA 5 GENERAL HOSPITAL  55 M.4 Theparuk Road, Bangplee, Samutprakan Thailand0", 100, linenumber - 15, 0);
                canvas.EndText();
                linenumber = 720;
                canvas.BeginText();
                canvas.SetFontAndSize(bfR, fontSize3);
                canvas.ShowTextAligned(Element.ALIGN_CENTER, "ใบรับรองแพทย์", PageSize.A4.Width / 2, linenumber + 40, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ส่วนที่ 1", 50, linenumber += 10, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ของผู้ขอรับใบรับรองสุขภาพ", 100, linenumber, 0);

                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ข้าพเจ้า นาย/นาง/นางสาว ", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "................................................................................................................................................................  ", 170, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtPatientName.Text.Trim(), 173, linenumber, 0);

                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "สถานที่อยู่ (ที่สามารถติดต่อได้)", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtAddr1.Text, 172, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "................................................................................................................................................................  ", 170, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "...................................................................................................................................................................................................................  ", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtAddr2.Text, 55, linenumber + 5, 0);
                canvas.SetFontAndSize(bfR, fontSize1);

                canvas.ShowTextAligned(Element.ALIGN_LEFT, "หมายเลขบัตรประจำตัวประชาชน", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtId.Text, 172, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "................................................................... ", 170, linenumber - 5, 0);

                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ข้าพเจ้าขอใบรับรองสุขภาพ โดยมีประวัติสุขภาพดังนี้", 330, linenumber, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "1. โรคประจำตัว", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "[  ] ไม่มี     [  ] มี  ระบุ ........................................................................................................................", 200, linenumber, 0);

                if (chk1Normal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 205, linenumber, 0);
                }
                else if (chk1AbNormal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 248, linenumber, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, txt1AbNormal.Text, 290, linenumber + 5, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "2. อุบัติเหตุ และ ผ่าตัด", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "[  ] ไม่มี     [  ] มี  ระบุ ........................................................................................................................", 200, linenumber, 0);
                if (chk2Normal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 205, linenumber, 0);
                }
                else if (chk2AbNormal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 248, linenumber, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, txt2AbNormal.Text, 290, linenumber + 5, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "3. เคยเข้ารับการรักษาในโรงพยาบาล", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "[  ] ไม่มี     [  ] มี  ระบุ ........................................................................................................................", 200, linenumber, 0);
                if (chk3Normal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 205, linenumber, 0);
                }
                else if (chk3AbNormal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 248, linenumber, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, txt3AbNormal.Text, 290, linenumber + 5, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "4. ประวัติอื่นที่สำคัญ", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "..................................................................................................................................................................................  ", 130, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtOther.Text, 133, linenumber, 0);

                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ลงชื่อ .............................................................. วันที่ .............. เดือน .............................. พ.ศ. ...............", 150, linenumber -= 40, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, DateTime.Now.ToString("dd"), 340, linenumber + 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, bc.getMonth(DateTime.Now.ToString("MM")), 400, linenumber + 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, DateTime.Now.ToString("yyyy"), 490, linenumber + 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_CENTER, "ในกรณีเด็กทีไม่สามารถรับรองตนเองได้ ให้ผู้ปกครองลงนามรับรองแทนได้", PageSize.A4.Width / 2, linenumber -= 20, 0);

                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ส่วนที่ 2   ของแพทย์", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "สถานที่ตรวจ", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "................................................................................................................  ", 100, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, TxtHospitalName.Text, 110, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "วันที่ ", 380, linenumber, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "..........", 398, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, DateTime.Now.ToString("dd"), 401, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, " เดือน", 420, linenumber, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, ".........................", 445, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, bc.getMonth(DateTime.Now.ToString("MM")), 448, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, " พ.ศ. ", 500, linenumber, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "............", 520, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, DateTime.Now.ToString("yyyy"), 523, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);

                canvas.ShowTextAligned(Element.ALIGN_LEFT, "(1) ข้าพเจ้า นายแพทย์/แพทย์หญิง", 40, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, ".....................................................................................................................  ", 175, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtDoctorName.Text, 178, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ใบอนุญาตประกอบวิชาชีพเวชกรรมเลขที่", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, ".....................................  ", 205, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtDoctorId.Text, 208, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "สถานพยาบาลชื่อ", 292, linenumber, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, ".........................................................................................  ", 355, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, TxtHospitalName.Text, 358, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ที่อยู่", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "55 หมู่4 ถนนเทพารักษ์ ตำบลบางพลีใหญ่ อำเภอบางพลี จังหวัดสมุทรปราการ 10540", 77, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "....................................................................................................................................................................................................................  ", 72, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ได้ตรวจร่างกาย นาย/นาง/นางสาว", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtPatientName.Text, 187, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "..................................................................................................................  ", 182, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "แล้วเมื่อ     วันที่", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "..........", 120, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, DateTime.Now.ToString("dd"), 123, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, " เดือน", 142, linenumber, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, ".........................", 167, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, bc.getMonth(DateTime.Now.ToString("MM")), 170, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, " พ.ศ. ", 230, linenumber, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "............", 250, linenumber - 5, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, DateTime.Now.ToString("yyyy"), 253, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, " มีรายละเอียดดังนี้ ", 290, linenumber, 0);

                canvas.ShowTextAligned(Element.ALIGN_LEFT, "น้ำหนักตัว", 50, linenumber -= 20, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtWeight.Text, 105, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "......................", 88, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "กก. ความสูง", 140, linenumber, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtHeight.Text, 205, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "......................", 190, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "เซนติเมตร ความดันโลหิต", 240, linenumber, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtBloodPressure.Text, 345, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "......................", 340, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "มม.ปรอท ชีพจร ", 400, linenumber, 0);
                canvas.SetFontAndSize(bfRB, fontSize2);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, txtPulse.Text, 480, linenumber, 0);
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, ".................", 468, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ครั้ง/นาที ", 520, linenumber, 0);

                canvas.ShowTextAligned(Element.ALIGN_LEFT, "สภาพร่างกายทั่วไปอยู่ในเกณฑ์  [  ] ปกติ   [  ] ผิดปกติ  ระบุ", 50, linenumber -= 20, 0);
                if (chkNormal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 173, linenumber, 0);
                }
                else if (chkAbNormal.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 214, linenumber, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, txtAbnormal.Text, 287, linenumber, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "....................................................................................................................", 280, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ขอรับรองว่า บุคคลดังกล่าว ไม่เป็นผู้มีร่างกายทุพพลภาพจนไม่สามารถปฏิบัติหน้าที่ได้ ไม่ปรากฏอาการของโรคจิต ", 100, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "หรือจิตฟั่นเฟือน หรือปัญญาอ่อน ไม่ปรากฏอาการของการติดยาเสพติดให้โทษ และอาการของโรคพิษสุราเรื้อรัง และไม่", 50, linenumber   -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ปรากฏอาการและอาการแสดงของโรคต่อไปนี้", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "(1) โรคเรื้อนในระยะติดต่อ หรือในระยะที่ปรากฏอาการเป็นที่รังเกียจแก่สังคม", 80, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "(2) วัณโรคในระยะอันตราย", 80, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "(3) โรคเท้าช้างในระยะที่ปรากฏอาการเป็นที่รังเกียจแก่สังคม", 80, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "(4) ถ้าจำเป็นต้องตรวจหาโรคที่เกี่ยวข้องกับการปฏิบัติงานของผูัรับการตรวจให้ระบุข้อนี้ ", 80, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, ".......................................................................", 400, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "สรุปความเห็นและข้อแนะนำของแพทย์ ", 100, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "[  ]  " + chk1.Text, 120, linenumber -= 20, 0);
                if (chk1.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 124, linenumber, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "[  ]  " + chk2.Text, 120, linenumber -= 20, 0);
                if (chk2.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 124, linenumber, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "[  ]  " + chk3.Text, 120, linenumber -= 20, 0);
                if (chk3.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 124, linenumber, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "[  ]  " + chk4.Text, 120, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "...................................................................................", 178, linenumber - 5, 0);
                if (chk4.Checked)
                {
                    canvas.SetFontAndSize(bfRB, fontSize2);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "/ ", 124, linenumber, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, txt4Other.Text, 180, linenumber, 0);
                }
                canvas.SetFontAndSize(bfR, fontSize1);
                //canvas.ShowTextAligned(Element.ALIGN_LEFT, ".......................................................................................................................................", 50, linenumber -= 20, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "ลงชื่อ ", 270, linenumber -= 40, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "...................................................................................", 290, linenumber - 5, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "แพทย์ผู้ตรวจร่างกาย", 480, linenumber, 0);
                //canvas.SetFontAndSize(bfRB, fontSize2);
                //canvas.ShowTextAligned(Element.ALIGN_LEFT, txtDoctorName.Text, 213, linenumber, 0);

                canvas.SetFontAndSize(bfR, fontSize0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "หมายเหตุ (1) ต้องเป็นแพทย์ซึ่งได้ขึ้นทะเบียนรับใบอนุญาตประกอบวิชาชีพเวชกรรม ", 50, linenumber -= 10, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "(2) ให้แสดงว่าเป็นผู้มีร่างกายสมบูรณ์เพียงใด ใบรับรองแพทย์ฉบับนี้ให้ใช้ได้ 1 เดือน นับแต่วันที่ตรวจร่างกาย ", 72, linenumber -= 10, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "(3) คำรับรองนี้เป็นการตรวจวินิจฉัยเบื้องต้น ", 72, linenumber -= 10, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "แบบฟอร์มนี้ได้รับการรับรองจากมติคณะกรรมการแพทยสภาในการประชุมครั้งที่ ค/2561 วันที่ 14 สิงหาคม 2561 ", 50, linenumber -= 10, 0);

                canvas.EndText();

                canvas.Stroke();
                //canvas.RestoreState();
                //pB1.Maximum = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                doc.Close();
                Process          p = new Process();
                ProcessStartInfo s = new ProcessStartInfo(Environment.CurrentDirectory + "\\" + txtHn.Text.Trim() + ".pdf");
                //s.Arguments = "/c dir *.cs";
                p.StartInfo = s;
                //p.StartInfo.Arguments = "/c dir *.cs";
                //p.StartInfo.UseShellExecute = false;
                //p.StartInfo.RedirectStandardOutput = true;
                p.Start();

                //string output = p.StandardOutput.ReadToEnd();
                //p.WaitForExit();
                //Application.Exit();
            }
        }
示例#43
0
        /**
         * Sets the dingbat's color.
         *
         * @param zapfDingbatColor color for the ZapfDingbat
         */
        virtual public void setDingbatColor(BaseColor zapfDingbatColor)
        {
            float fontsize = symbol.Font.Size;

            symbol.Font = FontFactory.GetFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL, zapfDingbatColor);
        }
示例#44
0
    public static ActionResult PDF(int companyId, string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

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

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

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

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

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

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

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

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

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

        pdfDoc.Open();

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

        var titleTable = new iTSpdf.PdfPTable(1);

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

        titleTable.AddCell(titleCell);

        // @alex: hay que indicar que hay una columna menos por fila
        //// var table = new iTSpdf.PdfPTable(4)
        var table = new iTSpdf.PdfPTable(3)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

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

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Code"] + " - " + dictionary["Item_Equipment_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Location"]));

        // @alex: se omite la columna de la cabecera
        //// table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Cost"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Responsible"]));

        int cont = 0;
        var data = Equipment.ByCompany(companyId).ToList();

        string filter = GetFilter();

        if (filter.IndexOf("1", StringComparison.OrdinalIgnoreCase) != -1)
        {
            data = data.Where(d => !d.EndDate.HasValue).ToList();
        }

        if (filter.IndexOf("2", StringComparison.OrdinalIgnoreCase) != -1)
        {
            data = data.Where(d => d.EndDate.HasValue).ToList();
        }

        var dataC = new List <Equipment>();

        if (filter.IndexOf("C", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataC = data.Where(d => d.IsCalibration).ToList();
        }

        var dataV = new List <Equipment>();

        if (filter.IndexOf("V", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataV = data.Where(d => d.IsVerification).ToList();
        }

        var dataM = new List <Equipment>();

        if (filter.IndexOf("M", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataM = data.Where(d => d.IsMaintenance).ToList();
        }

        data = dataC;
        foreach (var equipmentV in dataV)
        {
            if (!data.Any(d => d.Id == equipmentV.Id))
            {
                data.Add(equipmentV);
            }
        }

        foreach (var equipmentM in dataM)
        {
            if (!data.Any(d => d.Id == equipmentM.Id))
            {
                data.Add(equipmentM);
            }
        }

        // aplicar filtros

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

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

        string statusText    = string.Empty;
        string operativaText = string.Empty;

        if (filter.IndexOf("0") != -1)
        {
            statusText = dictionary["Common_All"];
        }
        else if (filter.IndexOf("1") != -1)
        {
            statusText = dictionary["Item_Equipment_List_Filter_ShowActive"];
        }
        else if (filter.IndexOf("2") != -1)
        {
            statusText = dictionary["Item_Equipment_List_Filter_ShowClosed"];
        }

        bool first = true;

        if (filter.IndexOf("C") != -1)
        {
            first         = false;
            operativaText = dictionary["Item_Equipment_List_Filter_ShowCalibration"];
        }
        if (filter.IndexOf("V") != -1)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_List_Filter_ShowVerification"];
        }
        if (filter.IndexOf("M") != -1)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_List_Filter_ShowMaintenance"];
        }

        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByOperation"], operativaText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByStatus"], statusText);

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

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

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

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

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

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

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

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

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

        foreach (Equipment equipment in data)
        {
            total += equipment.TotalCost;

            var lineBackground = pair ? rowEven : rowPair;

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

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

            // @alex: se omite la celda de los datos del coste

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

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

            cont++;
        }

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

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

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

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

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

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

        pdfDoc.Add(criteriatable);
        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
示例#45
0
 /// <summary>
 /// Constructs a Font-object.
 /// </summary>
 /// <param name="fontname">the name of the font</param>
 /// <param name="encoding">the encoding of the font</param>
 /// <param name="size">the size of this font</param>
 /// <param name="style">the style of this font</param>
 /// <param name="color">the BaseColor of this font</param>
 /// <returns>a Font object</returns>
 public static Font GetFont(string fontname, string encoding, float size, int style, BaseColor color)
 {
     return(GetFont(fontname, encoding, defaultEmbedding, size, style, color));
 }
示例#46
0
    public static ActionResult PDF(
        int companyId,
        DateTime?from,
        DateTime?to,
        int status,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

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

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

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

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

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

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

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

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

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

        pdfDoc.Open();

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

        var titleTable = new iTSpdf.PdfPTable(1);

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


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

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

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

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

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

        ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText);

        if (!string.IsNullOrEmpty(filterText))
        {
            ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText);
        }
        pdfDoc.Add(criteriatable);
        #endregion

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

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

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Name"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Responsible"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_StartDate"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_PreviewEndDate"]));

        int cont = 0;
        var data = Objetivo.Filter(companyId, from, to, status).ToList();
        foreach (var item in data)
        {
            if (!item.Objetivo.EndDate.HasValue)
            {
                item.Objetivo.EndDate = item.Objetivo.PreviewEndDate;
            }
        }

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

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

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

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

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

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

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

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

        cont = 0;
        foreach (var item in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                var show = false;
                if (item.Objetivo.Name.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    show = true;
                }

                if (item.Objetivo.Responsible.FullName.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    show = true;
                }

                if (!show)
                {
                    continue;
                }
            }

            string endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.PreviewEndDate);
            if (item.Objetivo.EndDate.HasValue)
            {
                endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.EndDate);
            }

            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Active ? dictionary["Common_Active"] : dictionary["Common_Inactve"], ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Name, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Responsible.FullName, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.StartDate), ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(endDateText, ToolsPdf.LayoutFonts.Times));
            cont++;
        }

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

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

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

        pdfDoc.Add(table);

        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
示例#47
0
        protected void CreatePdf(int id)
        {
            DataRow  dr       = GetData(39).Rows[0];
            Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);

            iTextSharp.text.Font NormalFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                Phrase    phrase = null;
                PdfPCell  cell   = null;
                PdfPTable table  = null;
                iTextSharp.text.BaseColor color = null;

                document.Open();

                //Header Table
                table             = new PdfPTable(2);
                table.TotalWidth  = 500f;
                table.LockedWidth = true;
                table.SetWidths(new float[] { 0.3f, 0.7f });

                //Company Logo
                cell = ImageCell("~/images/secure-test.png", 30f, PdfPCell.ALIGN_CENTER);
                table.AddCell(cell);

                //Company Name and Address
                phrase = new Phrase();
                phrase.Add(new Chunk("Online Examination System\n\n", FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK)));
                phrase.Add(new Chunk("107, Park site,\n", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)));
                phrase.Add(new Chunk("Salt Lake Road,\n", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)));
                phrase.Add(new Chunk("Seattle, USA", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)));
                cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
                cell.VerticalAlignment = PdfPCell.ALIGN_TOP;
                table.AddCell(cell);

                //Separater Line
                color = new iTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
                DrawLine(writer, 25f, document.Top - 79f, document.PageSize.Width - 25f, document.Top - 79f, color);
                DrawLine(writer, 25f, document.Top - 80f, document.PageSize.Width - 25f, document.Top - 80f, color);
                document.Add(table);

                table = new PdfPTable(2);
                table.HorizontalAlignment = Element.ALIGN_LEFT;
                table.SetWidths(new float[] { 0.3f, 1f });
                table.SpacingBefore = 20f;

                //Employee Details
                cell         = PhraseCell(new Phrase("Faculty Detail", FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.UNDERLINE, iTextSharp.text.BaseColor.BLACK)), PdfPCell.ALIGN_CENTER);
                cell.Colspan = 2;
                table.AddCell(cell);
                cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
                cell.Colspan       = 2;
                cell.PaddingBottom = 30f;
                table.AddCell(cell);

                //Photo
                cell = ImageCell(string.Format("{0}", dr["avatar"]), 25f, PdfPCell.ALIGN_CENTER);
                table.AddCell(cell);

                //Name
                phrase = new Phrase();
                phrase.Add(new Chunk(dr["first_name"] + " " + dr["last_name"] + "\n", FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK)));
                phrase.Add(new Chunk("Faculty at OES", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK)));
                cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
                cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                table.AddCell(cell);
                document.Add(table);

                DrawLine(writer, 160f, 80f, 160f, 690f, iTextSharp.text.BaseColor.BLACK);
                DrawLine(writer, 115f, document.Top - 200f, document.PageSize.Width - 100f, document.Top - 200f, iTextSharp.text.BaseColor.BLACK);

                table = new PdfPTable(2);
                table.SetWidths(new float[] { 0.5f, 2f });
                table.TotalWidth          = 340f;
                table.LockedWidth         = true;
                table.SpacingBefore       = 20f;
                table.HorizontalAlignment = Element.ALIGN_RIGHT;

                //Employee Id
                table.AddCell(PhraseCell(new Phrase("Faculty code:", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
                table.AddCell(PhraseCell(new Phrase("000" + dr["faculty_id"], FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
                cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
                cell.Colspan       = 2;
                cell.PaddingBottom = 10f;
                table.AddCell(cell);


                //email Address
                table.AddCell(PhraseCell(new Phrase("Email ID:", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
                phrase = new Phrase(new Chunk(dr["email"] + "\n", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)));
                //phrase.Add(new Chunk(dr["City"] + "\n", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)));
                //phrase.Add(new Chunk(dr["Region"] + " " + dr["Country"] + " " + dr["PostalCode"], FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)));
                table.AddCell(PhraseCell(phrase, PdfPCell.ALIGN_LEFT));
                cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
                cell.Colspan       = 2;
                cell.PaddingBottom = 10f;
                table.AddCell(cell);



                //Phone
                table.AddCell(PhraseCell(new Phrase("Phone Number:", FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
                table.AddCell(PhraseCell(new Phrase("+91 " + dr["contact_no"], FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
                cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
                cell.Colspan       = 2;
                cell.PaddingBottom = 10f;
                table.AddCell(cell);


                document.Add(table);
                document.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + dr["first_name"] + "_" + dr["last_name"] + ".pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        var learningId = Convert.ToInt32(Request.QueryString["id"]);
        var companyId = Convert.ToInt32(Request.QueryString["companyId"]);
        var company = new Company(companyId);
        var res = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary<string, string>;
        var learning = new Learning(learningId, companyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

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

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

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

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

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

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

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

        writer.PageEvent = pageEventHandler;

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

        document.Open();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        document.Add(table);
        #endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

        document.Add(tableAssistants);
        #endregion

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
示例#49
0
 public void Init(InputMeta meta) {
     style = meta.ReadWord();
     color = meta.ReadColor();
     hatch = meta.ReadWord();
 }
示例#50
0
        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();
                }
            }
        }
示例#51
0
 /** Sets the text rendering mode. It can outline text, simulate bold and make
  * text invisible.
  * @param mode the text rendering mode. It can be <CODE>PdfContentByte.TEXT_RENDER_MODE_FILL</CODE>,
  * <CODE>PdfContentByte.TEXT_RENDER_MODE_STROKE</CODE>, <CODE>PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE</CODE>
  * and <CODE>PdfContentByte.TEXT_RENDER_MODE_INVISIBLE</CODE>.
  * @param strokeWidth the stroke line width for the modes <CODE>PdfContentByte.TEXT_RENDER_MODE_STROKE</CODE> and
  * <CODE>PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE</CODE>.
  * @param strokeColor the stroke color or <CODE>null</CODE> to follow the text color
  * @return this <CODE>Chunk</CODE>
  */
 public Chunk SetTextRenderMode(int mode, float strokeWidth, BaseColor strokeColor)
 {
     return(SetAttribute(TEXTRENDERMODE, new Object[] { mode, strokeWidth, strokeColor }));
 }
示例#52
0
 /** Places the barcode in a <CODE>PdfContentByte</CODE>. The
 * barcode is always placed at coodinates (0, 0). Use the
 * translation matrix to move it elsewhere.<p>
 * The bars and text are written in the following colors:<p>
 * <P><TABLE BORDER=1>
 * <TR>
 *    <TH><P><CODE>barColor</CODE></TH>
 *    <TH><P><CODE>textColor</CODE></TH>
 *    <TH><P>Result</TH>
 *    </TR>
 * <TR>
 *    <TD><P><CODE>null</CODE></TD>
 *    <TD><P><CODE>null</CODE></TD>
 *    <TD><P>bars and text painted with current fill color</TD>
 *    </TR>
 * <TR>
 *    <TD><P><CODE>barColor</CODE></TD>
 *    <TD><P><CODE>null</CODE></TD>
 *    <TD><P>bars and text painted with <CODE>barColor</CODE></TD>
 *    </TR>
 * <TR>
 *    <TD><P><CODE>null</CODE></TD>
 *    <TD><P><CODE>textColor</CODE></TD>
 *    <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD>
 *    </TR>
 * <TR>
 *    <TD><P><CODE>barColor</CODE></TD>
 *    <TD><P><CODE>textColor</CODE></TD>
 *    <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD>
 *    </TR>
 * </TABLE>
 * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed
 * @param barColor the color of the bars. It can be <CODE>null</CODE>
 * @param textColor the color of the text. It can be <CODE>null</CODE>
 * @return the dimensions the barcode occupies
 */    
 public override Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) {
     Rectangle rect = this.BarcodeSize;
     float barStartX = 0;
     float barStartY = 0;
     float textStartY = 0;
     if (font != null) {
         if (baseline <= 0)
             textStartY = barHeight - baseline;
         else {
             textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size);
             barStartY = textStartY + baseline;
         }
     }
     switch (codeType) {
         case EAN13:
         case UPCA:
         case UPCE:
             if (font != null)
                 barStartX += font.GetWidthPoint(code[0], size);
             break;
     }
     byte[] bars = null;
     int[] guard = GUARD_EMPTY;
     switch (codeType) {
         case EAN13:
             bars = GetBarsEAN13(code);
             guard = GUARD_EAN13;
             break;
         case EAN8:
             bars = GetBarsEAN8(code);
             guard = GUARD_EAN8;
             break;
         case UPCA:
             bars = GetBarsEAN13("0" + code);
             guard = GUARD_UPCA;
             break;
         case UPCE:
             bars = GetBarsUPCE(code);
             guard = GUARD_UPCE;
             break;
         case SUPP2:
             bars = GetBarsSupplemental2(code);
             break;
         case SUPP5:
             bars = GetBarsSupplemental5(code);
             break;
     }
     float keepBarX = barStartX;
     bool print = true;
     float gd = 0;
     if (font != null && baseline > 0 && guardBars) {
         gd = baseline / 2;
     }
     if (barColor != null)
         cb.SetColorFill(barColor);
     for (int k = 0; k < bars.Length; ++k) {
         float w = bars[k] * x;
         if (print) {
             if (Array.BinarySearch(guard, k) >= 0)
                 cb.Rectangle(barStartX, barStartY - gd, w - inkSpreading, barHeight + gd);
             else
                 cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight);
         }
         print = !print;
         barStartX += w;
     }
     cb.Fill();
     if (font != null) {
         if (textColor != null)
             cb.SetColorFill(textColor);
         cb.BeginText();
         cb.SetFontAndSize(font, size);
         switch (codeType) {
             case EAN13:
                 cb.SetTextMatrix(0, textStartY);
                 cb.ShowText(code.Substring(0, 1));
                 for (int k = 1; k < 13; ++k) {
                     string c = code.Substring(k, 1);
                     float len = font.GetWidthPoint(c, size);
                     float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2;
                     cb.SetTextMatrix(pX, textStartY);
                     cb.ShowText(c);
                 }
                 break;
             case EAN8:
                 for (int k = 0; k < 8; ++k) {
                     string c = code.Substring(k, 1);
                     float len = font.GetWidthPoint(c, size);
                     float pX = TEXTPOS_EAN8[k] * x - len / 2;
                     cb.SetTextMatrix(pX, textStartY);
                     cb.ShowText(c);
                 }
                 break;
             case UPCA:
                 cb.SetTextMatrix(0, textStartY);
                 cb.ShowText(code.Substring(0, 1));
                 for (int k = 1; k < 11; ++k) {
                     string c = code.Substring(k, 1);
                     float len = font.GetWidthPoint(c, size);
                     float pX = keepBarX + TEXTPOS_EAN13[k] * x - len / 2;
                     cb.SetTextMatrix(pX, textStartY);
                     cb.ShowText(c);
                 }
                 cb.SetTextMatrix(keepBarX + x * (11 + 12 * 7), textStartY);
                 cb.ShowText(code.Substring(11, 1));
                 break;
             case UPCE:
                 cb.SetTextMatrix(0, textStartY);
                 cb.ShowText(code.Substring(0, 1));
                 for (int k = 1; k < 7; ++k) {
                     string c = code.Substring(k, 1);
                     float len = font.GetWidthPoint(c, size);
                     float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2;
                     cb.SetTextMatrix(pX, textStartY);
                     cb.ShowText(c);
                 }
                 cb.SetTextMatrix(keepBarX + x * (9 + 6 * 7), textStartY);
                 cb.ShowText(code.Substring(7, 1));
                 break;
             case SUPP2:
             case SUPP5:
                 for (int k = 0; k < code.Length; ++k) {
                     string c = code.Substring(k, 1);
                     float len = font.GetWidthPoint(c, size);
                     float pX = (7.5f + (9 * k)) * x - len / 2;
                     cb.SetTextMatrix(pX, textStartY);
                     cb.ShowText(c);
                 }
                 break;
         }
         cb.EndText();
     }
     return rect;
 }
示例#53
0
 /// <summary>
 /// Sets the color.
 /// </summary>
 /// <param name="red">the red-value of the new color</param>
 /// <param name="green">the green-value of the new color</param>
 /// <param name="blue">the blue-value of the new color</param>
 public virtual void SetColor(int red, int green, int blue)
 {
     this.color = new BaseColor(red, green, blue);
 }
 private void SynchronizeSymbol(float fontSize, List lst, BaseColor color) {
     Font font = lst.Symbol.Font;
     font.Size = fontSize;
     font.Color = color;
     lst.SymbolIndent = fontSize;
 }
 private void ShrinkSymbol(List lst, float fontSize, BaseColor color) {
     lst.SymbolIndent = 12;
     Chunk symbol = lst.Symbol;
     //symbol.SetTextRise(2);
     Font font = symbol.Font;
     font.Size = fontSize;
     font.Color = color;
 }
示例#56
0
        private void AddRow(PdfPTable t, RollsheetModel.PersonMemberInfo p, BaseColor color)
        {
            t.DefaultCell.BackgroundColor = color;

            var c = new Phrase();
            c.Add(new Chunk(p.Name, boldfont));
            c.Add(new Chunk($"  ({p.PeopleId})\n", smallfont));
            var sb = new StringBuilder();
            AddLine(sb, p.Address);
            AddLine(sb, p.Address2);
            AddLine(sb, p.CityStateZip);
            c.Add(new Chunk(sb.ToString(), font));
            t.AddCell(c);

            sb = new StringBuilder();
            AddPhone(sb, p.HomePhone, "h ");
            AddPhone(sb, p.CellPhone, "c ");
            AddPhone(sb, p.WorkPhone, "w ");
            AddLine(sb, p.Email);
            t.AddCell(new Phrase(sb.ToString(), font));

            t.AddCell(new Phrase(p.MemberType));
        }
示例#57
0
 /// <summary>
 /// Constructs a Font-object.
 /// </summary>
 /// <param name="fontname">the name of the font</param>
 /// <param name="size">the size of this font</param>
 /// <param name="color">the Color of this font</param>
 /// <returns>a Font object</returns>
 public static Font GetFont(string fontname, float size, BaseColor color)
 {
     return(GetFont(fontname, DefaultEncoding, DefaultEmbedding, size, Font.UNDEFINED, color));
 }
示例#58
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var alignRight  = Element.ALIGN_RIGHT;

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

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

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

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

        var alignLeft = Element.ALIGN_LEFT;

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

        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        table.AddCell(SeparationRow());

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

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

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

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

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

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

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

        document.Add(table);
        #endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    cont++;
                }

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

                document.Add(tableHistoric);
            }
            #endregion

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

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

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

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

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

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

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

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

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

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

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



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

                document.Add(tableCost);
            }

            #endregion
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
示例#59
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);
    }
示例#60
-3
 public virtual void GoodColorTests() {
     String[] colors = {
         "#00FF00", "00FF00", "#0F0", "0F0", "LIme",
         "rgb(0,255,0 )"
     };
     // TODO webColor creates colors with a zero alpha channel (save
     // "transparent"), BaseColor's 3-param constructor creates them with a
     // 0xFF alpha channel. Which is right?!
     BaseColor testCol = new BaseColor(0, 255, 0);
     foreach (String colStr in colors) {
         BaseColor curCol = WebColors.GetRGBColor(colStr);
         Assert.IsTrue(testCol.Equals(curCol), DumpColor(testCol) + "!=" + DumpColor(curCol));
     }
 }