Ejemplo n.º 1
0
        public static void Sort(ref string[] lines, LineOptions lineOptions)
        {
            IComparer <string> comparer = new LineComparer(lineOptions);

            Array.Sort(lines, comparer);

            if (lineOptions.HasFlag(LineOptions.EliminateDuplicates))
            {
                int           numLines     = lines.Length;
                List <string> newLines     = new(numLines);
                string        previousLine = null;
                for (int i = 0; i < numLines; i++)
                {
                    string line = lines[i];
                    if (previousLine == null || comparer.Compare(line, previousLine) != 0)
                    {
                        newLines.Add(line);
                    }

                    previousLine = line;
                }

                lines = newLines.ToArray();
            }
        }
Ejemplo n.º 2
0
        protected void InitComponent()
        {
            options = new LineOptions
            {
                Responsive = true,
                Title      = new OptionsTitle
                {
                    Display = false,
                    Text    = ""
                },
                Legend = new Legend
                {
                    Position = Position.Right,
                    Labels   = new LegendLabelConfiguration
                    {
                        UsePointStyle = true
                    }
                },
                Tooltips = new Tooltips
                {
                    Mode      = InteractionMode.Nearest,
                    Intersect = false
                },
                Scales = new Scales
                {
                    xAxes = new List <CartesianAxis>
                    {
                        new TimeAxis
                        {
                            Distribution = TimeDistribution.Linear,
                            Ticks        = new TimeTicks
                            {
                                Source = TickSource.Data
                            },
                            Time = new TimeOptions
                            {
                                Unit           = TimeMeasurement.Millisecond,
                                Round          = TimeMeasurement.Millisecond,
                                TooltipFormat  = "DD.MM.YYYY HH:mm:ss:SSS",
                                DisplayFormats = TimeDisplayFormats.DE_CH
                            },
                            ScaleLabel = new ScaleLabel
                            {
                                LabelString = "Time"
                            }
                        }
                    }
                },
                Hover = new LineOptionsHover
                {
                    Intersect = true,
                    Mode      = InteractionMode.Y
                }
            };



            config = new LineConfig();
        }
Ejemplo n.º 3
0
        public FlotChartOptions Bars(Action<LineOptions> barOptionsBuilder)
        {
            if (_barOptions == null)
                _barOptions = new LineOptions();

            barOptionsBuilder(_barOptions);

            return this;
        }
Ejemplo n.º 4
0
        public FlotChartOptions Points(Action<LineOptions> pointOptionsBuilder)
        {
            if (_pointOptions == null)
                _pointOptions = new LineOptions();

            pointOptionsBuilder(_pointOptions);

            return this;
        }
Ejemplo n.º 5
0
 public DialogueLine(string type, string contents, LineOptions opts)
 {
     LineType = type;
     Content = contents;
     QuotedContent = string.Format("\"{0}\"", contents);
     Options = opts ?? new LineOptions();
     LineNumber = 0;
     File = DialogueFile.NullFile;
 }
Ejemplo n.º 6
0
 public DialogueLine(string type, LineOptions opts)
 {
     LineType = type;
     Content = "";
     QuotedContent = "";
     Options = opts ?? new LineOptions();
     LineNumber = 0;
     File = DialogueFile.NullFile;
 }
Ejemplo n.º 7
0
 public void Test3()
 {
     var json = new LineOptions()
                .Show(true)
                .Fill(true)
                .FillColor("#222")
                .LineWidth(2)
                .ToJson();
 }
Ejemplo n.º 8
0
        public FlotChartOptions Lines(Action<LineOptions> lineOptionsBuilder)
        {
            if (_lineOptions == null)
                _lineOptions = new LineOptions();

            lineOptionsBuilder(_lineOptions);

            return this;
        }
Ejemplo n.º 9
0
 protected void SetShapeLine(Excel.Shape shape, LineOptions options)
 {
     shape.Line.Visible = GetState(false);
     if (options.Visible)
     {
         shape.Line.Visible       = GetState(options.Visible);
         shape.Line.Weight        = (float)options.Weight;
         shape.Line.ForeColor.RGB = options.Color.ToRgb();
     }
 }
