Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

KaTeX does not export PNG or JPG files directly. It renders TeX as HTML and/or MathML. To make an image, first render the equation with KaTeX and its CSS and fonts, then capture the rendered element or page with a browser-based screenshot or rasterization tool. Choose PNG for lossless, sharp text and possible transparency; choose JPG when a smaller photographic-style file with a solid background is acceptable.

The workflow below gives you a reproducible KaTeX render, explains the image-capture decisions that affect quality, and shows an automated option with ScreenshotNeo.

Understand the format boundary

The documented KaTeX APIs return markup, not an image file. In a browser, katex.render(tex, element, options) inserts rendered markup into a DOM element. On the server, katex.renderToString(tex, options) returns an HTML string. KaTeX can produce HTML, MathML, or both; the default output is htmlAndMathml.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The image step is separate. A screenshot or rasterizer must display the generated markup with KaTeX’s stylesheet and font files, then encode the pixels as PNG or JPG. The KaTeX command-line interface likewise prepares HTML; do not treat its HTML output as a PNG/JPG exporter.

Prepare a correctly styled KaTeX render

Prerequisites

  • Node.js and npm for the server-side example.
  • The katex package, installed with npm install katex.
  • KaTeX’s CSS and font files available to the page. Without them, glyph metrics, fractions, radicals, and spacing can be wrong.
  • An HTML5 doctype when rendering in a browser.

Generate a standalone HTML file with Node.js

This script renders one display equation and writes equation.html. Run it from the directory containing node_modules; the relative stylesheet path then resolves to the installed package.

const fs = require('node:fs');
const katex = require('katex');

const tex = String.raw`frac{-b pm sqrt{b^2 - 4ac}}{2a}`;
const markup = katex.renderToString(tex, {
  displayMode: true,
  output: 'htmlAndMathml',
  throwOnError: true
});

const html = `<!doctype html>
<html lang='en'>
<head>
  <meta charset='utf-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <link rel='stylesheet' href='node_modules/katex/dist/katex.min.css'>
  <style>
    body { margin: 0; padding: 32px; background: white; }
    #equation { display: inline-block; }
  </style>
</head>
<body>
  <div id='equation'>${markup}</div>
</body>
</html>`;

fs.writeFileSync('equation.html', html);
console.log('Wrote equation.html');

Open the generated file in a browser after confirming that the CSS and font files load. Keep the page background and padding intentional: those pixels become part of the eventual image unless your capture step crops to the equation element.

Render directly in a browser

If your application already bundles KaTeX, render into a known element and capture that element after the call completes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const tex = String.raw`int_0^infty e^{-x^2},dx = frac{sqrt{pi}}{2}`;
katex.render(tex, document.querySelector('#equation'), {
  displayMode: true,
  output: 'htmlAndMathml',
  throwOnError: true
});

Include the KaTeX stylesheet in the same page and make sure its fonts are reachable from the browser. If you use a server-side renderToString result, the receiving page still needs those CSS and font resources.

Turn the rendered markup into PNG or JPG

Choose the capture target

  • Element capture: captures only the equation and is easiest to place in documents or slides. Use a deliberate margin so accents and tall delimiters are not clipped.
  • Page capture: captures the entire HTML page, which is useful when the equation is part of a larger annotated figure.
  • Fixed viewport: gives repeatable dimensions for a pipeline. Set the viewport before rendering and keep the device scale consistent.
  • Full-page capture: is useful for long content, but it can include unnecessary whitespace around a single equation.

Pick PNG or JPG deliberately

Requirement PNG JPG
Equation edges Lossless; preserves thin strokes and small glyphs Lossy; compression can create halos around text
Transparency Can retain an alpha channel when the capture tool supports it Requires a solid background
Best use Documentation, diagrams, scientific notation, repeated editing Cases where a smaller file matters and a solid background is acceptable
Color control Preserves exact flat colors May alter edges and subtle color transitions through compression

Capture at the final display size or at a higher device scale and downsample once. Repeated resizing softens fraction bars and superscripts. For a transparent result, remove the page background before capture; do not expect JPG to preserve transparency.

Use a browser or rasterizer you have verified

  1. Render the equation and wait until KaTeX CSS and fonts have loaded.
  2. Inspect the result at 100% zoom. Fix TeX or styling problems before making pixels.
  3. Choose an element or page capture and set the viewport, scale, padding, and background explicitly.
  4. Export as PNG or JPG using the capture tool’s current format setting.
  5. Open the resulting file independently and check that radicals, accents, matrices, and baseline alignment are intact.

