How to Capture a Webpage as PDF with GrabzIt
Convert a webpage URL to PDF with GrabzIt using its REST API or client libraries. Choose PDF layout settings, handle errors, and save the result safely.
To capture a webpage as a PDF with GrabzIt, send its URL to the capture API with format=pdf, then save the PDF bytes returned in the HTTP response. With a GrabzIt client library, call its URL-to-PDF method and follow that library’s save or retrieval flow. Use a public URL for a live webpage; choose the HTML or HTML-file route when you already have the page source. The official docs describe all three input routes and support PDF layout options including page size, orientation, and Screen or Print CSS media.
This guide uses the REST API for runnable examples. Keep the application key on a server: GrabzIt explicitly warns that putting it in client-side code exposes it. See the GrabzIt API overview and REST API reference for the current integration details.
1. Get your GrabzIt credentials and choose an input
Create or access a GrabzIt account and obtain its application key and secret. The REST request below uses the application key. Keep credentials in environment variables or a secret manager, and restrict account access by domain or IP where appropriate.
Choose the input method that matches what you have:
- URL to PDF: the page is available at a URL, which is the usual choice for capturing a webpage.
- HTML to PDF: your application already has the HTML string. The REST interface accepts HTML through a POST request.
- HTML file to PDF: use the file-to-PDF method in a language client library when the source is an HTML file. The exact method names and save workflow vary by library.
For URL capture, GrabzIt’s REST endpoint is https://api.grabz.it/convert. Set key, url, and format=pdf. The API returns the capture in the HTTP response. The service also documents a Bearer token alternative for the application key.
2. Capture a URL as PDF with cURL
This example writes the response body to page.pdf. Replace the URL and set GRABZIT_KEY before running it. The REST API requires parameter values to be URL encoded; --data-urlencode handles that for the URL.
export GRABZIT_KEY='YOUR_APPLICATION_KEY'
curl --fail --silent --show-error -G 'https://api.grabz.it/convert' \
--data-urlencode "key=$GRABZIT_KEY" \
--data-urlencode 'format=pdf' \
--data-urlencode 'url=https://example.com/' \
--output page.pdf
Use --fail so HTTP errors cause a nonzero exit status. Also check the downloaded content before treating it as a PDF: the API may report an application error as JSON. The reference recommends checking the response content type and says an application/json response indicates an error.
3. Capture the same URL with Python
Install the HTTP client with python -m pip install requests. The code streams the response to disk, checks for HTTP failure, and rejects JSON error responses rather than saving them as a PDF.
import os
from pathlib import Path
import requests
api_key = os.environ["GRABZIT_KEY"]
response = requests.get(
"https://api.grabz.it/convert",
params={
"key": api_key,
"format": "pdf",
"url": "https://example.com/",
},
timeout=120,
)
response.raise_for_status()
content_type = response.headers.get("Content-Type", "").lower()
if "application/json" in content_type:
raise RuntimeError(f"GrabzIt returned an API error: {response.text}")
Path("page.pdf").write_bytes(response.content)
if not response.content.startswith(b"%PDF-"):
Path("page.pdf").unlink(missing_ok=True)
raise RuntimeError("The response did not look like a PDF")
Set GRABZIT_KEY in your shell before running the script. The content-type and file-signature checks help catch error payloads and unexpected responses. They do not prove that the rendered page is complete or visually correct, so open the PDF as part of your application’s acceptance checks.
4. Capture the same URL with Node.js
This example uses the built-in fetch available in current Node.js releases and writes the returned bytes to page.pdf.
import { writeFile } from 'node:fs/promises';
const key = process.env.GRABZIT_KEY;
if (!key) throw new Error('Set GRABZIT_KEY first');
const url = new URL('https://api.grabz.it/convert');
url.search = new URLSearchParams({
key,
format: 'pdf',
url: 'https://example.com/',
});
const response = await fetch(url);
if (!response.ok) {
throw new Error(`GrabzIt HTTP error: ${response.status} ${response.statusText}`);
}
const contentType = response.headers.get('content-type') ?? '';
if (contentType.toLowerCase().includes('application/json')) {
throw new Error(`GrabzIt API error: ${await response.text()}`);
}
const bytes = Buffer.from(await response.arrayBuffer());
if (bytes.subarray(0, 5).toString() !== '%PDF-') {
throw new Error('The response did not look like a PDF');
}
await writeFile('page.pdf', bytes);
Keep this code in a server process. Do not embed the application key in browser JavaScript or a publicly distributed app bundle.
5. Set the PDF layout and rendering options
Start with the defaults, then adjust one setting at a time while checking the output. Defaults are convenient, not a guarantee that a particular site will paginate as you expect.
| Option | Documented behavior | When to adjust it |
|---|---|---|
pagesize |
Defaults to A4. Options include A3, A4, A5, A6, B3, B4, B5, B6, Legal, and Letter. | Choose the paper size your readers or downstream workflow require. |
orientation |
Portrait by default; Portrait or Landscape. | Try Landscape for wide tables or dashboards; inspect text size and page breaks. |
media |
Defaults to Screen; options are Screen and Print. | Choose Print when the site has print-specific CSS; use Screen when its regular layout is the intended result. |
background |
Defaults to 1, which includes page backgrounds; 0 excludes them. |
Exclude backgrounds if they are unnecessary, or include them when color blocks and background styling carry meaning. |
includelinks |
Defaults to 1, including links. |
Disable links if the document should be a visual record without active links. |
includeoutline |
Defaults to 0; 1 includes PDF bookmarks or an outline. |
Enable for long documents whose headings should be navigable. |
title |
Optional PDF document title; empty by default. | Set a meaningful title for files users will organize or search. |
mtop, mright, mbottom, mleft |
REST options for page margins in millimeters; each defaults to 10. | Adjust when content is clipped, cramped, or needs room for annotations. |
width, height |
REST options for custom document dimensions in millimeters. Defaults follow the selected page size; minimum is 15. Height -1 means page height equals webpage height. |
Use custom dimensions only when a standard paper size is unsuitable. Full-page height may create an unusually long page rather than conventional pagination. |
coverurl |
Optional URL to use as a PDF cover page. | Use when a separate cover page is part of the output. |
waitfor |
Waits until a matching CSS selector is visible, for at most 25 seconds. | Wait for a specific page component when the page renders asynchronously. |
delay |
Wait in milliseconds before capture; default 0, maximum 30,000. | Add a modest delay when content needs time to settle and no reliable selector is available. |
bwidth, bheight |
Browser dimensions in pixels; defaults are 1366 by 1170, maximum 10,000 each. bwidth=-1 matches browser width to document width; bheight=-1 captures full page height. |
Set a viewport to reproduce a desktop or mobile layout. Full height and document page dimensions are different controls. |
country |
Capture location options are SG, UK, and US; default is the current fastest location. | Choose a location if the site varies by region. |
requestas |
0 standard website, 1 mobile version, 2 search-engine view. | Use only when that alternate version is the intended capture. |
noads, nonotify |
Both default to 0; set to 1 to hide adverts or commonly found cookie notifications respectively. | Use when those elements should not appear in the saved document. |
target, hide |
CSS selector options for capturing a single document element or hiding selected elements. | Use to focus on the main content or remove a known page element; verify selectors against the target site. |
click, hover, scroll |
Each names a CSS selector to interact with; only one of click, hover, or scroll may be specified. A delay may be needed after interaction. | Use for content revealed by a menu, hover state, or scroll position. |
jscode |
JavaScript to execute before capture. | Use only for a controlled page and keep injected code narrowly scoped. |
password, proxy, post |
REST parameters for document password protection, HTTP proxy details, or request POST parameters. | Consult the current REST reference for the required value format and use case before integrating. |
customid |
Optional identifier returned with a callback URL when one is specified. | Associate a capture with an internal job when using callback handling. |
For example, add these parameters to the cURL command to request US capture, landscape Letter pages, Print CSS, and a document title:
--data-urlencode 'country=US' \
--data-urlencode 'pagesize=Letter' \
--data-urlencode 'orientation=Landscape' \
--data-urlencode 'media=Print' \
--data-urlencode 'title=Saved webpage'
Place them before --output page.pdf in the earlier command. The official REST options reference lists the REST parameter names and values. The GrabzIt Node.js documentation describes library options using different names, such as pagesize, cssMediaType, and includeBackground; do not assume REST parameter spellings transfer unchanged to a client library.
6. Use GrabzIt’s language client when you need its lifecycle helpers
The REST examples are direct request/response captures. GrabzIt’s client libraries provide language-specific methods for URL, HTML string, and HTML-file input. In the documented Java workflow, after requesting a PDF capture, call Save or SaveTo to retrieve or save it. Do not assume every language uses those same method names or runs synchronously; follow the documentation for the library you install.
The API overview says you need an application key and secret when choosing an API access method. The REST examples above use the key and do not expose the secret in the URL. Keep both credentials private.
7. Save HTML as PDF instead of a live URL
If you already have HTML, the GrabzIt REST API accepts it as a POST body parameter. When converting HTML, the docs require HTTP POST and application/x-www-form-urlencoded values. Include address when your HTML refers to relative CSS, images, or other resources so those URLs have a base.
curl --fail --silent --show-error 'https://api.grabz.it/convert' \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode "key=$GRABZIT_KEY" \
--data-urlencode 'format=pdf' \
--data-urlencode 'html=<main><h1>Quarterly report</h1><p>Ready to print.</p></main>' \
--output report.pdf
For a local HTML file, use a supported client library’s file-to-PDF method, as documented in GrabzIt’s Node.js technical documentation. If the HTML includes private user data or remote resource URLs, consider what the remote capture service must fetch and process before sending it.
8. Troubleshoot common capture problems
| Symptom | Likely cause | What to check |
|---|---|---|
| The saved file contains JSON or is not a PDF | The API returned an error object or an unexpected response, but the client saved it as a document. | Check the HTTP status and Content-Type; the REST docs say an application/json response indicates an error. Log the error body safely and avoid saving it as a PDF. |
| “URL is missing” or another API error appears | A required parameter is missing or the request was encoded incorrectly. | For a URL capture send key, url, and format=pdf; URL-encode parameter values. Check the REST error JSON’s message and code. |
| The capture looks like the mobile site or wrong regional content | Viewport or location-dependent rendering differs from your expected context. | Review bwidth, bheight, requestas, and country. |
| Content is missing or appears before it finishes loading | The page renders data or images after initial navigation. | Try waitfor with a visible selector; otherwise use a measured delay within the documented 30-second maximum. Check whether the needed content is accessible at the submitted URL. |
| Background colors or images are absent | PDF background inclusion is disabled, or Print CSS removes those styles. | Set background=1 and compare media=Screen with media=Print. |
| Text is clipped or the PDF has awkward page breaks | Paper size, orientation, browser viewport, margins, and the site’s print styles interact. | Adjust one setting at a time; compare Portrait and Landscape, use the required paper size, and inspect the page in a PDF viewer. There is no universal setting for every site. |
| HTML’s images or styles fail to load | Relative URLs have no base when sending an HTML string. | Provide address as a base URL or use absolute resource URLs. |
| cURL exposes the key in shell history or logs | The credential was typed directly into a command or included in an application log. | Read it from an environment variable or secret manager, restrict access, and avoid logging full request URLs containing credentials. |
| A browser-side request fails or reveals the key | The REST API is being called from public client-side code. | Move the request to a server. GrabzIt explicitly cautions that client-side REST calls expose the application key. |
9. Performance, reliability, and cost considerations
Capture time depends on the target page, its resources, its scripts, and any wait you request. A longer delay can help with pages that render late, but it also makes every capture slower; use a selector-based wait where possible and validate that it becomes visible on the pages you support. The REST API documents a 30,000 ms maximum delay and a 25-second maximum wait for waitfor.
For reliability, handle HTTP failures, JSON error responses, network timeouts, and unexpected file content separately. Set a request timeout appropriate to your app, log a capture identifier rather than secrets, and retry only transient failures with a limit and backoff. Inspect sample PDFs from representative target pages because page structure, responsive design, and client-side rendering vary.
Pricing, account allowances, maximum output size, and capture success for a specific site are not established by the documentation cited here. Check GrabzIt’s current account and plan information before estimating production costs. Do not treat a successful HTTP response alone as proof that the document contains the intended content.
10. Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. One GET request can return a PNG, JPEG, WebP, or PDF, with capture options such as paper size, margins, landscape, and PDF page ranges. The ScreenshotNeo API documentation has the complete parameter reference.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
For a PDF response, set the documented output format parameter for PDF in your request. With ScreenshotNeo, cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up free and capture up to 1,000 screenshots a month with no card.
FAQ
Can GrabzIt convert HTML to PDF?
Yes. Its documentation describes URL-to-PDF, HTML-to-PDF, and HTML-file-to-PDF input paths. Use POST for HTML through the REST API, or use the corresponding method in a supported client library.
Should I choose Screen or Print media?
Choose the mode whose CSS layout matches the PDF you want. Compare both when the site defines separate print styles; inspect the output instead of assuming one mode is always better.
Can I use the GrabzIt REST API directly from a webpage?
GrabzIt advises against client-side REST use because it exposes the application key. Put the request in a server-side component.
Does a PDF capture always fit on standard pages?
No universal pagination result is guaranteed by the listed options. Page size, orientation, margins, viewport, media type, and the source page’s layout all affect the result; render and review the PDF for your use case.
How do I add PDF bookmarks?
Enable the PDF outline with includeoutline=1 in REST, or use the corresponding option in the client library. The REST default is disabled.