Ejemplo n.º 10
0
        public FlotChartOptions Bars(Action <LineOptions> barOptionsBuilder)
        {
            if (_barOptions == null)
            {
                _barOptions = new LineOptions();
            }

            barOptionsBuilder(_barOptions);

            return(this);
        }
Ejemplo n.º 11
0
        public FlotChartOptions Points(Action <LineOptions> pointOptionsBuilder)
        {
            if (_pointOptions == null)
            {
                _pointOptions = new LineOptions();
            }

            pointOptionsBuilder(_pointOptions);

            return(this);
        }
Ejemplo n.º 12
0
        public FlotChartOptions Lines(Action <LineOptions> lineOptionsBuilder)
        {
            if (_lineOptions == null)
            {
                _lineOptions = new LineOptions();
            }

            lineOptionsBuilder(_lineOptions);

            return(this);
        }
Ejemplo n.º 13
0
        public bool Execute(Options options)
        {
            LineOptions lineOptions = options.LineOptions;

            this.caseSensitive.IsChecked              = lineOptions.HasFlag(LineOptions.CaseSensitive);
            this.compareByOrdinal.IsChecked           = lineOptions.HasFlag(LineOptions.ByOrdinal);
            this.descending.IsChecked                 = lineOptions.HasFlag(LineOptions.Descending);
            this.ignoreWhitespace.IsChecked           = lineOptions.HasFlag(LineOptions.IgnoreWhitespace);
            this.ignorePunctuation.IsChecked          = lineOptions.HasFlag(LineOptions.IgnorePunctuation);
            this.wholeLines.IsChecked                 = lineOptions.HasFlag(LineOptions.WholeLines);
            this.eliminateDuplicates.IsChecked        = lineOptions.HasFlag(LineOptions.EliminateDuplicates);
            this.compareByLength.IsChecked            = lineOptions.HasFlag(LineOptions.ByLength);
            this.onlyShowWhenShiftIsPressed.IsChecked = options.OnlyShowSortLinesDialogWhenShiftIsPressed;

            bool result = false;

            if (this.ShowModal().GetValueOrDefault())
            {
                lineOptions = LineOptions.None;
                void AddOption(CheckBox checkBox, LineOptions option)
                {
                    if (checkBox.IsChecked.GetValueOrDefault())
                    {
                        lineOptions |= option;
                    }
                }

                AddOption(this.caseSensitive, LineOptions.CaseSensitive);
                AddOption(this.compareByOrdinal, LineOptions.ByOrdinal);
                AddOption(this.descending, LineOptions.Descending);
                AddOption(this.ignoreWhitespace, LineOptions.IgnoreWhitespace);
                AddOption(this.ignorePunctuation, LineOptions.IgnorePunctuation);
                AddOption(this.wholeLines, LineOptions.WholeLines);
                AddOption(this.eliminateDuplicates, LineOptions.EliminateDuplicates);
                AddOption(this.compareByLength, LineOptions.ByLength);
                options.LineOptions = lineOptions;

                options.OnlyShowSortLinesDialogWhenShiftIsPressed = this.onlyShowWhenShiftIsPressed.IsChecked.GetValueOrDefault();

                options.SaveSettingsToStorage();
                result = true;
            }

            return(result);
        }
Ejemplo n.º 14
0
        private LineComparer(LineOptions options)
        {
            bool caseSensitive = options.HasFlag(LineOptions.CaseSensitive);

            if (options.HasFlag(LineOptions.ByOrdinal))
            {
                this.comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
            }
            else
            {
                this.comparison = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
            }

            this.descending        = options.HasFlag(LineOptions.Descending);
            this.ignoreWhitespace  = options.HasFlag(LineOptions.IgnoreWhitespace);
            this.ignorePunctuation = options.HasFlag(LineOptions.IgnorePunctuation);
            this.byLength          = options.HasFlag(LineOptions.ByLength);
        }
