Kotlin
Example of image generation using Kotlin.
The Canvasflare API allows the creation of images from specified HTML, CSS, and other parameters. This example demonstrates how to use this API in Kotlin to generate an image.
Rendering an Image
To render an image, send a POST request to https://api.canvasflare.com/render with the necessary parameters.
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 Kotlin
In Kotlin, you can use the OkHttpClient from the OkHttp library to send HTTP requests:
import java.net.HttpURLConnection
import java.net.URL
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStream
fun main() {
val url = URL("https://api.canvasflare.com/render?api_key=YOUR_API_KEY")
val connection = url.openConnection() as HttpURLConnection
try {
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
connection.doOutput = true
val jsonInputString = """
{
"html": "<div>This is something</div>",
"css": ".h1 { color: red }",
"device_scale": 2,
"viewport_width": 640,
"viewport_height": 480,
"ms_delay": 500
}
""".trimIndent()
connection.outputStream.use { os ->
val input = jsonInputString.toByteArray(charset("utf-8"))
os.write(input, 0, input.size)
}
val code = connection.responseCode
println("Response Code : $code")
BufferedReader(InputStreamReader(connection.inputStream, "utf-8")).use { br ->
val response = StringBuilder()
var responseLine: String?
while (br.readLine().also { responseLine = it } != null) {
response.append(responseLine!!.trim { it <= ' ' })
}
println(response.toString())
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection.disconnect()
}
}
Response
The API response will return a URL to the generated image that you can download or display.
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
For this code to work, you'll need to include the OkHttp library and org.json library in your Kotlin project. You can add these dependencies via your project's build system (like Gradle or Maven).