Rendering part of the image
How to take generate part of image.
In this example, we will demonstrate how to use the selector parameter to render only a specific part of an image. The selector parameter allows you to target and capture a specific element within the HTML content.
selector param
The selector parameter is used to specify a CSS selector that corresponds to an element in the HTML. The image will be cropped precisely to this designated element.
Example HTML Content
Here is an example HTML content that we will use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>
And CSS part:
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}
Here is rendered image:

Using selector param
Using the selector parameter with the value .highlighted, we can capture the paragraph with the "highlighted" class:

Code examples
- Python
- Java
- Go
- Dart
- C#
- Kotlin
- C++
- Curl
import requests
url = 'https://api.canvasflare.com/render?api_key=YOUR_API_KEY'
html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>
'''
css = '''
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}
'''
# Specify the CSS selector for the element you want to capture
selector = ".highlighted"
# Set other parameters like device_scale, viewport_width, etc.
response = requests.post(url, data={'html': html, 'css': css, 'selector': selector})
if response.status_code == 200:
image_url = response.json()['imageUrl']
print(f"Image URL: {image_url}")
else:
print(f"Error creating image: {response.status_code}")
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class ImageGenerationExample {
static class ImageRequest {
String html;
String css;
String selector;
}
public static void main(String[] args) {
try {
String apiUrl = "https://api.canvasflare.com/render?api_key=YOUR_API_KEY";
ImageRequest request = new ImageRequest();
request.html = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>Advanced Example</title></head><body><div class=\"container\"><h1>Generating Part of Image Example</h1><p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p><p class=\"highlighted\">This paragraph has a special class called \"highlighted\".</p></div></body></html>";
request.css = "body { background-color: #f0f0f0; font-family: Arial, sans-serif; text-align: center; }.container { padding: 20px; background-color: #ffffff; border: 1px solid #cccccc; border-radius: 5px; margin: 20px; }h1 { color: #333333; }p { color: #666666; }.highlighted { background-color: yellow; }";
request.selector = ".highlighted";
Gson gson = new Gson();
String jsonInputString = gson.toJson(request);
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println("Response from server: " + response.toString());
}
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
System.out.println("Image generated successfully");
} else {
System.out.println("Error: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://api.canvasflare.com/render?api_key=YOUR_API_KEY"
html := `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>`
css := `body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}`
// Specify the CSS selector for the element you want to capture
selector := ".highlighted"
// Set other parameters like device_scale, viewport_width, etc.
// Create JSON payload
jsonData := map[string]string{
"html": html,
"css": css,
"selector": selector,
}
jsonValue, _ := json.Marshal(jsonData)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
// Handle the response, e.g., download or display the image
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Image URL:", string(body))
} else {
fmt.Println("Error creating image:", resp.Status)
}
}
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
final url = Uri.parse('https://api.canvasflare.com/render?api_key=YOUR_API_KEY');
final html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>
''';
final css = '''
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}
''';
// Specify the CSS selector for the element you want to capture
final selector = '.highlighted';
// Convert data to JSON
final jsonBody = json.encode({
'html': html,
'css': css,
'selector': selector,
});
try {
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
},
body: jsonBody,
);
if (response.statusCode == 200) {
// Handle the response, e.g., download or display the image
print('Image URL: ${response.body}');
} else {
print('Error creating image: ${response.statusCode}');
}
} catch (error) {
print('Error creating image: $error');
}
}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
static async Task Main(string[] args)
{
var url = "https://api.canvasflare.com/render?api_key=YOUR_API_KEY";
var html = @"<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""UTF-8"">
<meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
<title>Advanced Example</title>
</head>
<body>
<div class=""container"">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class=""highlighted"">This paragraph has a special class called ""highlighted"".</p>
</div>
</body>
</html>";
var css = @"body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}";
var selector = ".highlighted";
var payload = new
{
html = html,
css = css,
selector = selector
};
var jsonPayload = JsonConvert.SerializeObject(payload);
using (var httpClient = new HttpClient())
{
var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
try
{
var response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var imageUrl = await response.Content.ReadAsStringAsync();
Console.WriteLine("Image URL: " + imageUrl);
}
else
{
Console.WriteLine("Error creating image: " + response.StatusCode);
}
}
catch (Exception ex)
{
Console.WriteLine("Error creating image: " + ex.Message);
}
}
}
}
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
fun main() {
val url = "https://api.canvasflare.com/render?api_key=YOUR_API_KEY"
val html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>
"""
val css = """
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}
"""
val selector = ".highlighted"
val json = JSONObject()
json.put("html", html)
json.put("css", css)
json.put("selector", selector)
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val requestBody = json.toString().toRequestBody(mediaType)
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
try {
val response = client.newCall(request).execute()
if (response.isSuccessful) {
val imageUrl = response.body?.string()
println("Image URL: $imageUrl")
} else {
println("Error creating image: ${response.code}")
}
} catch (e: Exception) {
println("Error creating image: ${e.message}")
}
}
#include <iostream>
#include <curl/curl.h>
#include <string>
int main() {
// Initialize libcurl
CURL* curl = curl_easy_init();
if (!curl) {
std::cerr << "Error initializing libcurl." << std::endl;
return 1;
}
// Set API URL and API key
const char* url = "https://api.canvasflare.com/render?api_key=YOUR_API_KEY";
// Create a JSON string for the POST data
std::string jsonPayload = R"({
"html": "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><title>Advanced Example</title></head><body><div class=\"container\"><h1>Generating Part of Image Example</h1><p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p><p class=\"highlighted\">This paragraph has a special class called \"highlighted\".</p></div></body></html>",
"css": "body { background-color: #f0f0f0; font-family: Arial, sans-serif; text-align: center; } .container { padding: 20px; background-color: #ffffff; border: 1px solid #cccccc; border-radius: 5px; margin: 20px; } h1 { color: #333333; } p { color: #666666; } .highlighted { background-color: yellow; }",
"selector": ".highlighted"
})";
// Perform the POST request
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonPayload.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonPayload.size());
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
// Handle the response, e.g., download or display the image
std::cout << "Image URL: " << jsonPayload << std::endl;
} else {
std::cerr << "Error creating image: " << curl_easy_strerror(res) << std::endl;
}
// Clean up
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
return 0;
}
#!/bin/bash
api_key="YOUR_API_KEY"
url="https://api.canvasflare.com/render?api_key=$api_key"
html=$(cat <<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Example</title>
</head>
<body>
<div class="container">
<h1>Generating Part of Image Example</h1>
<p>This is a more complex example that demonstrates the usage of the <code>selector</code> parameter.</p>
<p class="highlighted">This paragraph has a special class called "highlighted".</p>
</div>
</body>
</html>
HTML
)
css=$(cat <<CSS
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
}
.container {
padding: 20px;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 5px;
margin: 20px;
}
h1 {
color: #333333;
}
p {
color: #666666;
}
.highlighted {
background-color: yellow;
}
CSS
)
selector=".highlighted"
# Create JSON payload
json_payload=$(jq -n \
--arg html "$html" \
--arg css "$css" \
--arg selector "$selector" \
'{html: $html, css: $css, selector: $selector}')
response=$(curl -X POST "$url" \
-H "Content-Type: application/json" \
--data "$json_payload")
if [[ $response =~ ^https://.* ]]; then
echo "Image URL: $response"
else
echo "Error creating image: $response"
fi