JS Chart: Getting Started

This is step-by-step tutorial on how to setup a JavaScript chart using MindFusion JS Chart library. In the sample here we will use a pie chart but the steps are applicable to any type of chart with small modifications.

The video for this tutorial is uploaded on YouTube at https://www.youtube.com/watch?v=kc1nNe4p770

I. The Web Page

Basically, our sample consists of an HTML file and a Scripts folder, which will hold all used *.js files. In the web page that will hold the control we add two JS references.

The first one is the config file:

<script type="text/javascript" src="Scripts/config.js">

We will define our chart in a PieChart.js file that we will place in the Scripts folder.

In the body of the file we create a div that holds a canvas.

The canvas renders the chart and we will access and use it in the JavaScript file. That’s why it is important that the canvas has an id.

II. Setup of the *.JS File

In the PieChart.js file we create a single method that will be responsible for building and customizing the chart:

define(["require", "exports", 'MindFusion.Charting'], function (require, exports, m) {
....
}

The first few lines define variables used to reference various chart namespaces:

var Charting = m.MindFusion.Charting;
var Controls = m.MindFusion.Charting.Controls;
var Collections = m.MindFusion.Charting.Collections;
var Drawing = m.MindFusion.Charting.Drawing;

III. General Chart Settings

We create the chart from the canvas in the HTML file.

var pieChart = new Controls.PieChart( document.getElementById('pieChart'));

Then we set a title for the chart and we increase the font size for the title:

pieChart.title = "Corporate Sales";
pieChart.theme.titleFontSize = 24;	

IV. Series

The pie chart holds a single PieSeries.. For it we need data, inner and outer labels.
The data is a list with numbers:

var values = new Collections.List([20, 30, 10, 40, 35]);

The labels are a list with strings. Here is how we create the series:

pieChart.series = new Charting.PieSeries( values, null, new Collections.List(["a", "b", "c", "d", "e"]));

If you run the chart now you’ll see the pie with labels painted in a light green color.

initial-js-chart

So, we need

V. Styling

The styling includes brushes for the pie pieces:

var brushes = new Collections.List([
new Drawing.Brush("#081b67"),
new Drawing.Brush("#cc2020"),
new Drawing.Brush("#7D7D7D"),
new Drawing.Brush("#67a6c7"),
new Drawing.Brush("#d0d0d0")
    ]);
var seriesBrushes = new Collections.List();
   seriesBrushes.add(brushes);

a single pie pen:

var pens = new Collections.List([
     new Drawing.Brush("#ffffff")
]);
var seriesPens = new Collections.List();
 seriesPens.add(pens);

a thickness for the pie pen:

var thicknesses = new Collections.List([
        15
		
]);

var seriesThicknesses = new Collections.List();
seriesThicknesses.add(thicknesses);

and a DashStyle for it:

var dashStyles = new Collections.List([
        Drawing.DashStyle.Solid
]);
var seriesDashStyles = new Collections.List();
  seriesDashStyles.add(dashStyles);

We could have set different pens, thicknesses and DashStyle for each pie piece, but we want all the pieces to be outlined with a single pen.

Note that those settings are of type array and are nested in another array. That is because the styling might apply to multi-series charts and each array is responsible for styling the elements of each series.

In our sample we style the pie chart with a PerElementSeriesStyle object, which we assign to the seriesStyle property:

pieChart.plot.seriesStyle = new Charting.PerElementSeriesStyle(seriesBrushes, seriesPens, seriesThicknesses, seriesDashStyles);

VI. Legend

The legend needs to be styled – the background, border and title need to be specified and customized to make it look better.

The legend title is a property of the chart.

pieChart.legendTitle = "Period";

The styling settings for a legend can be accessed through the theme property:

pieChart.theme.legendBackground = new Drawing.Brush("#ffffff");
pieChart.theme.legendBorderStroke = new Drawing.Brush("#cecece");
pieChart.theme.legendBorderStrokeThickness = 1.0;
pieChart.theme.legendTitleFontSize = 16;

The legend label is read from the title of each series in the chart. In our case we use:

pieChart.series.title = "2016";

With this our chart is complete. A hint: if you want to make the pie labels from inner to outer, you just need to change the position of the null value in the PieSeries constructor.

JS Pie Chart

JS Pie Chart

Download Sample

MindFusion JS Chart is an interactive library for charts and gauges written purely in JavaScript. It supports all common chart types, multiple series, custom data,financial charts, a large selection of gauges and rich styling capabilities. The elegant architecture of the library allows you to create dashboards, charts with multiple different types of series in a single plot, unlimited number of axes, reusable styling themes, various oval and linear gauges. The innovative approach to data lets you define your own data classes by implementing a single interface.
The library also boasts a rich event set, zoom, pan, dragging of the legend and a set of many popular gauges. It is designed and implemented to provide JS developers with the perfect tool to create beautiful, interactive dashboards fast and easy. Download trial directly at http://mindfusion.eu/JavaScript.Chart.zip Get your license today at http://www.javascript-chart-buy.html

Lane diagram in JavaScript

In this post we will show how to use the JavaScript diagram library to create a lane diagram. The complete example is available here:

Lanes.zip

Create a new HTML page and add references to the jQuery library and to the MindFusion.Diagramming library:

<script src="jquery.min.js" type="text/javascript"></script>
<script src="MindFusion.Common.js" type="text/javascript"></script>
<script src="MindFusion.Diagramming.js" type="text/javascript"></script>

Create shortcuts to some classes from the diagram model:

var Events = MindFusion.Diagramming.Events;
var Diagram = MindFusion.Diagramming.Diagram;
var AnchorPattern = MindFusion.Diagramming.AnchorPattern;
var AnchorPoint = MindFusion.Diagramming.AnchorPoint;
var Alignment = MindFusion.Diagramming.Alignment;
var MarkStyle = MindFusion.Diagramming.MarkStyle;
var Style = MindFusion.Diagramming.Style;
var Theme = MindFusion.Diagramming.Theme;
var LinkShape = MindFusion.Diagramming.LinkShape;
var Shape = MindFusion.Diagramming.Shape;
var LaneGrid = MindFusion.Diagramming.Lanes.Grid;
var LaneHeader = MindFusion.Diagramming.Lanes.Header;
var LaneStyle = MindFusion.Diagramming.Lanes.Style;
var Rect = MindFusion.Drawing.Rect;
var Point = MindFusion.Drawing.Point;
var HandlesStyle = MindFusion.Diagramming.HandlesStyle;

Next, add a canvas the the page and create a diagram from it by using the Diagram.create() method:

diagram = Diagram.create($("#diagram")[0]);

You can obtain a reference to the diagram lane grid by calling the Diagram.getLaneGrid() method. You can use the returned object to add rows and columns to the grid and customize its appearance. Finally, to display the grid, call Diagram.setShowLaneGrid(). The customization is omitted here for brevity, but the full code is available in the associated sample project.

The lane grid implies some restrictions to the node and links inside of it. For example, the nodes can be moved only inside the row lanes of the grid. To enforce those restrictions, we will handle several diagram events:

diagram.addEventListener(Events.nodeCreated, onNodeCreated);
diagram.addEventListener(Events.nodeModified, onNodeModified);
diagram.addEventListener(Events.linkCreated, onLinkCreated);

In the nodeCreated event handler, get the gird cell at the top left of the node’s bounding rectangle and align the node to this cell:

function onNodeCreated(sender, e) {
    var node = e.getNode();
    node.setAnchorPattern(pattern);
    node.setHandlesStyle(HandlesStyle.HatchHandles3);

    // Place the box within the grid
    var bounds = node.getBounds();
    var topLeft = new Point(bounds.x, bounds.y);

    var cellBoundsReciever = {};
    if (!grid.getCellFromPoint(topLeft, cellBoundsReciever))
        return;
    var cellBounds = cellBoundsReciever.cellBounds;

    var pixel = 1;

    bounds.y = cellBounds.y + pixel;
    bounds.height = cellBounds.height - 2 * pixel;
    node.setBounds(bounds);
}

Similar rules can be applied to the links in the linkCreated event handler.

The following image illustrates the grid in action:

JavaScript Swimlane Diagram

For more information on MindFusion JavaScript diagram library, see its help reference and overview page.

Enjoy!

Class inheritance diagram in JavaScript

In this post we will show how to use the JavaScript diagram library to generate a class inheritance diagram. The complete example is available here:

InheritanceDiagram.zip

and a live version here:

http://mindfusion.eu/demos/jsdiagram/Inheritance.html

Let’s start by creating shortcuts to some classes from the diagram model:

var Diagram = MindFusion.Diagramming.Diagram;

var DiagramItem = MindFusion.Diagramming.DiagramItem;
var DiagramLink = MindFusion.Diagramming.DiagramLink;
var DiagramNode = MindFusion.Diagramming.DiagramNode;
var ShapeNode = MindFusion.Diagramming.ShapeNode;
var TableNode = MindFusion.Diagramming.TableNode;
var ContainerNode = MindFusion.Diagramming.ContainerNode;
var FreeFormNode = MindFusion.Diagramming.FreeFormNode;
var SvgNode = MindFusion.Diagramming.SvgNode;

var ScrollBar = MindFusion.Diagramming.ScrollBar;
var Rect = MindFusion.Drawing.Rect;
var Font = MindFusion.Drawing.Font;
var TreeLayout = MindFusion.Graphs.TreeLayout;

Next, create a function that takes a Diagram instance and a list of class names as parameters. It will create a TableNode for each class. Each property of the class prototype is listed in a TableNode cell. If the getBaseType function detects a class inherits another one from the list, we’ll create a link between their nodes. Finally, the diagram is arranged using the TreeLayout algorithm.

function createClassDiagram(diagram, classes)
{
    var classConstructors = [];

    // create a table node for each class
    for (var i = 0; i < classes.length; i++)
    {
        var className = classes[i];
        var node = diagram.getFactory().createTableNode(20, 20, 42, 42);
        node.redimTable(1, 0);
        node.setText(className);
        node.setBrush("white");
        node.setCaptionBackBrush("lightgray");
        node.setCaptionFont(
            new Font("sans-serif", 3, true /*bold*/, true /*italic*/));
        node.setScrollable(true);

        var ctor = eval(className);
        for (var property in ctor.prototype)
        {
            node.addRow();
            node.getCell(0, node.rows.length - 1).setText(property);
        }
        classConstructors.push(ctor);
        ctor.classNode = node;
    }
	
    // create a diagram link for each prototype inheritance
    classConstructors.forEach(function(ctor)
    {
        var base = getBaseType(ctor);
        if (base && base.classNode)
        {
            var link = diagram.factory.createDiagramLink(
                base.classNode,
                ctor.classNode);
            link.setHeadShape(null);
            link.setBaseShape("Triangle");
            link.setBaseShapeSize(3);
        }
    });

    // arrange as a tree
    var treeLayout = new TreeLayout();
    treeLayout.linkType = MindFusion.Graphs.TreeLayoutLinkType.Cascading;
    diagram.arrange(treeLayout);
}

The getBaseType implementation checks if a class was registered as a base for the argument using MindFusion.registerClass method or the common prototype inheritance pattern.

function getBaseType(ctor)
{
    // if class registered using MindFusion.registerClass
    if (ctor.__baseType)
        return ctor.__baseType;

    // if  prototypical inheritance with Child.prototype = new Parent()
    if (ctor.prototype && ctor.prototype.constructor != ctor)
        return ctor.prototype.constructor;
	
    return null;
}

The ready handler creates a Diagram instance binding it to a #diagram canvas element. It then calls createClassDiagram with a list of DiagramItem -derived classes as argument:

$(document).ready(function ()
{
    TableNode.prototype.useScrollBars = true;
    ScrollBar.prototype.background = "Lavender";
    ScrollBar.prototype.foreground = "DarkGray";

    // create a Diagram component that wraps the "diagram" canvas
    var diagram = Diagram.create($("#diagram")[0]);

    createClassDiagram(diagram,
    [
        "DiagramItem",
        "DiagramLink",
        "DiagramNode",
        "ShapeNode",
        "TableNode",
        "ContainerNode",
        "FreeFormNode",
        "SvgNode"
    ]);
});

If you run the sample now, you should see this nice visualization of MindFusion classes 🙂

JavaScript class inheritance diagram

For more information on MindFusion JavaScript diagram library, see its help reference and overview page.

Enjoy!

MindFusion WinForms Spreadsheet Control: Convert XLSX to PDF

This blog demonstrates how easily you can convert XLSX files to PDF using the Windows Forms Spreadsheet control.

Setup

Create a new WinForms application and add the necessary assemblies to the project. Add a WorkbookView control to the main application window. Note, that this is not necessary for the conversion – it is done only to display the original XLSX file.

Perform the conversion

Add a button to the main form, set its text to ‘Convert…’ and handle its Click event. In the event handler display an OpenFileDialog to query the user for the input XLSX file, then display a SaveFileDialog to request the target PDF file. Once the two files are specified, proceed with the conversion by creating an ExcelImporter and PdfExporter objects and using their Import and Export methods in succession:

// Import the data
var importer = new ExcelImporter();
importer.Import(xlsxPath, workbook1);

// Export the worksheet as PDF
var exporter = new PdfExporter();
exporter.EnableGridLines = true;
exporter.Export(workbook1.Worksheets[0], pdfPath);

// Open the PDF
System.Diagnostics.Process.Start(pdfPath);

The xlsxPath and pdfPath variables identify the respective XLSX and PDF file names. The workbook1 variable represents the Workbook displayed on the form. Once the conversion is complete, the PDF file is opened in the default PDF viewer by calling Process.Start.

The following image illustrates the result:

The source code of the project together with all necessary libraries can be downloaded from here:

Convert .XLSX to .PDF Files Using the WinForms Spreadsheet Control: Download Sample

You are welcome to ask any questions about the WorkbookView control at MindFusion discussion board or per e-mail at support@mindfusion.eu.

Click here here to visit the official page of the MindFusion WinForms Spreadsheet control.

We hope you find this tutorial useful and thank you for your interest in MindFusion developer tools.

Custom Templates With the WPF Diagram Control

In this blog you will learn how to create a presentation of a hierarchical organization using MindFusion WPF Diagram control. The hierarchy is presented as a diagram, where each node represents an employee in the organization and each link represents the direct relationship between employees. The nodes in the diagram use custom templates to give a more detailed description of the employee, as well as to enable editing of various properties.

Setup

Create a new WPF application and add the necessary assemblies to the project. In the main window, declare the following namespace:

xmlns:diag="http://mindfusion.eu/diagramming/wpf"

Then declare an instance of the DiagramView class inside the root grid:

<diag:diagramview x:name="diagramView">
    <diag:diagram x:name="diagram" backbrush="White">
</diag:diagram></diag:diagramview>

Creating the custom node

To create the custom node, from the “Project -> Add New Item” menu add a new CustomControl (WPF) item to the project. This automatically creates a themes folder inside the project and a generic.xaml resource dictionary, which contains the template of the newly added class. Rename the newly created file (and class) to OrgChartNode. Ensure that the new class derives from TemplatedNode rather than Control. Then define the following dependency properties in the class: Title, FullName, and Image, of types string and ImageSource respectively.

Define the appearance of the node in its template in the generic.xaml file. In this case the node will display a round border, an image of the employee, its title, name, and description, and several buttons that can be used to change the role of the employee or add subordinates. The components bind directly to the properties of the node class. For example:

<textbox acceptsreturn="False" fontfamily="Verdana" fontsize="12" borderbrush="Transparent" background="Transparent" text="{Binding FullName}"></textbox>

The complete listing of the node’s template can be found in the project below.

To handle the Click event of the buttons in the template, register a routed event handler in the OrgChartNode class:

AddHandler(Button.ClickEvent, new RoutedEventHandler(OnClick));
...
void OnClick(object sender, RoutedEventArgs e)
{
    ...
}

Declare an Index property in the OrgChartNode class, which will indicate the role of the employee. Changing the role will automatically update the title and background color of the node:

public int Index
{
    get { return Images.IndexOf(Image); }
    set
    {
        if (value != -1)
        {
            Image = Images[value];
            Title = Titles[value];
            Brush = Fills[value];
        }
        else
        {
            Image = null;
        }

        InvalidateVisual();
    }
}

Create the hierarchy

Now that the custom node is ready, we can create a diagram representing the hierarchy. In the code behind of the main window, create a series of OrgChartNode objects, each representing an employee in the organization, then link the nodes using the CreateDiagramLink method of the diagram Factory class:

var node1 = new OrgChartNode
{
    Bounds = new Rect(0, 0, 300, 160),
    FullName = "Mike Powell",
    Text = "This is the leader of the sample organization.",
    Index = 2
};
diagram.Nodes.Add(node1);

var node2 = new OrgChartNode
{
    Bounds = new Rect(0, 0, 300, 160),
    FullName = "Emily Williams",
    Text = "Emily is the leader highest in the PR hierarchy.",
    Index = 1
};
diagram.Nodes.Add(node2);
...
diagram.Factory.CreateDiagramLink(node1, node2);

Finally, arrange the hierarchy by using the built-in tree layout:

TreeLayout layout = new TreeLayout();
layout.Type = TreeLayoutType.Centered;
layout.LinkStyle = TreeLayoutLinkType.Cascading3;
layout.Direction = TreeLayoutDirections.TopToBottom;
layout.KeepRootPosition = false;
layout.LevelDistance = 40;
layout.Arrange(diagram);

The following image illustrates the result:

Diagramming_Wpf_Templates

The source code of the project together with all necessary libraries can be downloaded from here:

Download Organization Hierarchy Sample

You are welcome to ask any questions about the Diagram control at MindFusion discussion board or per e-mail at support@mindfusion.eu.

Click here here to visit the official page of the WPF diagram control.

We hope you find this tutorial useful and thank you for your interest in MindFusion developer tools.