Create an export and download a file

Contents[Hide]

1. Overview

This article will guide you through exporting a dashboard, report, or other view type to PDF and then saving it to a file using the REST API. For example, you could embed a view into another web application and trigger the file export from the parent application toolbar.

To create an export and a download a file you will need to do the following:

  • Log on and get a session
  • Create an export
  • Download the export result

2. Log on and get a session

To log on and get a session using the REST API, you will need to make a POST /API/LogOn request. The following is an example of how to accomplish this:

using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Globalization;

// ... 

string baseUrl = "http://localhost:8010";

var cookieContainer = new CookieContainer();

string sessionId = string.Empty;

using (HttpClientHandler httpClientHandler = new HttpClientHandler())
{
    httpClientHandler.CookieContainer = cookieContainer;

	using (HttpClient httpClient = new HttpClient(httpClientHandler))
	{
		// Get Session ID
		string logonUri = string.Concat(baseUrl, "/Api/LogOn/");
			
		var logonOptions = new
		{
			accountName = "admin",
			password = "1234",
			cultureName = string.Empty,
			deleteOtherSessions = true,
			isWindowsLogOn = false
		};
	
		JavaScriptSerializer serializer = new JavaScriptSerializer();
		var requestBodyAsString = serializer.Serialize(logonOptions);
		StringContent content = new StringContent(
			requestBodyAsString,
			Encoding.UTF8,
			"application/json"
		);
			
		string jsonString = string.Empty;
	
		using (var response = httpClient.PostAsync(logonUri, content).Result)
		{
			jsonString = response.Content.ReadAsStringAsync().Result;
		}
	
		var obj = (Dictionary<string, object>)serializer.DeserializeObject(jsonString);
		
		sessionId = obj["sessionId"].ToString();

		// ...
    }
}

Tip
For multiple examples of REST logon visit the POST /LogOn/ page in the REST API documentation.

3. Create an export

After getting a session ID, you can create an export. This will be accomplished by making a POST /API/Export call to the REST API. The following example creates an export for the view with a particular ID. The providerId is 5752eb39-40b5-4d79-b96b-9f9297c67193 which is the standard PDF export provider ID. The isLegacyExport property is set to true to avoid passing the viewData property.

string url = string.Format(
	CultureInfo.InvariantCulture,
	"{0}/API/Export/",
	baseUrl
);

var exportRequestOptions = new 
{
	__classType = "dundas.export.ExportRequest",
	isLegacyExport = true,

	// PDF Exporter
	providerId = "5752eb39-40b5-4d79-b96b-9f9297c67193",
	viewId = "e16138cd-b78f-4c43-9b2d-d0e68f427998"
};

requestBodyAsString = serializer.Serialize(exportRequestOptions);

string exportResultId = string.Empty; 

// Add an Authorization header (v10 and higher)
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessionId);

// Define the request body
HttpContent requestBody = null;
requestBody = new StringContent(requestBodyAsString, Encoding.UTF8," application/json");
using (var response = httpClient.PostAsync(url, requestBody).Result)
{
	if (response.StatusCode == HttpStatusCode.OK)
	{
		Console.WriteLine("Success");

		string jsonObject = response.Content.ReadAsStringAsync().Result;
		
		exportResultId = jsonObject.Trim('\"');
	}
}

Note
Passing the session ID in an authorization header requires version 10 or higher. In earlier versions, you can pass it as a query string parameter in the URL: ?sessionId={1}

4. Download the export result

Now that you have the export ID, you can make the following request to GET /Export/Result/{id}/ to get the file from the REST API. The following is an example of how to download the export file, and then save it to C:\Temp\file.pdf:

if (!string.IsNullOrEmpty(exportResultId))
{
	url = string.Format(
		CultureInfo.InvariantCulture,
		"{0}/API/Export/Result/{1}/?isDownloadLink={2}",
		baseUrl,
		exportResultId,
		false
	);
		
	using (var response = httpClient.GetAsync(url).Result)
	{
		if (response.StatusCode == HttpStatusCode.OK)
		{
			byte[] fileBytes = response.Content.ReadAsByteArrayAsync().Result;
				
			File.WriteAllBytes(@"C:\Temp\file.pdf", fileBytes);
		}
	}
}


5. Entire code

The following is the entire example together: the sample logs in, creates a PDF export for the view with ID e16138cd-b78f-4c43-9b2d-d0e68f427998, then the file is downloaded and saved:

using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Globalization;

// ...

string baseUrl = "http://localhost:8010";

var cookieContainer = new CookieContainer();

string sessionId = string.Empty;

using (HttpClientHandler httpClientHandler = new HttpClientHandler())
{
    httpClientHandler.CookieContainer = cookieContainer;

	using (HttpClient httpClient = new HttpClient(httpClientHandler))
	{
		// Get Session ID
		string logonUri = string.Concat(baseUrl, "/Api/LogOn/");
			
		var logonOptions = new
		{
			accountName = "admin",
			password = "1234",
			cultureName = string.Empty,
			deleteOtherSessions = true,
			isWindowsLogOn = false
		};
	
		JavaScriptSerializer serializer = new JavaScriptSerializer();
		var requestBodyAsString = serializer.Serialize(logonOptions);
		StringContent content = new StringContent(
			requestBodyAsString,
			Encoding.UTF8,
			"application/json"
		);
			
		string jsonString = string.Empty;
	
		using (var response = httpClient.PostAsync(logonUri, content).Result)
		{
			jsonString = response.Content.ReadAsStringAsync().Result;
		}
	
		var obj = (Dictionary<string, object>)serializer.DeserializeObject(jsonString);
		
		sessionId = obj["sessionId"].ToString();
					
		string url = string.Format(
			CultureInfo.InvariantCulture,
			"{0}/API/Export/",
			baseUrl
		);
		
		var exportRequestOptions = new
		{
			__classType = "dundas.export.ExportRequest",
			isLegacyExport = true,
	
			// PDF Exporter
			providerId = "5752eb39-40b5-4d79-b96b-9f9297c67193",
			viewId = "e16138cd-b78f-4c43-9b2d-d0e68f427998"
		};
		
		requestBodyAsString = serializer.Serialize(exportRequestOptions);
		
		string exportResultId = string.Empty; 

		// Add an Authorization header (v10 and higher)
		httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessionId);
		
		// Define the request body
		HttpContent requestBody = null;
		requestBody = new StringContent(requestBodyAsString, Encoding.UTF8, "application/json");
		using (var response = httpClient.PostAsync(url, requestBody).Result)
		{
			if (response.StatusCode == HttpStatusCode.OK)
			{
				Console.WriteLine("Success");
		
				string jsonObject = response.Content.ReadAsStringAsync().Result;
				
				exportResultId = jsonObject.Trim('\"');
			}
		}
			
		if (!string.IsNullOrEmpty(exportResultId))
		{
			
		    url = string.Format(
				CultureInfo.InvariantCulture,
				"{0}/API/Export/Result/{1}/?isDownloadLink={2}",
				baseUrl,
				exportResultId,
				false
			);
					
				
					
			using (var response = httpClient.GetAsync(url).Result)
			{
				if (response.StatusCode == HttpStatusCode.OK)
				{
					byte[] fileBytes = response.Content.ReadAsByteArrayAsync().Result;
							
					File.WriteAllBytes(@"C:\Temp\file.pdf", fileBytes);
				}
			}		
		}
	}
}

6. See also

Dundas Data Visualization, Inc.
400-15 Gervais Drive
Toronto, ON, Canada
M3C 1Y8

North America: 1.800.463.1492
International: 1.416.467.5100

Dundas Support Hours:
Phone: 9am-6pm, ET, Mon-Fri
Email: 7am-6pm, ET, Mon-Fri