Ejemplo n.º 15
0
        /// <inheritdoc/>
        protected override void OnInitialized()
        {
            PageTitle   = NeonDashboardService.ClusterInfo.Name;
            clusterInfo = NeonDashboardService.ClusterInfo;

            AppState.OnDashboardChange += StateHasChanged;
            AppState.Kube.OnChange     += StateHasChanged;
            AppState.Metrics.OnChange  += StateHasChanged;

            clusterMetaData = new Dictionary <string, string>()
            {
                { "Version", clusterInfo.ClusterVersion },
                { "Datacenter", clusterInfo.Datacenter },
                { "Enviroment", clusterInfo.Environment.ToString() },
                { "Purpose", clusterInfo.Purpose.ToString() }
            };

            LineOptions options = new LineOptions()
            {
                Responsive          = true,
                MaintainAspectRatio = false,
                Scales = new Scales()
                {
                }
            };

            memoryChartConfig = new LineConfig()
            {
                Options = options
            };

            cpuChartConfig = new LineConfig()
            {
                Options = options
            };

            diskChartConfig = new LineConfig()
            {
                Options = options
            };
        }
Ejemplo n.º 16
0
        public SCMap AddLine(double[] point1, double[] point2, bool geodesic, LineOptions options = null)
        {
            options ??= new LineOptions();

            var mapItem = new MapLine();

            if (point1 == null || point1.Length != 2)
            {
                throw new Exception("Point1 must be double array with 2 elements.");
            }
            if (point2 == null || point2.Length != 2)
            {
                throw new Exception("Point2 must be double array with 2 elements.");
            }

            mapItem.Point1     = CreateCoordPoint(point1[0], point1[1]);
            mapItem.Point2     = CreateCoordPoint(point2[0], point2[1]);
            mapItem.IsGeodesic = geodesic;

            options.ConfigureMapItem(this, mapItem);

            return(this);
        }
