ScreenshotNeo

BlogHow-to

GrabzIt HTML to Image API: Convert HTML to PNG

Convert an HTML snippet or webpage to PNG with GrabzIt using its REST API, cURL, Python, or Node.js, with guidance on credentials and common errors.

By the ScreenshotNeo team4 October 20269 min read

GrabzIt can convert either an HTML snippet or a webpage URL into an image, including PNG. For a custom HTML snippet, send a URL-encoded HTTP POST to GrabzIt’s conversion endpoint with your application key, the output format, and the HTML. Keep the application key on your server: GrabzIt’s REST documentation warns that putting it in client-side code exposes the key. GrabzIt describes HTML and webpage inputs, and its REST documentation specifies POST for HTML conversion.

This guide uses the REST API so the request and encoding are visible. GrabzIt also provides native libraries, including Node.js and PHP. PNG is a supported format; GrabzIt positions PNG for image quality and JPG for smaller file size. The documentation cited here does not establish a speed or file-size benchmark, so choose based on the output you need.

1. Get credentials and choose an integration

Obtain your GrabzIt application key and secret through its account workflow before making API requests. The REST examples below use the application key as the key form field. Never substitute a real key into a browser-exposed script, public repository, or page source.

Approach Use it when Important detail
REST API You want a direct HTTP request or are using a language without a suitable library. HTML conversion is a URL-encoded HTTP POST; the capture is returned in the HTTP response.
GrabzIt language library You prefer a vendor method over constructing requests yourself. GrabzIt documents html_to_image(html, options) for Node.js and HTMLToImage for PHP. Confirm the installed library’s current usage and options in its official documentation.

2. Convert an HTML snippet to PNG with REST

The request contains three essential values: key, format, and html. Encode all values as URL-encoded form data and use application/x-www-form-urlencoded. A form encoder matters because HTML contains characters such as ampersands, plus signs, and quotes that must not be interpreted as form delimiters.

cURL

curl --fail-with-body \
  --request POST "https://api.grabz.it/services/convert" \
  --header "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "key=YOUR_APPLICATION_KEY" \
  --data-urlencode "format=png" \
  --data-urlencode 'html=<!doctype html><html><head><meta charset="utf-8"><style>body{font:16px sans-serif;padding:32px;color:#18212f}</style></head><body><h1>Hello from HTML</h1><p>This page becomes a PNG.</p></body></html>' \
  --output capture.png

The endpoint and field pattern above follow the REST documentation. If you receive an API error rather than image bytes, inspect the HTTP status and response body instead of treating the response as a PNG.

Python

import os
import requests

endpoint = "https://api.grabz.it/services/convert"
html = """<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <style>body { font: 16px sans-serif; padding: 32px; }</style>
  </head>
  <body><h1>Hello from HTML</h1></body>
</html>"""

response = requests.post(
    endpoint,
    data={
        "key": os.environ["GRABZIT_APPLICATION_KEY"],
        "format": "png",
        "html": html,
    },
    timeout=90,
)
response.raise_for_status()

content_type = response.headers.get("Content-Type", "")
if "image/" not in content_type:
    raise RuntimeError(
        f"Expected image response, got {content_type}: {response.text[:500]}"
    )

with open("capture.png", "wb") as image_file:
    image_file.write(response.content)

Install the dependency with python -m pip install requests. The dictionary passed as data is encoded by Requests as form data. Set GRABZIT_APPLICATION_KEY in the server process environment; do not hard-code the credential into a distributed client.

Node.js

const endpoint = "https://api.grabz.it/services/convert";
const html = `<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <style>body { font: 16px sans-serif; padding: 32px; }</style>
  </head>
  <body><h1>Hello from HTML</h1></body>
</html>`;

async function main() {
  if (!process.env.GRABZIT_APPLICATION_KEY) {
    throw new Error("Set GRABZIT_APPLICATION_KEY in the environment");
  }

  const form = new URLSearchParams({
    key: process.env.GRABZIT_APPLICATION_KEY,
    format: "png",
    html,
  });

  const response = await fetch(endpoint, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: form,
  });

  if (!response.ok) {
    const detail = await response.text();
    throw new Error(`GrabzIt returned HTTP ${response.status}: ${detail}`);
  }

  const contentType = response.headers.get("content-type") || "";
  if (!contentType.startsWith("image/")) {
    throw new Error(`Expected an image response, received ${contentType}`);
  }

  const bytes = Buffer.from(await response.arrayBuffer());
  await import("node:fs/promises").then((fs) => fs.writeFile("capture.png", bytes));
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

This example uses the built-in fetch available in current Node.js releases. URLSearchParams performs form encoding. Keep the key in a server environment variable, and use the GrabzIt Node.js library instead if you want its documented html_to_image(html, options) interface.

3. Convert a webpage URL instead of an HTML string

GrabzIt supports webpage URLs as well as HTML snippets. The REST documentation’s stated requirement to POST applies to HTML conversion. For a URL-based capture, consult the current REST parameter documentation for that input mode and its exact request fields; do not assume the HTML field is interchangeable with a URL field.

For a URL you control, check that it is reachable by the conversion service and that the page does not depend on a private network, local browser state, or credentials unavailable to the service. If your goal is to convert a string of markup, use the HTML POST examples above rather than first publishing the HTML at a public URL.