Capture-tool controls vary, so verify the current tool’s behavior for cropping, device scale, transparent backgrounds, font loading, and JPEG quality rather than assuming that two tools produce identical pixels.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. Give it a public equation page and it returns a screenshot in PNG, JPEG, WebP, or PDF formats. Its cleanup step accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For API parameters, see the ScreenshotNeo documentation. The following request saves the returned image as WebP; select PNG or JPEG in the API’s documented format option when you need those formats.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://screenshotneo.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://screenshotneo.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://screenshotneo.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await Bun.write('shot.webp', bytes);

Replace the example URL with the public URL that serves your generated KaTeX HTML. ScreenshotNeo can capture a full page or one CSS-selected element, load lazy images, emulate dark mode, use 12 device presets or a custom viewport, apply retina scale, inject custom CSS or JavaScript, click an element, hide selectors, and wait for a selector, delay, or network idle. You can also block ads, trackers, requests, or resource types; provide headers, cookies, a user agent, or an Authorization header; set timezone and geolocation; request a transparent background; resize the output; cache with a chosen TTL; create signed links for public <img> tags; submit asynchronous jobs with signed webhooks; capture up to 100 URLs per bulk call; and read usage through the usage API. An OpenAPI specification and commonly used parameter names make migration from another screenshot API easier. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Every plan includes every feature. The Free plan provides 1,000 shots per month without a card; paid plans are Starter $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing provides two months free. Create a free ScreenshotNeo account to start without a card.

Handle errors before capturing

Symptom Likely cause Fix
ParseError from KaTeX Invalid or unsupported TeX Correct the command or delimiters, then render again with throwOnError: true while developing.
Equation appears as unstyled text KaTeX CSS or fonts did not load Check the stylesheet path, font requests, and browser network errors. Capture only after resources finish loading.
Layout is inconsistent between machines Different fonts, viewport, zoom, or device scale Bundle or consistently serve KaTeX fonts and set an explicit viewport and scale.
Image contains an error-looking TeX string throwOnError: false rendered invalid input as text with hover information Validate the source and use throwOnError: true for an all-or-nothing export.
Top or bottom of a symbol is cut off Crop bounds are tighter than the element’s ink Add padding, capture the parent element, or use a slightly larger crop rectangle.
Capture is blank The page failed to load, timed out, or was blocked Inspect the page directly, wait for the equation selector, and check the capture response verdict. With ScreenshotNeo, failed loads and blank pages are reported and not billed.
Consent dialog or chat bubble covers the equation Page UI appeared before capture Dismiss or hide those selectors in your capture setup. ScreenshotNeo accepts consent banners and removes known popups and chat widgets before the shot.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Production and batch considerations

Make output deterministic

Store the TeX source, KaTeX version, CSS, font files, viewport, scale, background, and output format alongside each generated image. Changing any of these can change line breaks or glyph metrics. Use a stable page template rather than copying equations into arbitrary documents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate rendering from capture

First test the HTML output in a browser. Only then troubleshoot the image service. This isolates TeX parse failures from font-loading, network, cropping, and encoding problems. For dynamic pages, wait for the equation container or network idle rather than relying on a fixed delay alone.

Automate responsibly

For many equations, generate one page per expression or a controlled grid, capture at a fixed viewport, and record the source-to-image mapping. ScreenshotNeo supports asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, caching with a chosen TTL, and a usage API, which can reduce repeated work in a publishing pipeline.

FAQ

Can I use KaTeX’s CLI alone to create a PNG?

No. The CLI produces HTML. You still need a separate, verified screenshot or rasterization step to create image pixels.

Which output mode should I choose?

Use htmlAndMathml when you want the default combined output and accessibility-oriented MathML alongside the visual HTML. Use html or mathml only when your page architecture specifically requires one representation.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does the same TeX look different after conversion?

The pixels depend on the KaTeX version, stylesheet, loaded fonts, viewport, device scale, padding, and encoder settings—not just the TeX string. Keep those inputs fixed when reproducibility matters.

Frequently Asked Questions

Can I use KaTeX’s CLI alone to create a PNG?

No. The CLI produces HTML; a separate, verified screenshot or rasterization step is required to create image pixels.

Which output mode should I choose?

Use htmlAndMathml for the default combined output. Choose html or mathml only when your page architecture specifically requires one representation.

Why does the same TeX look different after conversion?

The final pixels also depend on the KaTeX version, CSS, fonts, viewport, device scale, padding, and image encoder settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.