# HTML to PDF: web pages and raw HTML to PDF in bulk (`examsens.ai/html-to-pdf`) Actor

Prints every URL or raw HTML document you list to PDF in headless Chrome, with page size, margins, landscape, backgrounds, scale, page numbers, and header and footer templates. Returns a download link for each PDF.

- **URL**: https://apify.com/examsens.ai/html-to-pdf.md
- **Developed by:** [Ed Rayyis](https://apify.com/examsens.ai) (community)
- **Categories:** Developer tools, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $9.00 / 1,000 pdf createds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## HTML to PDF: web pages and raw HTML to PDF in bulk

Give it a list of web page URLs, raw HTML documents, or both, and it prints each one to PDF in headless Chrome. Every PDF goes into the run's key value store, and the dataset gives you a direct download link with the page count and file size.

Use it for invoices, reports, receipts and certificates built from your own HTML templates, or to archive web pages as PDF.

### Options

- Page size: Letter (default), Legal, Tabloid, Ledger, A0 to A6, or a custom width and height such as `4in` by `6in` or `210mm` by `297mm`
- Sideways pages: turn each page on its side, wider than tall
- Margins for each side, in `in`, `cm`, `mm` or `px` (default `0.5in`)
- Print backgrounds: background colors and images (default on)
- Scale of the content, from 0.1 to 2
- Page numbers: a centered "Page 1 of 3" footer with one switch
- Header and footer templates in HTML. Chrome fills in these classes for you: `date`, `title`, `url`, `pageNumber` and `totalPages`, as in `<span class="pageNumber"></span>`. For raw HTML, `url` prints `about:blank`. Set a font size inside the template, such as `style="font-size:9px"`, and leave a margin big enough to hold it.
- Page ranges, such as `1-3` or `1,4`
- Use the page's own CSS page size when it sets one with an `@page` rule
- CSS media type: print (default) uses the page's print stylesheet; screen applies the page's screen styles instead
- Tagged PDF with structure tags for screen readers (default on)
- Bookmarks built from the page headings
- Browser language (default `en-US`), sent to sites that serve several languages
- Wait until the load event (default), DOM content loaded or network idle, plus an extra delay for late content (default 500 ms), and a page timeout (default 60 seconds)
- Viewport width while the page loads (default 1,280 pixels)

### Raw HTML documents

Each entry is an object with an `html` field and an optional `name`, used in the file name:

```json
[
  {"name": "invoice-1001", "html": "<!doctype html><html><head><title>Invoice 1001</title></head><body><h1>Invoice 1001</h1></body></html>"},
  {"name": "with-images", "baseUrl": "https://www.example.com/assets/", "html": "<img src='logo.png'>"}
]
```

Add `baseUrl` when the HTML loads images or stylesheets by relative path; the paths are resolved against it. A plain string in the list is treated as the HTML of one document.

### Output

Dataset: one item per URL or document with `pdfUrl` (download link), `pdfKey` (the file name in the key value store), `source`, `type` (`url` or `html`), `title`, `pages`, `bytes`, `pageFormat` and `landscape`. URLs also get `finalUrl` (after redirects) and `status`, the HTTP status of the page. Files are named by their position in your list and the source, such as `0001-example-com.pdf`.

An input that cannot be printed gets `ok: false` and an `error`, such as an unknown host, a page timeout, or an empty `html` field. One bad input never stops the run. A page that answers with an HTTP error such as 404 is still printed, and its `status` shows the code.

### Pricing

Pay per event: one event per PDF created. Inputs that fail are not charged. The run stops when it reaches the maximum charge you set.

### Scope and conduct

Only the URLs you supply are opened, one at a time, each in a fresh browser context with no cookies carried over. No proxies are used, and the actor does not log in anywhere or collect personal data. Print pages you are allowed to copy.

### Support

Questions and problems: the Issues tab on this page. Replies are written by an AI assistant on behalf of the developer and reviewed by the developer.

# Actor input Schema

## `urls` (type: `array`):

Web pages to turn into PDFs.

## `htmlDocuments` (type: `array`):

HTML you supply yourself, such as invoices or reports. Each entry is an object: {"name": "invoice-1001", "html": "<h1>Invoice</h1>"}. Add "baseUrl" when the HTML links images or stylesheets with relative paths.

## `pageFormat` (type: `string`):

Paper size. Ignored when page width and height are both set.

## `pageWidth` (type: `string`):

A custom width with a unit, such as 8.5in, 210mm or 800px. Needs a custom height too.

## `pageHeight` (type: `string`):

A custom height with a unit, such as 11in, 297mm or 1200px. Needs a custom width too.

## `landscape` (type: `boolean`):

Turn each page on its side, wider than tall.

## `marginTop` (type: `string`):

With a unit: in, cm, mm or px.

## `marginRight` (type: `string`):

With a unit: in, cm, mm or px.

## `marginBottom` (type: `string`):

With a unit: in, cm, mm or px.

## `marginLeft` (type: `string`):

With a unit: in, cm, mm or px.

## `printBackground` (type: `boolean`):

Include background colors and images.

## `scale` (type: `number`):

Zoom of the page content, from 0.1 to 2.

## `pageNumbers` (type: `boolean`):

Add a centered "Page 1 of 3" footer. Ignored when you write your own footer template.

## `headerTemplate` (type: `string`):

HTML printed at the top of every page. These classes are filled in for you: date, title, url, pageNumber, totalPages, as in <span class="pageNumber"></span>. Set a font size in the template, such as style="font-size:9px", and leave a top margin big enough to hold it.

## `footerTemplate` (type: `string`):

HTML printed at the bottom of every page, with the same classes as the header. Set a font size and leave a bottom margin big enough to hold it.

## `pageRanges` (type: `string`):

Print only some pages, such as 1-3 or 1,4. Leave empty for all pages.

## `preferCssPageSize` (type: `boolean`):

When the page sets its size with a CSS @page rule, use that size.

## `mediaType` (type: `string`):

Print uses the page's print stylesheet. Screen makes the PDF look like the page on screen.

## `taggedPdf` (type: `boolean`):

Add structure tags that help screen readers.

## `outline` (type: `boolean`):

Add a document outline (bookmarks) built from the page headings.

## `waitUntil` (type: `string`):

When the page counts as loaded: the load event, DOMContentLoaded, or no network traffic for 500 ms.

## `delayMs` (type: `integer`):

Wait this long after loading before printing, for scripts and late content.

## `timeoutSecs` (type: `integer`):

Give up on a page that does not load within this time.

## `viewportWidth` (type: `integer`):

Browser window width while the page loads. Affects pages whose layout depends on window width.

## `locale` (type: `string`):

The language the browser asks for, such as en-US, de-DE or ja-JP. Sites that serve several languages pick theirs from this.

## Actor input object example

```json
{
  "urls": [
    {
      "url": "https://www.w3.org/TR/WCAG22/"
    }
  ],
  "htmlDocuments": [
    {
      "name": "hello",
      "html": "<!doctype html><html><head><title>Hello</title></head><body><h1>Hello</h1><p>This HTML becomes a PDF.</p></body></html>"
    }
  ],
  "pageFormat": "Letter",
  "landscape": false,
  "marginTop": "0.5in",
  "marginRight": "0.5in",
  "marginBottom": "0.5in",
  "marginLeft": "0.5in",
  "printBackground": true,
  "scale": 1,
  "pageNumbers": false,
  "preferCssPageSize": false,
  "mediaType": "print",
  "taggedPdf": true,
  "outline": false,
  "waitUntil": "load",
  "delayMs": 500,
  "timeoutSecs": 60,
  "viewportWidth": 1280,
  "locale": "en-US"
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "urls": [
        {
            "url": "https://www.w3.org/TR/WCAG22/"
        }
    ],
    "htmlDocuments": [
        {
            "name": "hello",
            "html": "<!doctype html><html><head><title>Hello</title></head><body><h1>Hello</h1><p>This HTML becomes a PDF.</p></body></html>"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("examsens.ai/html-to-pdf").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "urls": [{ "url": "https://www.w3.org/TR/WCAG22/" }],
    "htmlDocuments": [{
            "name": "hello",
            "html": "<!doctype html><html><head><title>Hello</title></head><body><h1>Hello</h1><p>This HTML becomes a PDF.</p></body></html>",
        }],
}

# Run the Actor and wait for it to finish
run = client.actor("examsens.ai/html-to-pdf").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "urls": [
    {
      "url": "https://www.w3.org/TR/WCAG22/"
    }
  ],
  "htmlDocuments": [
    {
      "name": "hello",
      "html": "<!doctype html><html><head><title>Hello</title></head><body><h1>Hello</h1><p>This HTML becomes a PDF.</p></body></html>"
    }
  ]
}' |
apify call examsens.ai/html-to-pdf --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,examsens.ai/html-to-pdf"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/7RghcxqOeKnfUMdby/builds/bANkhQgXNjB1Z3dKy/openapi.json
