# HTML To PDF API (`igview-owner/html-to-pdf-api`) Actor

Convert HTML content and webpage URLs to high-quality PDF documents instantly. HTML to PDF converter with customizable page formats (A4, Letter), scale control, background graphics, and smart waiting for dynamic content. Perfect for reports, documentation, and automated PDF generation workflows.

- **URL**: https://apify.com/igview-owner/html-to-pdf-api.md
- **Developed by:** [Sachin Kumar Yadav](https://apify.com/igview-owner) (community)
- **Categories:** Automation, Developer tools, Other
- **Features:** Limited permissions
- **Stats:** 52 total users, 0 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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 Converter – Fast & Reliable Web & HTML to PDF Generation

**🚀 Convert any HTML content, invoice, receipt, report, or live webpage URL into high-quality, pixel-perfect PDF documents using headless Chrome rendering. Complete with custom paper sizes, margins, headers, footers with page numbers, CSS backgrounds, and direct download links. Built with Apify best practices for reliability, speed, and scale.**

***

### 📋 Table of Contents

- [✨ Features](#-features)
- [🎯 Use Cases](#-use-cases)
- [⚡ Quick Start](#-quick-start)
- [📊 Input Parameters](#-input-parameters)
- [📤 Output Format](#-output-format)
- [❓ FAQ](#-faq)
- [🛠️ Troubleshooting](#️-troubleshooting)
- [🏷️ Tags](#️-tags)
- [🚀 Get Started Now](#-get-started-now)

***

### ✨ Features

- **HTML to PDF** – Convert raw HTML code into professional, print-ready PDF files
- **URL to PDF** – Render live web pages and articles directly from any public URL
- **Full Styling Support** – Supports inline `<style>`, external CSS stylesheets, web fonts (Google Fonts), and images
- **Custom Paper Formats** – Choose from A3, A4, A5, Letter, Legal, or Tabloid
- **Orientation & Margins** – Portrait or landscape layout with customizable CSS unit margins (mm, in, px)
- **Headers & Footers** – Add custom running headers and footers with dynamic page numbers (`pageNumber` / `totalPages`)
- **Background Graphics** – Full control over CSS background colors, gradients, and background images
- **Rendering Scale** – Fine-tune scale factor from 0.1x to 2x for optimal fit
- **Page Ranges** – Print specific pages or page selections (e.g., `1-3, 5`)
- **Direct Cloud Storage** – PDFs are automatically saved to Apify Key-Value Store with instant public download URLs

***

### 🎯 Use Cases

| Use Case | Description | Key Benefits |
|----------|-------------|--------------|
| Automated Invoicing & Billing | Generate invoices, receipts, and order confirmations dynamically from HTML templates | Pixel-perfect invoices, automated accounting workflows |
| Webpage Archiving & Snapshots | Save blog posts, news articles, and documentation as offline PDF files | Permanent archival, reading offline, compliance records |
| Reports & Dashboard Exports | Turn business dashboards, charts, and metrics tables into executive reports | Clean page layouts, consistent corporate branding |
| Contracts & Legal Documents | Render NDAs, agreements, and certificates from dynamic customer data | Consistent pagination, legal page numbering |
| Ticket & Boarding Pass Generation | Create event tickets, badges, and vouchers with scannable barcodes & QR codes | High print resolution, exact dimension control |
| Web Scraping to PDF | Archive scraped web pages or search results in PDF format for research | Seamless integration into Apify scraping pipelines |

***

### ⚡ Quick Start

#### 1. Basic – HTML to PDF

```json
{
  "html": "<h1 style=\"font-family: Arial; color: #2563eb;\">Invoice #INV-2026-001</h1><p>Amount Due: <strong>$1,250.00</strong></p>",
  "filename": "invoice-001",
  "format": "A4"
}
```

#### 2. Live Webpage – URL to PDF

```json
{
  "url": "https://example.com",
  "filename": "example-page",
  "format": "Letter",
  "orientation": "landscape"
}
```

#### 3. Professional Report – Custom Margins & Page Numbers

```json
{
  "html": "<div style=\"font-family: sans-serif; padding: 20px;\"><h1>Annual Business Report</h1><p>Confidential summary for stakeholders...</p></div>",
  "filename": "annual-report",
  "format": "A4",
  "marginTop": "25mm",
  "marginBottom": "25mm",
  "displayHeaderFooter": true,
  "headerTemplate": "<div style=\"font-size: 9px; width: 100%; text-align: center; color: #666;\">Acme Corp – Confidential</div>",
  "footerTemplate": "<div style=\"font-size: 9px; width: 100%; text-align: center; color: #666;\">Page <span class=\"pageNumber\"></span> of <span class=\"totalPages\"></span></div>"
}
```

***

### 📊 Input Parameters

| Parameter | Type | Default | Description | Example |
|-----------|------|---------|-------------|---------|
| `html` | String | — | Raw HTML document string to render (Max 5 MB) | `"<h1 style='color:blue'>Hello</h1>"` |
| `url` | String | — | Live public webpage URL to render into PDF | `"https://en.wikipedia.org/wiki/PDF"` |
| `filename` | String | `"document"` | Name of the output PDF file (without .pdf extension) | `"monthly_invoice"` |
| `format` | String | `"A4"` | Standard paper size (`A3`, `A4`, `A5`, `Letter`, `Legal`, `Tabloid`) | `"A4"`, `"Letter"` |
| `orientation` | String | `"portrait"` | Page orientation (`portrait` or `landscape`) | `"portrait"`, `"landscape"` |
| `marginTop` | String | `"15mm"` | Top page margin with CSS units (`mm`, `in`, `px`) | `"20mm"`, `"0.5in"` |
| `marginRight` | String | `"15mm"` | Right page margin with CSS units | `"15mm"`, `"20px"` |
| `marginBottom` | String | `"15mm"` | Bottom page margin with CSS units | `"20mm"`, `"0.5in"` |
| `marginLeft` | String | `"15mm"` | Left page margin with CSS units | `"15mm"`, `"20px"` |
| `printBackground` | Boolean | `true` | Include CSS backgrounds, gradients, and images | `true`, `false` |
| `scale` | Number | `1` | Zoom scale factor between 0.1 and 2 | `1`, `0.85` |
| `displayHeaderFooter` | Boolean | `false` | Enable running headers and footers on every page | `true`, `false` |
| `headerTemplate` | String | — | HTML template for top header (must include inline font-size) | `"<div style='font-size:8px'>Header</div>"` |
| `footerTemplate` | String | — | HTML template for bottom footer (supports `pageNumber` & `totalPages`) | `"<div style='font-size:8px'><span class='pageNumber'></span></div>"` |
| `pageRanges` | String | — | Print specific pages only (e.g., `1-3,5`) | `"1-5"`, `"2,4,6"` |
| `emulateMedia` | String | `"print"` | CSS media type emulation (`print` or `screen`) | `"print"`, `"screen"` |
| `waitUntil` | String | `"load"` | Readiness event (`load`, `domcontentloaded`, `networkidle0`, `networkidle2`) | `"networkidle2"` |
| `timeout` | Integer | `30000` | Maximum rendering wait time in ms (1,000 to 60,000) | `30000`, `45000` |

> ℹ️ **Note**: Provide either `html` OR `url`. If both are provided, `html` takes priority.

***

### 📤 Output Format

#### Dataset Record Example

```json
{
  "source": "html_to_pdf_converter",
  "input_type": "html",
  "input_source": "HTML (327 chars)",
  "filename": "hello.pdf",
  "pdf_download_url": "https://api.apify.com/v2/key-value-stores/0e31f5e3-5889-4605-a15a-7bf916b0e4fd/records/hello.pdf",
  "pdf_key_value_store_key": "hello.pdf",
  "key_value_store_id": "0e31f5e3-5889-4605-a15a-7bf916b0e4fd",
  "file_size_bytes": 31569,
  "file_size_kb": 30.83,
  "format": "A4",
  "orientation": "portrait",
  "margins": {
    "top": "15mm",
    "right": "15mm",
    "bottom": "15mm",
    "left": "15mm"
  },
  "print_background": true,
  "scale": 1,
  "display_header_footer": false,
  "page_ranges": "all",
  "emulate_media": "print",
  "wait_until": "load",
  "status": "success",
  "converted_at": "2026-10-20T14:40:43.000Z"
}
```

#### Output Fields Explained

| Field | Type | Description |
|-------|------|-------------|
| `filename` | String | Generated PDF filename with extension |
| `pdf_download_url` | String | Direct public download URL to access the PDF |
| `file_size_kb` | Number | Generated PDF file size in kilobytes |
| `file_size_bytes` | Integer | Generated PDF file size in bytes |
| `input_type` | String | Input format used (`html` or `url`) |
| `format` | String | Paper size used for conversion |
| `orientation` | String | Orientation layout (`portrait` or `landscape`) |
| `status` | String | Execution status (`success` or `error`) |
| `converted_at` | String | ISO 8601 timestamp of conversion completion |

***

### ❓ FAQ

- **Q: Where is my generated PDF saved?**
  - Your PDF is automatically stored in the run's default **Apify Key-Value Store**. A direct `pdf_download_url` is returned in the dataset for instant access and downloading.

- **Q: Can I use CSS frameworks, Google Fonts, and images?**
  - Yes! You can include `<link>` tags for external fonts (like Google Fonts), `<style>` tags with custom CSS, Tailwind/Bootstrap via CDN, and `<img>` tags pointing to public URLs or base64 data URIs.

- **Q: How do page numbers work in headers and footers?**
  - Enable `displayHeaderFooter: true` and use Chrome's built-in CSS classes in your template:
    - `<span class="pageNumber"></span>` for current page number
    - `<span class="totalPages"></span>` for total pages count
    - `<span class="date"></span>` for formatted date
  - *Tip: Set top and bottom margins to at least 20mm so headers and footers are not clipped.*

- **Q: What is the maximum HTML file size supported?**
  - The API supports raw HTML payloads up to 5 MB, which is ample for hundreds of pages of formatted text and styling.

- **Q: When should I change `waitUntil` to `networkidle0` or `networkidle2`?**
  - If your webpage loads external fonts, analytics, or dynamic images via JavaScript, choose `networkidle0` or `networkidle2` to ensure all assets finish downloading before rendering.

- **Q: Can I integrate this with other Apify Actors or webhooks?**
  - Absolutely. You can call this Actor via Apify API, integrate it in Apify Workflows, or use webhooks to automatically download PDFs upon completion into Google Drive, S3, or Zapier.

***

### 🛠️ Troubleshooting

| Issue | Cause | Solution |
|-------|-------|----------|
| "No input provided" | Neither `html` nor `url` was passed | Provide either raw HTML content or a public webpage URL |
| Header/Footer is cut off | Margins are smaller than the header/footer height | Increase `marginTop` or `marginBottom` to `20mm` or `25mm` |
| Font size too large/small in header | Header/footer templates render outside the main document | Use explicit inline styling like `style="font-size: 9px;"` |
| Background colors missing | CSS background printing is turned off | Ensure `printBackground` is set to `true` |
| Page render timed out (504) | Webpage has heavy media or slow external scripts | Increase `timeout` (up to `60000` ms) or switch `waitUntil` to `domcontentloaded` |
| 413 Payload Too Large | HTML string exceeds 5 MB | Optimize inline SVGs/images or load them via external URLs |

***

### 🏷️ Tags

`html to pdf`, `pdf converter`, `webpage to pdf`, `url to pdf`, `chrome pdf generator`, `html2pdf`, `headless chrome pdf`, `puppeteer pdf`, `invoice generator`, `receipt to pdf`, `document generator`, `pdf api`, `apify actor`, `pdf download`, `automated pdf`, `print stylesheet`

***

### 🚀 Get Started Now

**Ready to convert HTML or URLs to PDF?**

1. Provide your **HTML content** or enter a **webpage URL**
2. Choose your preferred **paper size, orientation, and margins**
3. Click **Start** to run the actor
4. Download your generated PDF directly via the **download URL**
5. Click ["Try for free"](https://apify.com?fpr=ykgg9c) to test the actor

**If this actor helps your workflow, please give it a star!**

***

*Built with Apify Platform*

# Actor input Schema

## `html` (type: `string`):

Paste your full HTML document here. Inline <style> tags and external assets (images, fonts) are supported. Maximum size: 5 MB. Either HTML or URL is required — not both.

## `url` (type: `string`):

Enter a live webpage URL to render and convert to PDF (e.g., 'https://example.com'). The page will be fully loaded before conversion. Leave empty if you are providing HTML content above.

## `filename` (type: `string`):

Name for the generated PDF file (without .pdf extension). For example, entering 'invoice' will produce 'invoice.pdf'.

## `format` (type: `string`):

Select the paper format for the PDF output.

## `orientation` (type: `string`):

Choose between portrait (vertical) or landscape (horizontal) page layout.

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

Top margin with CSS units (e.g., '15mm', '0.5in', '40px').

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

Right margin with CSS units (e.g., '15mm', '0.5in', '40px').

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

Bottom margin with CSS units (e.g., '15mm', '0.5in', '40px').

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

Left margin with CSS units (e.g., '15mm', '0.5in', '40px').

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

Include CSS background colors and images in the PDF output.

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

Scale of the webpage rendering (0.1 to 2). Use values less than 1 to zoom out, greater than 1 to zoom in.

## `displayHeaderFooter` (type: `boolean`):

Enable header and footer rendering on every page. Keep margins ≥ 20mm so they are not clipped.

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

Inline-styled HTML shown at the top of every page. Must include explicit font-size. Example: <div style="font-size:8px;width:100%;text-align:center;">My Header</div>

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

Inline-styled HTML shown at the bottom of every page. Supports special classes: pageNumber, totalPages, date. Example: <div style="font-size:8px;width:100%;text-align:center;"><span class="pageNumber"></span> / <span class="totalPages"></span></div>

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

Print only selected pages (e.g., '1-3,5'). Leave empty to print all pages.

## `emulateMedia` (type: `string`):

Emulate CSS media type during rendering. 'print' uses print stylesheets, 'screen' uses screen stylesheets.

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

When to consider the page fully loaded: 'load' (default), 'domcontentloaded', 'networkidle0' (no connections for 500ms), 'networkidle2' (≤2 connections for 500ms).

## `timeout` (type: `integer`):

Maximum time in milliseconds to wait for the page to render (1000–60000).

## Actor input object example

```json
{
  "html": "<h1 style=\"font-family: sans-serif; color: #2563eb;\">Hello, PDF!</h1>\n<p style=\"font-size: 16px;\">This PDF was generated by the <strong>HTML to PDF Converter</strong> actor on Apify.</p>\n<ul>\n  <li>✅ Custom paper size & margins</li>\n  <li>✅ Headers & footers with page numbers</li>\n  <li>✅ Background colors & images</li>\n</ul>",
  "filename": "document",
  "format": "A4",
  "orientation": "portrait",
  "marginTop": "15mm",
  "marginRight": "15mm",
  "marginBottom": "15mm",
  "marginLeft": "15mm",
  "printBackground": true,
  "scale": 1,
  "displayHeaderFooter": false,
  "emulateMedia": "print",
  "waitUntil": "load",
  "timeout": 30000
}
```

# Actor output Schema

## `pdf_results` (type: `string`):

Open the dataset view with PDF download links, file sizes, and conversion details.

# 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 = {
    "html": `<h1 style="font-family: sans-serif; color: #2563eb;">Hello, PDF!</h1>
<p style="font-size: 16px;">This PDF was generated by the <strong>HTML to PDF Converter</strong> actor on Apify.</p>
<ul>
  <li>✅ Custom paper size & margins</li>
  <li>✅ Headers & footers with page numbers</li>
  <li>✅ Background colors & images</li>
</ul>`,
    "filename": "document",
    "format": "A4",
    "orientation": "portrait",
    "marginTop": "15mm",
    "marginRight": "15mm",
    "marginBottom": "15mm",
    "marginLeft": "15mm",
    "printBackground": true,
    "scale": 1,
    "displayHeaderFooter": false,
    "emulateMedia": "print",
    "waitUntil": "load",
    "timeout": 30000
};

// Run the Actor and wait for it to finish
const run = await client.actor("igview-owner/html-to-pdf-api").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 = {
    "html": """<h1 style=\"font-family: sans-serif; color: #2563eb;\">Hello, PDF!</h1>
<p style=\"font-size: 16px;\">This PDF was generated by the <strong>HTML to PDF Converter</strong> actor on Apify.</p>
<ul>
  <li>✅ Custom paper size & margins</li>
  <li>✅ Headers & footers with page numbers</li>
  <li>✅ Background colors & images</li>
</ul>""",
    "filename": "document",
    "format": "A4",
    "orientation": "portrait",
    "marginTop": "15mm",
    "marginRight": "15mm",
    "marginBottom": "15mm",
    "marginLeft": "15mm",
    "printBackground": True,
    "scale": 1,
    "displayHeaderFooter": False,
    "emulateMedia": "print",
    "waitUntil": "load",
    "timeout": 30000,
}

# Run the Actor and wait for it to finish
run = client.actor("igview-owner/html-to-pdf-api").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 '{
  "html": "<h1 style=\\"font-family: sans-serif; color: #2563eb;\\">Hello, PDF!</h1>\\n<p style=\\"font-size: 16px;\\">This PDF was generated by the <strong>HTML to PDF Converter</strong> actor on Apify.</p>\\n<ul>\\n  <li>✅ Custom paper size & margins</li>\\n  <li>✅ Headers & footers with page numbers</li>\\n  <li>✅ Background colors & images</li>\\n</ul>",
  "filename": "document",
  "format": "A4",
  "orientation": "portrait",
  "marginTop": "15mm",
  "marginRight": "15mm",
  "marginBottom": "15mm",
  "marginLeft": "15mm",
  "printBackground": true,
  "scale": 1,
  "displayHeaderFooter": false,
  "emulateMedia": "print",
  "waitUntil": "load",
  "timeout": 30000
}' |
apify call igview-owner/html-to-pdf-api --silent --output-dataset

```

## MCP server setup

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

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/MEhMMwwWHRqdYUpdg/builds/A92l7GjRlF72jpjCq/openapi.json