Ejemplo n.º 17
0
 public void Sort(LineOptions lineOptions) => LineComparer.Sort(ref this.lines, lineOptions);
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            var curDir = Directory.GetCurrentDirectory();

            Console.WriteLine($"Current Directory: {curDir}");
            try
            {
                var months = 12;

                var FileName = "democharts.js";

                Random r = new Random();

                var Data1 = new Dataset()
                {
                    Name      = "Data 1",
                    ChartType = ChartTypes.line,
                    Values    = Enumerable.Range(0, months)
                                .Select(x => r.Next(1000))
                                .Select(y => (object)y)
                                .ToArray()
                };

                var Data2 = new Dataset()
                {
                    Name      = "Data 2",
                    ChartType = ChartTypes.line,
                    Values    = Enumerable.Range(0, months)
                                .Select(x => r.Next(1000))
                                .Select(y => (object)y)
                                .ToArray()
                };


                var labels = Enumerable.Range(0, months)
                             .Select(i => DateTime.Now.AddMonths(i - months))
                             .Select(date => date.ToString("MMM yyyy"))
                             .ToArray();


                var lineOptions = new LineOptions()
                {
                    Heatline   = true,
                    RegionFill = true,
                    DotSize    = 5
                };

                var axisOption = new AxisOptions()
                {
                    XAxisMode = AxisModes.tick
                };

                var FrappeChart = new FrappeChart("#FrappeChart", "FrappeChart")
                {
                    Options = new ChartOptions()
                    {
                        Title  = $"Chart Title",
                        Height = 350,
                        Data   = new ChartData()
                        {
                            Labels   = labels,
                            Datasets = new Dataset[] {
                                Data1,
                                Data2
                            }
                        },
                        Type             = ChartTypes.line,
                        ValuesOverPoints = false,
                        LineOptions      = lineOptions,
                        AxisOptions      = axisOption,
                        Colors           = new string[] { "#5bcaff", "#ff82d0" }
                    }
                };

                Console.WriteLine($"Saving Chart to file '{FileName}'");
                File.WriteAllText(FileName, FrappeChart.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine($"Starting default browser with 'index.html'");
            Process proc = new Process();

            proc.StartInfo.UseShellExecute = true;
            proc.StartInfo.FileName        = "index.html";
            proc.Start();
        }
Ejemplo n.º 19
0
 public void BasicJson()
 {
     var json = new LineOptions().ToJson();
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates a chart displaying a supported <see cref="ChartType"/> with the given data. Includes a chart and a table, and allows exporting the data to CSV.
        /// Assuming <paramref name="seriesCollection"/> has multiple elements, draws multiple sets of Y values on the same chart.
        /// </summary>
        /// <param name="setup">The setup object for the chart.</param>
        /// <param name="seriesCollection">The data series collection.</param>
        /// <param name="colors">The colors to use for the data series collection. Pass null for default colors. If you specify your own colors, the number of
        /// colors does not need to match the number of series. If you pass fewer colors than series, the chart will use random colors for the remaining series.
        /// </param>
        public Chart(ChartSetup setup, [NotNull] IEnumerable <DataSeries> seriesCollection, IEnumerable <Color> colors = null)
        {
            seriesCollection = seriesCollection.ToArray();

            var rand = new Random();

            colors = (colors ?? getDefaultColors()).Take(seriesCollection.Count())
                     .Pad(seriesCollection.Count(), () => Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256)));

            this.setup = setup;

            CssClass = CssClass.ConcatenateWithSpace(CssElementCreator.CssClass);

            Func <DataSeries, Color, BaseDataset> datasetSelector;
            OptionsBase options;

            switch (setup.ChartType)
            {
            case ChartType.Line:
                datasetSelector = (series, color) => new Dataset(color, series.Values.TakeLast(setup.MaxXValues));
                options         = new LineOptions {
                    bezierCurve = false
                };
                break;

            case ChartType.Bar:
                datasetSelector = (series, color) => new BaseDataset(color, series.Values.TakeLast(setup.MaxXValues));
                // ReSharper disable once RedundantEmptyObjectOrCollectionInitializer
                options = new BarOptions {
                };
                break;

            default:
                throw new UnexpectedValueException(setup.ChartType);
            }

            var chartData = new ChartData(
                setup.Labels.TakeLast(setup.MaxXValues),
                seriesCollection.Zip(colors, (series, color) => datasetSelector(series, color)).ToArray());

            var canvas = new HtmlGenericControl("canvas");

            switch (setup.ChartType)
            {
            case ChartType.Line:
            case ChartType.Bar:
                canvas.Attributes.Add("height", "400");
                break;

            default:
                throw new UnexpectedValueException(setup.ChartType);
            }
            Controls.Add(canvas);

            if (seriesCollection.Count() > 1)
            {
                this.AddControlsReturnThis(
                    new Section(
                        "Key",
                        new LineList(
                            chartData.datasets.Select(
                                (dataset, i) => (LineListItem) new TrustedHtmlString(
                                    "<div style='display: inline-block; vertical-align: middle; width: 20px; height: 20px; background-color: {0}; border: 1px solid {1};'>&nbsp;</div> {2}"
                                    .FormatWith(dataset.fillColor, dataset.strokeColor, seriesCollection.ElementAt(i).Name)).ToComponent()
                                .ToComponentListItem())).ToCollection(),
                        style: SectionStyle.Box).ToCollection()
                    .GetControls());
            }

            // Remove this when ColumnPrimaryTable supports Excel export.
            var headers   = setup.XAxisTitle.ToCollection().Concat(seriesCollection.Select(v => v.Name));
            var tableData = new List <IEnumerable <object> >(seriesCollection.First().Values.Count());

            for (var i = 0; i < tableData.Capacity; i++)
            {
                var i1 = i;
                tableData.Add(setup.Labels.ElementAt(i1).ToCollection().Concat(seriesCollection.Select(v => v.Values.ElementAt(i1).ToString())));
            }
            var exportAction = getExportAction(headers, tableData);

            var table = ColumnPrimaryTable.Create(tableActions: exportAction.ToCollection(), firstDataFieldIndex: 1)
                        .AddItems(
                EwfTableItem.Create(setup.XAxisTitle.ToCollection().Concat(setup.Labels).Select(i => i.ToCell()).Materialize())
                .ToCollection()
                .Concat(
                    from series in seriesCollection
                    select EwfTableItem.Create(series.Name.ToCell().Concat(from i in series.Values select i.ToString().ToCell()).Materialize()))
                .Materialize());

            this.AddControlsReturnThis(table.ToCollection().GetControls());

            jsInitStatementGetter = () => {
                using (var writer = new StringWriter()) {
                    writer.WriteLine("var canvas = document.getElementById( '{0}' );".FormatWith(canvas.ClientID));
                    writer.WriteLine("canvas.width = $( canvas ).parent().width();");
                    writer.WriteLine(
                        "new Chart( canvas.getContext( '2d' ) ).{0}( {1}, {2} );".FormatWith(
                            setup.ChartType,
                            JsonOps.SerializeObject(chartData),
                            JsonOps.SerializeObject(options)));
                    return(writer.ToString());
                }
            };
        }
