Angular Common - Client-Side Exporting and Printing

Although the DevExtreme Data Visualization widgets can be displayed in any browser on any platform, there are cases when printing a chart or having it as an image or a document may be necessary for an end user. For these cases, the DevExtreme Data Visualization widgets provide the client-side exporting and printing features. This guide shows how to use these features in the UI and in code. Also, it explains how to set up a server-side proxy that is necessary if you plan to support these features in Safari on Mac OS.

Watch Video

Exporting and Printing in the UI

To export or print a widget, a user clicks DevExtreme HTML5 DataVisualization Charts Export Print and selects a command from the drop-down menu that appears. The Print command opens the Print window in the browser that lets the user to select preferred printing options and to send the print job to the printer. The other commands save a file of the selected format on the user's local storage.

DevExtreme HTML5 DataVisualization Charts Export Print

Exporting and printing in the UI are configured by the export object. The following exporting and printing characteristics can be changed using the fields of this object.

  • Availability
    To enable exporting, assign true to the enabled field. With this setting, printing becomes available as well. If you need only exporting, disable printing by setting the printingEnabled field to false.
  • Formats and File Name
    By default, a user can export the widget into five formats: PNG, PDF, JPEG, SVG and GIF. To alter this set, use the formats option. In addition, you can change the default name for the file with the exported widget using the fileName option.
  • Background Color
    By default, the background of the widget is transparent. To fill it with a color of your choice, specify the backgroundColor option.
See Also
  • Setting Up a Server-Side Proxy - shows how to set up a server-side proxy to support the exporting and printing features in the Safari on Mac OS browser.

Exporting and Printing in Code

To export a widget in code, call its exportTo(fileName, format) method passing the needed file name and format ('PNG', 'PDF', 'JPEG', 'SVG' or 'GIF') as the arguments.

JavaScript
widgetInstance.exportTo('Test Chart', 'PDF');

To print a widget, call its print() method. Like the Print command in the Exporting/Printing menu, this method opens the Print window in the browser.

JavaScript
widgetInstance.print();

Also, the DevExtreme Data Visualization widgets fire the following exporting-related events.

  • exporting
    Allows you to request export details or prevent exporting.
  • exported
    Allows you to notify an end user when exporting is completed.
  • fileSaving
    Allows you to access exported data in the BLOB format and/or prevent it from being saved in a file on the user's local storage.

Setting Up a Server-Side Proxy

If your application will be used in browsers that do not implement an API for saving files (for instance, Safari on Mac OS) and you need the exporting feature to work correctly, you can implement a server-side proxy, which will stream the file back to an end user in response to a POST request. The proxy implementation is different for each platform.

ASPx

If your server runs the ASP.NET web application framework, you can implement a proxy using the following HTTP handler.

C#
VB
using System;
using System.Web;
namespace ExportService {
    public class ExportHandler : IHttpHandler {
        public void ProcessRequest(HttpContext context) {
            if(context.Request.Form["contentType"] != null && 
               context.Request.Form["fileName"]    != null && 
               context.Request.Form["data"]        != null) {
                context.Response.Clear();
                context.Response.ContentType = context.Request.Form["contentType"].ToString();
                context.Response.Charset = "UTF-8";
                context.Response.Expires = 0;
                context.Response.AppendHeader("Content-transfer-encoding", "binary");
                context.Response.AppendHeader("Content-Disposition", 
                                              "attachment; filename=" + context.Request.Form["fileName"].ToString());
                context.Response.BinaryWrite(Convert.FromBase64String(context.Request.Form["data"].ToString()));
                context.Response.Flush();
                context.Response.End();
            }
        }
        public bool IsReusable {
            get { return false; }
        }
    }
}
Imports System
Imports System.Web
Namespace ExportService
    Public Class ExportHandler
        Implements IHttpHandler
        Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            If context.Request.Form("contentType") IsNot Nothing AndAlso
               context.Request.Form("fileName")    IsNot Nothing AndAlso
               context.Request.Form("data")        IsNot Nothing Then
                context.Response.Clear()
                context.Response.ContentType = context.Request.Form("contentType").ToString()
                context.Response.Charset = "UTF-8"
                context.Response.Expires = 0
                context.Response.AppendHeader("Content-transfer-encoding", "binary")
                context.Response.AppendHeader("Content-Disposition", "attachment; filename=" & context.Request.Form("fileName").ToString())
                context.Response.BinaryWrite(Convert.FromBase64String(context.Request.Form("data").ToString()))
                context.Response.Flush()
                context.Response.End()
            End If
        End Sub
        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property
    End Class
