HTML is often easier to generate than SVG. Can it be converted to SVG? I've found a cloud service with an API that does a nice job converting various formats: CloudConvert. I ended up implementing a small part of their API to do the conversion. The only thing you need is an API key and CloudConvert does the rest.
Converter
The following class will implement the raw input type of the API. Basically you'll need to do the following steps:
- Create a convert process on CloudConvert.
- Use the process URL to post the raw data with
download=true
andwait=true
. - Return the result of the URL.
To make thing easier, I've created a converter class that leverages async
to return the content of the SVG:
public class RawCloudConvert
{
private string apiKey;
public RawCloudConvert(string apiKey)
{
this.apiKey = apiKey;
}
public async Task<string> Convert(string inputFormat, string outputFormat, string fileName, string data)
{
var url = await CreateProcess(inputFormat, outputFormat);
return await Upload(url, fileName, data, outputFormat);
}
private async Task<string> CreateProcess(string inputFormat, string outputFormat)
{
var request = new
{
apikey = apiKey,
inputformat = inputFormat,
outputformat = outputFormat
};
var json = await PostJson("https://api.cloudconvert.com/process", request);
dynamic obj = JObject.Parse(json);
return "https:" + obj.url;
}
private static async Task<string> Upload(string url, string fileName,
string data, string outputFormat)
{
var request = new
{
input = "raw",
file = data,
filename = fileName,
outputformat = outputFormat,
download = "true",
wait = "true"
};
return await PostJson(url, request);
}
private static async Task<string> PostJson(string url, object data)
{
var parameters = JsonConvert.SerializeObject(data);
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
return await wc.UploadStringTaskAsync(url, "POST", parameters);
}
}
}
Usage
Let's create the controller that does the conversion. Just post the HTML to the controller and it will spit back the SVG. To make things easier on IIS, we'll be using the AsyncController
.
public class ConversionController : AsyncController
{
[HttpPost]
[ValidateInput(false)]
public async Task<ActionResult> ToSvg(string html)
{
string apiKey = "{your-key-here}";
var rcc = new RawCloudConvert(apiKey);
//create process
string result = await rcc.Convert("html", "svg", "my-html.html", html);
//return content
return Content(result, "image/svg+xml");
}
}
That's it. Just add the controller en the converter to your project.