Ejemplo n.º 21
0
        void ControlTreeDataLoader.LoadData()
        {
            CssClass = CssClass.ConcatenateWithSpace( CssElementCreator.CssClass );

            var rand = new Random();
            var actualColors = ( colors ?? getDefaultColors() ).Take( seriesCollection.Count() )
                .Pad( seriesCollection.Count(), () => Color.FromArgb( rand.Next( 256 ), rand.Next( 256 ), rand.Next( 256 ) ) );

            Func<DataSeries, Color, BaseDataset> datasetSelector;
            OptionsBase options;
            switch( setup.ChartType ) {
                case ChartType.Line:
                    datasetSelector = ( series, color ) => new Dataset( color, series.Values.TakeLast( setup.MaxXValues ) );
                    options = new LineOptions { bezierCurve = false };
                    break;
                case ChartType.Bar:
                    datasetSelector = ( series, color ) => new BaseDataset( color, series.Values.TakeLast( setup.MaxXValues ) );
                    // ReSharper disable once RedundantEmptyObjectOrCollectionInitializer
                    options = new BarOptions { };
                    break;
                default:
                    throw new UnexpectedValueException( setup.ChartType );
            }

            var chartData = new ChartData(
                setup.Labels.TakeLast( setup.MaxXValues ),
                seriesCollection.Zip( actualColors, ( series, color ) => datasetSelector( series, color ) ).ToArray() );

            var canvas = new HtmlGenericControl( "canvas" );
            switch( setup.ChartType ) {
                case ChartType.Line:
                case ChartType.Bar:
                    canvas.Attributes.Add( "height", "400" );
                    break;
                default:
                    throw new UnexpectedValueException( setup.ChartType );
            }
            Controls.Add( canvas );

            if( seriesCollection.Count() > 1 ) {
                Controls.Add(
                    new Box(
                        "Key",
                        new ControlLine(
                            chartData.datasets.Select(
                                ( dataset, i ) =>
                                new Literal
                                    {
                                        Text =
                                            @"<div style='display: inline-block; vertical-align: middle; width: 20px; height: 20px; background-color: {0}; border: 1px solid {1};'>&nbsp;</div> {2}"
                                    .FormatWith( dataset.fillColor, dataset.strokeColor, seriesCollection.ElementAt( i ).Name )
                                    } as Control ).ToArray() ).ToSingleElementArray() ) );
            }

            // Remove this when ColumnPrimaryTable supports Excel export.
            var headers = setup.XAxisTitle.ToSingleElementArray().Concat( seriesCollection.Select( v => v.Name ) );
            var tableData = new List<IEnumerable<object>>( seriesCollection.First().Values.Count() );
            for( var i = 0; i < tableData.Capacity; i++ ) {
                var i1 = i;
                tableData.Add( setup.Labels.ElementAt( i1 ).ToSingleElementArray().Concat( seriesCollection.Select( v => v.Values.ElementAt( i1 ).ToString() ) ) );
            }
            Controls.Add( getExportButton( headers, tableData ) );

            var table = new ColumnPrimaryTable(
                firstDataFieldIndex: 1,
                items:
                    new EwfTableItem( from i in setup.XAxisTitle.ToSingleElementArray().Concat( setup.Labels ) select i.ToCell() ).ToSingleElementArray()
                        .Concat(
                            from series in seriesCollection
                            select new EwfTableItem( series.Name.ToCell().ToSingleElementArray().Concat( from i in series.Values select i.ToString().ToCell() ) ) ) );
            Controls.Add( table );

            using( var writer = new StringWriter() ) {
                writer.WriteLine( "var canvas = document.getElementById( '{0}' );".FormatWith( canvas.ClientID ) );
                writer.WriteLine( "canvas.width = $( canvas ).parent().width();" );
                writer.WriteLine( "new Chart( canvas.getContext( '2d' ) ).{0}( {1}, {2} );".FormatWith( setup.ChartType, chartData.ToJson(), options.ToJson() ) );
                jsInitStatements = writer.ToString();
            }
        }
