Skip to main content

CSharp

Example of image generation using C#.

The Canvasflare API allows you to create images from specified HTML, CSS, and other parameters. Below is an example of how you can use this API in C# to generate an image.

Rendering an Image

Send a POST request to https://api.canvasflare.com/render with the necessary parameters to render an image.

Parameters

  • html - The HTML content you wish to render, e.g., <div>Your content</div>.
  • css - The CSS styling for your rendered image, e.g., .h1 { color: red }.
  • device_scale - Modifies the pixel density of the screenshot.
  • viewport_width - The width of the Chrome viewport.
  • viewport_height - The height of the Chrome viewport.
  • viewport_device - Emulates a given device's metrics and user agent.
  • viewport_has_touch - Indicates whether the viewport supports touch events.
  • viewport_landscape - Indicates whether the viewport is in landscape mode.
  • viewport_mobile - Specifies whether the meta viewport tag is considered.
  • full_page - If set to true screenshots entire webpage.
  • selector - A CSS selector corresponding to an element in the HTML.
  • ms_delay - Additional delay to ensure completion of JavaScript execution.
  • user_agent - An user agent for the request.

Example Request in C#

You can use the HttpClient class in C# to send HTTP requests:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class Program
{
public static async Task Main(string[] args)
{
var endpoint = "https://api.canvasflare.com/render?api_key=YOUR_API_KEY";
var payload = new
{
html = "<div>This is something</div>",
css = ".h1 { color: red }",
device_scale = 2,
viewport_width = 640,
viewport_height = 480,
ms_delay = 500
};

var jsonPayload = JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var client = new HttpClient();

try
{
var response = await client.PostAsync(endpoint, content);
var responseContent = await response.Content.ReadAsStringAsync();

if(response.IsSuccessStatusCode)
{
Console.WriteLine("Image created: " + responseContent);
}
else
{
Console.WriteLine("Error creating image: " + responseContent);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred: " + ex.Message);
}
}
}

Response

The API response will return a URL to the generated image that you can download or display.

Make Your Image URL Downloadable

You can add the parameter ?dl=true to the image URL to make the browser download the image automatically. For example:

https://api.canvasflare.com/image/8d063c49-3f15-46c1-91c7-9cf61e6758c6?dl=true

.NET

For this example to work, ensure that you have .NET installed and that the Newtonsoft.Json package is included in your project for JSON serialization. You can add Newtonsoft.Json via NuGet package manager in your C# project.