End Namespace

PHP

If your server-side language is PHP, add a page with the following code to your website.

<?php
    if(!empty($_POST["data"]) && !empty($_POST["contentType"]) && !empty($_POST["fileName"])) {
      header("Access-Control-Allow-Origin: *");
      header("Content-type: {$_POST[contentType]};\n");
      header("Content-Transfer-Encoding: binary");
      header("Content-length: ".strlen($_POST["data"]).";\n");
      header("Content-disposition: attachment; filename=\"{$_POST[fileName]}\"");
      die(base64_decode($_POST["data"]));
    } 
?>

Usage

To enable server-side proxy support in a widget, set the export.proxyUrl option to the proxy that will stream the file to an end user.

dxExporter

IMPORTANT: This topic describes obsolete tools and approaches. Instead of them, consider using techniques described earlier in this guide.

Also, you can use the Exporter widget to provide an end user with the exporting and printing capabilities. To operate, this widget requires the PhantomJS WebKit running on a server. This topic shows how to deploy a server and configure the Exporter widget.

Deploy a Server

The Exporter widget can export any widget from the DevExtreme Data Visualization library into a PNG, PDF, SVG, JPEG or GIF file. In order to work, Exporter requires the PhantomJS WebKit. This WebKit allows you to use the client-server model where PhantomJS performs as a server. In this article, the Exporter basics are explained using a simple example where a single computer is used as the client and as the server.

Start by deploying the server that will process requests by following the steps below.

  • Download the zip-archive with the version 1.9.X of PhantomJS and unpack it. Name the folder PhantomJS.

  • Copy the Exporter folder to the PhantomJS folder. You can find the Exporter folder in the DevExtreme zip archive or in the folder where you have installed DevExtreme.

  • Open the system command line and specify the directory with the phantomjs.exe file as the current directory.

  • Type the following line.

    phantomjs Exporter/exporter-server.js 127.0.0.1 3003

    Here, Exporter/exporter-server.js refers to the script that implements the server logic. This script is supplied by DevExtreme. It is followed by the IP address that is assigned to your server and the number of the port that will be used for listening. Since the requests will be sent and received on the same machine in this example, the IP address corresponding to localhost is used. If the command line responds with the "OK, PhantomJS is ready." message, the server is deployed successfully.

NOTE
It is necessary for the phantomjs.exe process to operate on the server during export. Therefore, do not close the PhantomJS console window until you have finished exporting your widget.

Embed dxExporter

To add Exporter to your page, do the following.

  • Provide links to the exporter client script and one of the external stylesheets as it is shown below.

    HTML
    <link rel="stylesheet" type="text/css" href="dx.exporter.light.css">
    <!-- <link rel="stylesheet" type="text/css" href="dx.exporter.dark.css"> -->
    <script src="Exporter/dx.exporter.js"></script>
  • Add a div container for the Exporter widget.

    HTML
    <div id='exportMenu'></div>
  • Create the Exporter widget within this container using the jQuery, Knockout or AngularJS approach. In the code below, the widget is created using the jQuery approach.

    JavaScript
    $(function () {
        $("#exportMenu").dxExporter();
    });

If you run your page, you will see the Exporter Icon ChartJS and Exporter Icon ChartJS icons on it. But exporting and printing do not work yet, because the Exporter widget is not tuned properly. Refer to the next step to tune it.

Tune dxExporter

To ensure proper operation by the Exporter, several options should be specified.

  • Assign a jQuery selector to the sourceContainer option. This selector should specify the div element that contains the widget you wish to export.

  • Specify the URL of your server using the serverUrl option. In this example, it is 'http://127.0.0.1:3003'.

  • Additionally you can alter the default file name using the fileName option, change the set of available formats using the exportFormat option and enable/disable the entire export menu or only the printing button using the showMenu and printingEnabled options.

Now everything is ready for you to try the Exporter widget. Hover over the Exporter Icon ChartJS icon and choose the appropriate format to export your widget. In addition, you can change the print parameters within the Print window. To call this window, click the Exporter Icon ChartJS icon.

As you can see, the Exporter widget is very easy to use and presents your charts even when scripts are disabled.