Ejemplo n.º 22
0
        public void TestAddTitle()
        {
            var documentOptions = new DocumentOptions()
            {
                PageSize          = PageSize.A4,
                PageOrientation   = PageOrientation.Portrait,
                DefaultFontFamily = TextFontFamily.TimesNewRoman,
            };
            var builder = new PdfBuilder(documentOptions);

            builder.PageHeader += new PageHeaderEventHandler(this.PageHeader);
            builder.PageFooter += new PageFooterEventHandler(this.PageFooter);

            builder.Open();

            //
            // Fonts
            //
            builder.NewPage();
            builder.NewLine();
            builder.AddTitle("Fonts");
            builder.NewLine();

            builder.AddHeading("Styles");
            builder.AddText("Times New Roman - Normal");
            builder.NewLine();

            builder.AddText("Times New Roman - Bold", TextOptions.Set(FontWeight: TextFontWeight.Bold));

            builder.NewLine();

            builder.AddText("Times New Roman - Italic", TextOptions.Set(FontStyle: TextFontStyle.Italic));
            builder.NewLine();

            builder.AddText("Times New Roman - Italic Bold", TextOptions.Set(FontStyle: TextFontStyle.Italic, FontWeight: TextFontWeight.Bold));
            builder.NewLine();

            builder.AddText("Arial - Normal", TextOptions.Set(FontFamily: TextFontFamily.Arial));
            builder.NewLine();

            builder.AddText("Arial - Bold", TextOptions.Set(FontFamily: TextFontFamily.Arial, FontWeight: TextFontWeight.Bold));
            builder.NewLine();

            builder.AddText("Arial - Italic", TextOptions.Set(FontFamily: TextFontFamily.Arial, FontStyle: TextFontStyle.Italic));
            builder.NewLine();

            builder.AddText("Arial - Italic Bold", TextOptions.Set(FontFamily: TextFontFamily.Arial, FontStyle: TextFontStyle.Italic, FontWeight: TextFontWeight.Bold));
            builder.NewLine();
            builder.NewLine();

            builder.AddHeading("Colors");
            builder.AddText("Red", TextOptions.Set(FontColor: Color.Red));
            builder.NewLine();
            builder.AddText("Green", TextOptions.Set(FontColor: Color.Green));
            builder.NewLine();
            builder.AddText("Blue", TextOptions.Set(FontColor: Color.Blue));
            builder.NewLine();


            //
            // Paragraphs
            //

            builder.NewPage();
            builder.NewLine();
            builder.AddTitle("Paragraphs");
            builder.NewLine();

            builder.AddHeading("Left Aligned");
            builder.AddParagraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
            builder.NewLine();

            builder.AddHeading("Center Aligned");
            builder.AddParagraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", ParagraphOptions.Set(TextAlignment: TextAlignment.Center));
            builder.NewLine();

            builder.AddHeading("Right Aligned");
            builder.AddParagraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", ParagraphOptions.Set(TextAlignment: TextAlignment.Right));
            builder.NewLine();

            builder.AddHeading("Justified Aligned");
            builder.AddParagraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", ParagraphOptions.Set(TextAlignment: TextAlignment.Justify));
            builder.NewLine();


            //
            // Images
            //

            builder.NewPage();
            builder.NewLine();
            builder.AddTitle("Images");
            builder.NewLine();

            string imagepath = @"Sunset.jpg";

            builder.AddImage(imagepath, 50);
            builder.NewLine();

            builder.AddImage(imagepath, 100);
            builder.NewLine();

            builder.AddImage(imagepath, 150);
            builder.NewLine();


            //
            // Tables
            //

            builder.NewPage();
            builder.NewLine();
            builder.AddTitle("Tables");
            builder.NewLine();

            var tableOptions = TableOptions.Set(
                DefaultFontFamily: TextFontFamily.TimesNewRoman,
                BorderHeaderWidth: 1.0,
                BorderTopWidth: 0.0,
                BorderBottomWidth: 1.0,
                BorderHorizontalWidth: 0.8,
                BorderVerticalWidth: 0.6,
                BorderVerticalColor: Color.DarkGray,
                ColumnWidths: new List <double>(new double[] { 1.0, 2.0, 1.0 })
                );

            var table = new Table(tableOptions);

            var headerCellOptions = new TableCellOptions()
            {
                FontOptions     = table.Options.HeaderFontOptions,
                TextAlignment   = TextAlignment.Center,
                BackgroundColor = Color.LightGray
            };

            // change font family from the default
            headerCellOptions.FontOptions.FontFamily = TextFontFamily.Arial;

            var headerRowOptions = TableRowOptions.Set(TableCellOptions: headerCellOptions);

            var headers = new TableRow(headerRowOptions);

            headers.AddCell("Header 1");
            headers.AddCell("Header 2");
            headers.AddCell("Header 3");
            table.AddHeaders(headers);


            // default options for a table cell
            var defaultTableCellOptions = new TableCellOptions()
            {
                FontOptions = table.Options.CellFontOptions,
            };

            // change the font color
            defaultTableCellOptions.FontOptions.FontColor = Color.DarkGray;

            // specific cell options
            var descriptionTableCellOptions = TableCellOptions.Set(FontColor: Color.Red, FontFamily: table.Options.DefaultFontFamily);
            var amountTableCellOptions      = TableCellOptions.Set(TextAlignment: TextAlignment.Right, BackgroundColor: Color.LightGreen, FontFamily: TextFontFamily.Arial);

            // default options for a table row
            var defaultTableRowOptions = TableRowOptions.Set(TableCellOptions: defaultTableCellOptions);

            var row1 = new TableRow(defaultTableRowOptions);

            row1.AddCell("Row 1");
            row1.AddCell("Item 1", descriptionTableCellOptions);
            row1.AddCell("123.00", amountTableCellOptions);
            table.AddRow(row1);

            var row2 = new TableRow(defaultTableRowOptions);

            row2.AddCell("Row 2");
            row2.AddCell("Item 2", descriptionTableCellOptions);
            row2.AddCell("123.00", amountTableCellOptions);
            table.AddRow(row2);

            var row3 = new TableRow(defaultTableRowOptions);

            row2.AddCell("Row 3");
            row2.AddCell("Item 3", descriptionTableCellOptions);
            row2.AddCell("123.00", amountTableCellOptions);
            table.AddRow(row2);

            builder.AddTable(table);



            //
            // Lines
            //

            builder.NewPage();
            builder.NewLine();
            builder.AddTitle("Lines");
            builder.NewLine();

            var lineOptions = new LineOptions()
            {
                LineColor = Color.Blue,
                LineWidth = 1.0
            };

            builder.AddLine(80, LineOptions.Set(LineColor: Color.Blue));
            builder.NewLine();

            builder.AddLine(140, LineOptions.Set(LineColor: Color.Green));
            builder.NewLine();

            builder.AddLine(190, LineOptions.Set(LineColor: Color.Red));


            // save file
            var    guid     = System.Guid.NewGuid();
            string filepath = String.Format("TestPdfBuilder_{0}.pdf", guid.ToString("N"));

            using (var fileStream = new FileStream(filepath, FileMode.Create, FileAccess.Write))
            {
                byte[] data = builder.GetBytes();
                fileStream.Write(data, 0, data.Length);
            }

            builder.Close();

            Assert.IsTrue(1 == 1);
        }
