How to Save PNG Images with Wkhtmltoimage C Bindings in Pascal
Configure wkhtmltoimage’s C API from Pascal, save PNG files or buffers, handle transparency, and diagnose version-specific failures.

To save a PNG with wkhtmltoimage from Free Pascal or Lazarus, configure the image converter’s global setting fmt as png, set in to the page URL or input path, and choose one output route: set out to a filename, set it to - for standard output, or leave it empty and retrieve the bytes with wkhtmltoimage_get_output. The documented lifecycle is initialization, global settings creation, settings configuration, converter creation, conversion, output retrieval if needed, converter destruction, and library deinitialization.
The format is controlled by fmt; a .png filename alone does not request PNG encoding. The official settings reference lists PNG, JPEG, BMP and SVG output, and documents transparent = true for PNG or SVG. The C binding is described by the project as a high-level, stable pure C interface in image.h. See the libwkhtmltox documentation and its settings reference.
1. Choose a PNG output route
| Route | Setting | When to use it | Important detail |
|---|---|---|---|
| File | out = /path/result.png |
Batch jobs and simple command-line style workflows | The library writes the file; check the conversion result and filesystem permissions. |
| Standard output | out = - |
Piping image bytes to another process | Keep diagnostics separate from binary output. |
| Memory buffer | out = (empty) |
HTTP responses, databases, image processing, or custom storage | Write exactly the returned byte length; do not treat the bytes as a null-terminated string. |
Use a file route when you do not need to inspect or transform the image in Pascal. Use the buffer route when the application already owns the destination stream. A transparent result still needs a format that supports transparency: configure PNG (or SVG) and set transparent to true.
2. The documented converter lifecycle
- Call the global initialization function for wkhtmltoimage.
- Create a global settings object.
- Set
in,out,fmt, and any rendering options. - Create a converter from the settings object. The converter consumes those settings.
- Optionally attach progress, warning, error, or phase callbacks.
- Call the conversion function and inspect its Boolean result.
- For memory output, call
wkhtmltoimage_get_outputand copy the returned bytes before destroying the converter. - Destroy the converter, then deinitialize the library after all conversions are complete.
The upstream example follows this order. Its sample uses JPEG, so use the settings reference and set fmt to png for this task. Do not deinitialize the library while a converter is still alive.