4. Choose PNG or another format

The documented formats include PNG, JPG, BMP, WEBP, TIFF, and SVG. Set format to the requested output format. GrabzIt recommends PNG when image quality is the priority and JPG when a smaller file is the priority. Select a format based on downstream requirements: PNG is often appropriate when you need a lossless raster output or sharp text and interface edges; JPG is useful when lossy compression is acceptable. These are practical format considerations, not a GrabzIt performance guarantee.

Format Consider it when
PNG You need the requested PNG output or prefer the quality-oriented option GrabzIt recommends.
JPG Reducing file size matters and lossy image compression is acceptable; GrabzIt describes it as its smaller-file choice.
WEBP, BMP, TIFF, SVG Your consumer supports the format and you have a specific compatibility or workflow reason to use it. Verify the service’s current behavior and options for the chosen format.

5. Protect credentials and handle the response safely

  • Keep the application key server-side. GrabzIt’s REST page explicitly warns against using this API on the client side because doing so exposes the application key. The page recommends its JavaScript API for client-side use and says IP access can be restricted.
  • Use HTTPS. Send credentials only to the documented HTTPS endpoint.
  • Do not log secrets. Redact keys from request logs, exception traces, and support bundles.
  • Check status and content type. Save the body as a PNG only after confirming the request succeeded and returned image content. Error responses may be text or another non-image body.
  • Use Bearer authorization only as documented. The REST documentation describes an Authorization Bearer option for the application key. Follow its current syntax if choosing that authentication method; do not send the same secret to an unrelated host.

6. Troubleshooting

Symptom Likely cause What to check
Request rejected or API error returned Missing or invalid credentials, incorrect endpoint, or malformed fields. Confirm the application key, endpoint, and required key, format, and html values against the current REST docs. Inspect the response body.
HTML appears truncated or fields seem mixed together Form values were concatenated manually and special characters were not encoded. Use --data-urlencode in cURL, a form dictionary in Python Requests, or URLSearchParams in Node.js.
Saved file is not a valid PNG An error response was written to the image path, or the response was not checked. Check HTTP status and Content-Type; read the response body as text when it is not an image.
Application key is visible in browser source The REST request was made directly from client-side JavaScript. Move the call to a server endpoint, or follow GrabzIt’s documented JavaScript API approach for client-side usage. Consider the documented IP access restriction.
Webpage conversion cannot reach the page The URL may only be accessible from your network or require session state. Verify the URL is reachable to the conversion service and that required authentication or state is supported by the selected integration.
Output format is unexpected The requested format value may be absent, misspelled, or unsupported by the particular flow. Set format=png explicitly and confirm the response content type before naming the output file.

7. Performance, reliability, and cost considerations

The cited GrabzIt materials establish the request shape and supported formats, but do not establish conversion latency, throughput, uptime commitments, current plan quotas, or pricing. Check GrabzIt’s current service and account documentation for those operational and commercial details before setting production limits.

  • Keep HTML focused. Send only the markup and assets needed for the image. Large documents and external assets can add work, though no quantitative impact is claimed here.
  • Use bounded timeouts. Set a request timeout appropriate to your application and handle timeout failures explicitly; do not assume every capture completes immediately.
  • Retry selectively. Retry transient network failures with a limit and backoff. Do not endlessly retry invalid credentials, malformed requests, or other deterministic errors.
  • Make output writes atomic where needed. Write to a temporary file and rename after validating the response if downstream jobs might otherwise consume a partial file.
  • Track outcomes. Record request status, duration, response type, and a correlation identifier where available, while excluding credentials and sensitive HTML.
  • Check current pricing and limits. No pricing or quota is asserted here because the research materials do not establish those figures.

8. Or skip the browser setup

If the actual goal is to capture a live webpage as an image, ScreenshotNeo is a website screenshot API and MCP server for developers. It accepts one GET request and can return PNG, JPEG, WebP, or PDF. For a webpage PNG, specify the target URL and PNG output option in the request. The example below follows the documented ScreenshotNeo request pattern; see the ScreenshotNeo API documentation for the output-format parameter and the full option list.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -d format=png \
  -o shot.png

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={
        "access_key": "YOUR_API_KEY",
        "url": "https://stripe.com",
        "format": "png",
    },
    timeout=90,
)
r.raise_for_status()
with open("shot.png", "wb") as f:
    f.write(r.content)

Node.js

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com',
  format: 'png',
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`ScreenshotNeo returned HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.png', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed; its MCP server lets AI agents take screenshots; and 1,000 screenshots a month are free with no card, with paid plans starting at $5 for 3,000. Sign up for free and get 1,000 screenshots a month with no card.

Frequently asked questions

Can GrabzIt convert HTML that has not been published as a webpage?

Yes. Its HTML-to-image overview describes converting an HTML snippet, and the REST flow accepts HTML in a POST body.

Does the REST API return a PNG file directly?

The REST documentation describes the capture as returned in the HTTP response. Check the status and content type before saving the response body as a PNG.

Can I call the REST endpoint from a browser?

GrabzIt warns that client-side REST use exposes the application key. Keep the key on the server or use the vendor’s documented JavaScript API for client-side use.

Is there a documented conversion speed advantage for PNG or JPG?

The reviewed documentation gives a quality versus file-size recommendation, not a speed comparison or benchmark.