Ejemplo n.º 23
0
        void ControlTreeDataLoader.LoadData()
        {
            CssClass = CssClass.ConcatenateWithSpace(CssElementCreator.CssClass);

            var rand         = new Random();
            var actualColors = (colors ?? getDefaultColors()).Take(seriesCollection.Count())
                               .Pad(seriesCollection.Count(), () => Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256)));

            Func <DataSeries, Color, BaseDataset> datasetSelector;
            OptionsBase options;

            switch (setup.ChartType)
            {
            case ChartType.Line:
                datasetSelector = (series, color) => new Dataset(color, series.Values.TakeLast(setup.MaxXValues));
                options         = new LineOptions {
                    bezierCurve = false
                };
                break;

            case ChartType.Bar:
                datasetSelector = (series, color) => new BaseDataset(color, series.Values.TakeLast(setup.MaxXValues));
                // ReSharper disable once RedundantEmptyObjectOrCollectionInitializer
                options = new BarOptions {
                };
                break;

            default:
                throw new UnexpectedValueException(setup.ChartType);
            }

            var chartData = new ChartData(
                setup.Labels.TakeLast(setup.MaxXValues),
                seriesCollection.Zip(actualColors, (series, color) => datasetSelector(series, color)).ToArray());

            var canvas = new HtmlGenericControl("canvas");

            switch (setup.ChartType)
            {
            case ChartType.Line:
            case ChartType.Bar:
                canvas.Attributes.Add("height", "400");
                break;

            default:
                throw new UnexpectedValueException(setup.ChartType);
            }
            Controls.Add(canvas);

            if (seriesCollection.Count() > 1)
            {
                Controls.Add(
                    new Section(
                        "Key",
                        new ControlLine(
                            chartData.datasets.Select(
                                (dataset, i) =>
                                new Literal
                {
                    Text =
                        @"<div style='display: inline-block; vertical-align: middle; width: 20px; height: 20px; background-color: {0}; border: 1px solid {1};'>&nbsp;</div> {2}"
                        .FormatWith(dataset.fillColor, dataset.strokeColor, seriesCollection.ElementAt(i).Name)
                } as Control).ToArray()).ToSingleElementArray(),
                        style: SectionStyle.Box));
            }

            // Remove this when ColumnPrimaryTable supports Excel export.
            var headers   = setup.XAxisTitle.ToSingleElementArray().Concat(seriesCollection.Select(v => v.Name));
            var tableData = new List <IEnumerable <object> >(seriesCollection.First().Values.Count());

            for (var i = 0; i < tableData.Capacity; i++)
            {
                var i1 = i;
                tableData.Add(setup.Labels.ElementAt(i1).ToSingleElementArray().Concat(seriesCollection.Select(v => v.Values.ElementAt(i1).ToString())));
            }
            Controls.Add(getExportButton(headers, tableData));

            var table = new ColumnPrimaryTable(
                firstDataFieldIndex: 1,
                items:
                new EwfTableItem(from i in setup.XAxisTitle.ToSingleElementArray().Concat(setup.Labels) select(EwfTableCell) i).ToSingleElementArray()
                .Concat(
                    from series in seriesCollection
                    select new EwfTableItem(((EwfTableCell)series.Name).ToSingleElementArray().Concat(from i in series.Values select(EwfTableCell) i.ToString()))));

            Controls.Add(table);

            using (var writer = new StringWriter()) {
                writer.WriteLine("var canvas = document.getElementById( '{0}' );".FormatWith(canvas.ClientID));
                writer.WriteLine("canvas.width = $( canvas ).parent().width();");
                writer.WriteLine("new Chart( canvas.getContext( '2d' ) ).{0}( {1}, {2} );".FormatWith(setup.ChartType, chartData.ToJson(), options.ToJson()));
                jsInitStatements = writer.ToString();
            }
        }