3. Pascal binding considerations
There is no official Pascal binding in the reviewed sources. Your binding must mirror the native C declarations in image.h, including calling convention, pointer types, integer widths, and callback signatures. On Windows, a calling-convention mismatch can corrupt the stack; on 64-bit systems, using a 32-bit integer for a pointer can truncate addresses.
Keep C strings as null-terminated strings and pass them as pointers. Keep image data as binary memory. A typical binding represents opaque C handles as pointers, for example:
type
TWkGlobalSettings = Pointer;
TWkConverter = Pointer;
function wkhtmltoimage_init(useGraphics: Integer): Integer; cdecl; external 'wkhtmltox';
function wkhtmltoimage_deinit: Integer; cdecl; external 'wkhtmltox';
function wkhtmltoimage_create_global_settings: TWkGlobalSettings; cdecl; external 'wkhtmltox';
function wkhtmltoimage_set_global_setting(settings: TWkGlobalSettings; name, value: PAnsiChar): Integer; cdecl; external 'wkhtmltox';
function wkhtmltoimage_create_converter(settings: TWkGlobalSettings): TWkConverter; cdecl; external 'wkhtmltox';
function wkhtmltoimage_convert(converter: TWkConverter): Integer; cdecl; external 'wkhtmltox';
function wkhtmltoimage_get_output(converter: TWkConverter; outData: PPointer): NativeUInt; cdecl; external 'wkhtmltox';
procedure wkhtmltoimage_destroy_converter(converter: TWkConverter); cdecl; external 'wkhtmltox';
This is a binding shape, not a claim that every package exports exactly these Pascal declarations. Compare each declaration with the header shipped by your build. Some packages use different library names, callback declarations, or integer aliases. If your binding already supplies these functions, use its types rather than duplicating declarations.
4. Save a PNG directly to a path
The direct-file route lets wkhtmltoimage open and write the destination. The following program shows the sequence and uses a transparent PNG. Adjust the external declarations to your installed header and library package.
program PageToPngFile;
{$mode objfpc}{$H+}
uses
SysUtils;
// Import declarations from your verified wkhtmltox Pascal binding here.
// The names below illustrate the documented C API lifecycle.
var
settings: TWkGlobalSettings;
converter: TWkConverter;
ok: Integer;
begin
if wkhtmltoimage_init(0) = 0 then
raise Exception.Create('wkhtmltoimage initialization failed');
try
settings := wkhtmltoimage_create_global_settings;
if settings = nil then
raise Exception.Create('Could not create global settings');
if wkhtmltoimage_set_global_setting(settings, 'in',
'https://example.com') = 0 then
raise Exception.Create('Could not set input');
if wkhtmltoimage_set_global_setting(settings, 'out',
'page.png') = 0 then
raise Exception.Create('Could not set output path');
if wkhtmltoimage_set_global_setting(settings, 'fmt', 'png') = 0 then
raise Exception.Create('Could not set PNG format');
if wkhtmltoimage_set_global_setting(settings, 'transparent', 'true') = 0 then
raise Exception.Create('Could not set transparency');
converter := wkhtmltoimage_create_converter(settings);
if converter = nil then
raise Exception.Create('Could not create converter');
try
ok := wkhtmltoimage_convert(converter);
if ok = 0 then
raise Exception.Create('Conversion failed');
finally
wkhtmltoimage_destroy_converter(converter);
end;
finally
wkhtmltoimage_deinit;
end;
end.
Use an absolute output path while diagnosing failures. Confirm that the parent directory exists and that the account running the process can create or replace the file. A successful conversion result means the converter completed; still verify the file exists and has a nonzero size.
5. Retrieve PNG bytes from memory
For an in-memory result, leave out empty. The output function returns a pointer and a length. Copy those bytes before destroying the converter. The length is authoritative and may include zero bytes, so never call string functions such as StrPas on the image.
var
settings: TWkGlobalSettings;
converter: TWkConverter;
data: Pointer;
dataLen: NativeUInt;
stream: TFileStream;
begin
if wkhtmltoimage_init(0) = 0 then
raise Exception.Create('wkhtmltoimage initialization failed');
try
settings := wkhtmltoimage_create_global_settings;
wkhtmltoimage_set_global_setting(settings, 'in', 'https://example.com');
wkhtmltoimage_set_global_setting(settings, 'out', '');
wkhtmltoimage_set_global_setting(settings, 'fmt', 'png');
converter := wkhtmltoimage_create_converter(settings);
if converter = nil then
raise Exception.Create('Could not create converter');
try
if wkhtmltoimage_convert(converter) = 0 then
raise Exception.Create('Conversion failed');
data := nil;
dataLen := wkhtmltoimage_get_output(converter, @data);
if (data = nil) or (dataLen = 0) then
raise Exception.Create('Converter returned no image bytes');
stream := TFileStream.Create('page.png', fmCreate);
try
stream.WriteBuffer(data^, dataLen);
finally
stream.Free;
end;
finally
wkhtmltoimage_destroy_converter(converter);
end;
finally
wkhtmltoimage_deinit;
end;
end.
Depending on your binding, the output length may be declared as a platform-sized unsigned type. Use the exact type from the C header. If your wrapper copies output into managed memory, follow that wrapper’s ownership rules; otherwise, assume the pointer belongs to the converter and becomes invalid after destruction.
6. Rendering settings that affect PNG output
Input and destination
in accepts a URL or local input path. URL rendering depends on network access, redirects, TLS support, and the page’s own scripts. out accepts a file path, -, or an empty value as described above.
Format and transparency
Set fmt explicitly to png. Set transparent to true when the page background should be transparent. The setting is documented for PNG and SVG output; it does not turn a JPEG into a transparent image.
Callbacks
The C API supports callbacks for progress, phase changes, warnings, and errors. Attach them when a conversion can fail remotely or take a long time. Log the callback text, input URL, output route, library version, and process architecture. Keep callback functions alive for the entire conversion and match the header’s calling convention.
Page behavior
JavaScript-heavy pages may need a wait setting or page-specific configuration exposed by your binding. Keep waits bounded. A page that never reaches a stable state can make a batch worker appear stuck, so enforce an application-level timeout and terminate the worker cleanly if the native library does not return.
7. Diagnosing “Could not save image”
A 2017 Stack Overflow report from an FPC/Lazarus user described JPEG and SVG working while PNG produced the callback error “Could not save image.” The answer suggested that version 0.12.4 had a problem and that 0.12.3 worked. This is an old, anecdotal, version-specific report. It does not establish a current defect, a universal workaround, or a compatibility matrix.
Record enough detail to make a failure reproducible:
- Exact wkhtmltoimage and wkhtmltox package version, including whether it is a patched or distribution build.
- Operating system, CPU architecture, Free Pascal/Lazarus version, and the binding revision.
- Input URL or a local test page.
- Every relevant setting, especially
fmt,out, andtransparent. - Callback messages, conversion return value, HTTP error code if available, and destination path.
- Whether direct-file output and memory output fail in the same way.
Common errors and fixes
| Symptom | Likely cause | Action |
|---|---|---|
| Output has a different format | fmt was omitted or set incorrectly. |
Set fmt to png; do not rely on the filename extension. |
| Permission or open-file error | Parent directory is missing, read-only, or inaccessible to the service account. | Use an absolute path, create the directory, and test permissions with the same account. |
| Zero-length memory result | Conversion failed, output was not empty, or the pointer/length declaration is wrong. | Check the conversion result, set out to an empty string, and verify the binding against image.h. |
| Access violation after conversion | Bytes were read after destroying the converter, or a pointer-sized value was truncated. | Copy the exact byte range before destruction and use native-sized pointer and length types. |
| PNG fails while another format works | Build-specific encoder or library regression is possible. | Reproduce with a minimal page, record the exact build, and compare a supported build; do not assume the historical 0.12.4 report applies to your version. |
| Transparent background is white | transparent was not enabled, or the page itself paints an opaque background. |
Set transparent to true and inspect the page CSS. |
| Page is blank or incomplete | Network, JavaScript, redirect, font, or timing issue. | Test the URL in the same environment, add a bounded wait, and inspect callbacks and HTTP errors. |
8. Reliability, performance, and cost
Native conversion cost depends on page size, scripts, fonts, images, network latency, and whether the page waits for asynchronous content. For repeatable batch work, reuse a worker process only if your binding and build are stable, and isolate crashes in a supervised worker. Limit concurrent converters according to available memory; full-page pages and large images can consume substantially more memory than their final PNG file size.
Use deterministic local fixtures when diagnosing changes. Cache inputs outside the converter when appropriate, but remember that a remote page can change between runs. Store the library version beside generated artifacts so a later comparison can distinguish page changes from renderer changes.
wkhtmltoimage itself does not provide a price-per-capture service. Your costs are the application host, network transfer, storage, and operational work needed to maintain the native dependency. A managed API can move browser setup and rendering operations out of your application.
9. Or skip the browser setup
ScreenshotNeo provides a one-request website screenshot API and an MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF. Before capture, it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status with X-Page-Verdict and X-Billed headers.

cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the ScreenshotNeo API documentation for the complete option list. It supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, usage data, and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work, which can simplify migration.
ScreenshotNeo includes an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.
10. Checklist before shipping
- Confirm your Pascal declarations against the exact
image.hshipped with the native library. - Verify the calling convention and pointer-sized integer types.
- Set
fmt = pngexplicitly. - Choose file, standard output, or empty-buffer output deliberately.
- For memory output, copy exactly the returned length before destroying the converter.
- Test transparent and opaque pages separately.
- Log version, settings, callbacks, and destination for failures.
- Exercise an inaccessible URL, a slow page, and a page with JavaScript before running large batches.
FAQ
Does a .png extension force PNG output?
No. Set the global fmt setting to png.
Can I use the returned buffer after destroying the converter?
Copy it first. The converter owns the returned memory in the documented workflow.
Is the old 0.12.4 PNG failure still present?
The report only documents one user’s 2017 experience. It is not evidence about current builds.
What does out = - mean?
It directs output to standard output. Keep logs off that stream when piping binary PNG data.
When should I choose an API instead of local wkhtmltoimage?
Choose a managed API when you want to avoid native browser setup, consent-banner cleanup, renderer maintenance, or infrastructure for retries and batch capture.


