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.

MindFusion Component Suites With 30% Price Discount in July

Get a pack of MindFusion controls with 30% discount in July, 2016.

Get a pack of MindFusion controls with 30% discount in July, 2016.

MindFusion has completed integrating FreezePro Virtual Keyboard components in its WinForms and WPF component suites. On this occasion we offer all MindFusion
prospective buyers a special 30% discount on any license for any pack they buy throughout  July, 2016.

The discount is applied when you enter coupon code KPP-45K2D47GKJ at the purchase page. The number of times you can apply the discount is unlimited.

Clients who already own a license for a MindFusion Pack can get an upgrade
subscription with the same discount during the same time period.

If you are interested in purchasing just a Virtual Keyboard license then you use
a 20% discount from the retail price if you buy till July 31st, 2016. The coupon
code is VKP-45K2D47GKW.

The following “Buy” pages provide detailed information about the licensing scheme
and prices.

Buy MindFusion WinForms Pack License
Buy MindFusion WPF Pack License
Buy MindFusion WinForms Virtual Keyboard License
Buy MindFusion WPF Virtual Keyboard License

MindFusion reminds you that certain types of people and organizations are always
eligible for a discount – check here the list.

For additional questions, please write at support@mindfusion.eu.

Thank you for considering MindFusion as your partner in software development.

ASP.NET Org Chart with the Diagram Control

In this post you’ll learn how to create a beautiful organization chart where most of the work is done by the ASP.NET flowchart control. We’ll use the capabilities of the control to create nodes, where we’ll put an image and formatted text. We’ll create automatically links among the nodes and apply the tree layout algorithm to arrange the diagram. Let’s start.

I. Add the Necessary DLLs.

Create a new blank ASP.NET project and add those of the dll-s of the control that we need for this project:

ASP.NET Diagram dll-s needed to build the the org chart

ASP.NET Diagram dll-s needed to build the the org chart

MindFusion.Diagramming, MindFusion.Diagramming.WebForms, MindFusion.Common, MindFusion.Common.WebForms. The asp.net diagram control needs the MindFusion.Diagramming.js file to render its contents. If you add it directly into the project’s folder you won’t have to add a reference to it. Since we create a ew project folder “Scripts” where we put it, we’ll have to reference it in code. We’ll talk about this in the next step.

II. Setup of the Diagram Control.

We add a new WebForm file to the project and into the HTML code we register the diagramming dll with the tag “ndiag”.

<%@ Register Assembly="MindFusion.Diagramming.WebForms" Namespace="MindFusion.Diagramming.WebForms" TagPrefix="ndiag" %>

We need a reference to a few *.js and *.css files as shown below:

<link href="common/jquery-ui.min.css" rel\="stylesheet">
<link href="common/samples.css" rel="stylesheet">
<script type="text/javascript" src="common/jquery.min.js"></script>
<script type="text/javascript" src="common/jquery-ui.min.js"></script>
<script type="text/javascript" src="common/samples.js">

The *.js files are located in a folder “common” in the project. Of course, you can reference them from their respective online locations.

Don’t forget the ScriptManager:

<asp:scriptmanager id="ScriptManager1" runat="server">

</asp:scriptmanager>

Now it’s time for the diagram – we add it in the HTML of the page using the “ndiag” tag that we’ve defined above.

<ndiag:diagramview id="fc" runat="server" clientsidemode="Canvas" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px;" jslibrarylocation="Scripts/MindFusion.Diagramming.js" treeexpandedscript="onTreeExpanded">
      <diagram autoresize="RightAndDown" defaultshape="Rectangle" shapehandlesstyle="DashFrame">
</diagram></ndiag:diagramview>

The Diagram is in a DiagramView control that will render it contents. Node the “JsLibraryLocation” attribute – we use it to point to the location of the Diagramming.js file which we’ve placed in the Scripts folder in step 1.

III. Building the Diagram

We get the diagram object that we’ve defined in HTML like that:

Diagram diagram = fc.Diagram;

The data for the org chart is located in a XML file. The structure is something like this:

<employee>
  <name>Martin Larovsky</name>  
  <photourl>http://mindfusion.eu/_samples/ASP.NET_OrgChart/martin-larovsky.png</photourl>
  <title>COO</title>
  <level>Executive</level>
  <date>Aug 2015</date>  
    <employee>
      <name>Tanja Orsy</name>
..........................................

</employee></employee>

Each new hierarchy level is a list of Employee tags contained within the upper Employee node.

The first node is the top of the tree and we read it separately. First we open the XML document and then we get the first employee:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("http://mindfusion.eu/_samples/ASP.NET_OrgChart/employees.xml");
XmlNode ceo = xmlDoc.SelectSingleNode("Employee");

We use the methods of the diagram control to create a new shape node and assign its properties to the data that we’ve read from the XML file:

ShapeNode root = diagram.Factory.CreateShapeNode(nodeBounds);
root.Text = "" + ceo["Name"].InnerText + " (" + ceo["Title"].InnerText + ") since " +
ceo["Date"].InnerText + ""; 
root.Shape = Shape.FromId("RoundRect"); 
root.TextPadding = new Thickness(0, 0, 3, 0); 
root.Brush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(121, 109, 173)); 
root.TextFormat.Alignment = StringAlignment.Far; 
root.EnableStyledText = true; 
root.ImageUrl = ceo["PhotoUrl"].InnerText; 
root.ImageAlign = MindFusion.Drawing.ImageAlign.MiddleLeft;

The Factory class enables us to create different nodes within given bounds. HTML formatting of the text is supported because we have turned on the EnableStyledText property. The node shape is rounded rectangle for aesthetic reasons. The texi is aligned to the right and the image – to the left of the node. We use the ImageUrl property because the image is uploaded online and we just tell the ShapeNode from where to read it.

The nodes are read and created in a method that uses recurrence to cycle through all of them – you can see it in the sample. It has one line that’s worth noting:

//cycles through all nodes using recurrence and creates a DiagramNode for all employees
private void CreateChildren(Diagram diagram, DiagramNode parentDiagNode, XmlNode parentXmlNode)
{
foreach (XmlElement element in parentXmlNode.SelectNodes("Employee"))
{
.................................................................
diagram.Factory.CreateDiagramLink(parentDiagNode, node);

Note how we instruct the Factory to create a link between each node and its parent. This way we have the diagram ready.

IV. The Layout

If you run the application you’ll see just one node. It’s actually a pile of nodes. We need to arrange it but luckily the ASP.NET Diagram control has an impressive selection of layout algorithms. In our case the Tree layout is the perfect choice:

TreeLayout layout = new TreeLayout();
layout.Type = TreeLayoutType.Cascading;
layout.Direction = TreeLayoutDirections.LeftToRight;
layout.LinkStyle = TreeLayoutLinkType.Cascading2;
layout.NodeDistance = 3;
layout.LevelDistance = -8; // let horizontal positions overlap
layout.Arrange(diagram);

The TreeLayout class has plenty of customization options, here we have selected those that would make an org chart look best. You can experiment with the full set of options and see what looks right in your particular scenario.

Here is the final result:

ASP.NET Org Chart

ASP.NET Org Chart

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

Download ASP.NET Organization Browser Sample

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

Click here to visit the official page of MindFusion ASP.NET Diagram Control.

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

Node.js diagram module

MindFusion.Diagramming for JavaScript is now also available as a Node.js module, and you can use the diagram API you know and love in server code 🙂 A sample server application and the module script are available here:

diagram_nodejs.zip

For example, you can submit to server a diagram drawn interactively by the user and examine its contents there by iterating over the nodes and links members of the Diagram class:

// on client side
$.ajax(
{
	type: "post",
	url: "http://localhost:1234/diagram", 
	contentType: "application/json",
	data: diagram.toJson(),
	success: function(data)
	{
		console.log('success');
	},
	error: function(jqXHR, textStatus, err)
	{
		console.log(err);
	}
});

// on server side
app.post('/diagram', function(req, res)
{
    // won't be required in final release
    var dummyCanvas = { parentNode:{} };

    // create Diagram instance
    var diagram = new Diagram(dummyCanvas);

    // load diagram elements drawn by user
    diagram.fromJson(req.rawBody);

    // examine diagram contents
    console.log(diagram.nodes.length + " nodes");
    console.log(diagram.links.length + " links");
    diagram.nodes.forEach(function (node, index)
    {
        console.log("node " + index + ": " + node.getText());
    });

    // send some response
    res.send('ok');
});

Or you could build the diagram on server side and send it to the browser to render in client-side Diagram control:

// on server side
app.get('/diagram', function(req, res)
{
    // won't be required in final release
    var dummyCanvas = { parentNode:{} };

    // create Diagram instance
    var diagram = new Diagram(dummyCanvas);

    // create some diagram items
    var node1 = diagram.getFactory().createShapeNode(10, 10, 40, 30);
    var node2 = diagram.getFactory().createShapeNode(60, 10, 40, 30);
    var link = diagram.getFactory().createDiagramLink(node1, node2);

    // set nodes' content
    node1.setText("node.js");
    node1.setBrush("orange");
    node2.setText("hello there");

    // send diagram json
    res.send(
        diagram.toJson());
});

// on client side
$.ajax(
{
	type: "get",
	url: "http://localhost:1234/diagram", 
	success: function(data)
	{
		diagram.fromJson(data);
	},
	error: function(jqXHR, textStatus, err)
	{
		console.log(err);
	}
});

To run the sample Node.js application, run “node server.js” from command line and open http://localhost:1234/client.html in your browser. Draw some nodes and links, edit their text and click Post to see them enumerated in Node’s console. Clicking the Get button will show this diagram built on server side:

diagram built in node.js

For more information on MindFusion’s JavaScript Diagram API, see MindFusion.Diagramming online help

Enjoy!