# PDF to image

Use `/pdfToImage` to rasterize PDF pages as PNG or JPEG images for thumbnails, previews, or image-based processing.

## Endpoint

```
POST /pdfToImage
```

## Authentication

Send a valid API key or OAuth token in the `Authorization` header:

```
Authorization: Bearer YOUR_API_KEY
```

See [Authentication](https://pdf-mcp.io/docs/authentication) for details.

---

## JSON request body

**Content-Type:** `application/json`

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `pdf_base64` | string | * | Base64-encoded PDF file |
| `pdf_url` | string | * | URL to fetch PDF from |
| `pages` | array | No | Specific pages to convert (1-indexed), or all if omitted |
| `format` | string | No | Output image format: `"png"` or `"jpeg"` (default: `"png"`) |
| `dpi` | integer | No | Image resolution in DPI (default: `200`) |

*One of `pdf_base64` or `pdf_url` is required.

### Field details

**pdf_base64**

Base64-encoded PDF content. Use this when you have the PDF file data in memory or need to avoid additional HTTP requests.

**pdf_url**

URL to fetch the PDF from. The API will download the PDF from this URL before processing. Must be publicly accessible.

**pages** (optional)

Array of page numbers to convert. Pages are 1-indexed (first page is 1, not 0). If omitted, all pages in the PDF are converted.

```json
"pages": [1, 3, 5]  // Convert pages 1, 3, and 5
```

**format** (optional)

Output image format. Supported values:
- `"png"` - PNG format with transparency support (default)
- `"jpeg"` - JPEG format (smaller file size, no transparency)

Note: When using JPEG format, RGBA images are automatically converted to RGB.

**dpi** (optional)

Image resolution is measured in dots per inch. Higher values produce larger, sharper images:
- `72` - Screen resolution (smallest)
- `150` - Good for web previews
- `200` - Default, balanced quality/size
- `300` - Print quality

---

## Multipart request body

**Content-Type:** `multipart/form-data`

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `file` | file | Yes | PDF file upload |
| `pages` | string | No | Comma-separated page numbers (e.g., "1,3,5") |
| `format` | string | No | Output image format: `"png"` or `"jpeg"` (default: `"png"`) |
| `dpi` | integer | No | Image resolution in DPI (default: `200`) |

---

## Request examples

### Convert every page with JSON

```bash
curl -X POST https://api.pdf-mcp.io/pdfToImage \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_url": "https://example.com/document.pdf",
    "format": "png",
    "dpi": 200
  }'
```

### Convert selected pages with JSON

```bash
curl -X POST https://api.pdf-mcp.io/pdfToImage \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_base64": "JVBERi0xLjQKJeLjz9...",
    "pages": [1, 2, 5],
    "format": "jpeg",
    "dpi": 150
  }'
```

### Multipart file upload

```bash
curl -X POST https://api.pdf-mcp.io/pdfToImage \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@document.pdf" \
  -F "pages=1,3,5" \
  -F "format=png" \
  -F "dpi=300"
```

---

## Response

### Success

Returns JSON with base64-encoded images for each converted page.

```json
{
  "images": [
    {
      "page": 1,
      "format": "png",
      "image_base64": "iVBORw0KGgoAAAANSUhEUgAA..."
    },
    {
      "page": 2,
      "format": "png",
      "image_base64": "iVBORw0KGgoAAAANSUhEUgBB..."
    }
  ],
  "total_pages": 5
}
```

**Response fields:**

| Field | Type | Description |
|-------|------|-------------|
| `images` | array | Array of converted page images |
| `images[].page` | integer | Page number (1-indexed) |
| `images[].format` | string | Image format used |
| `images[].image_base64` | string | Base64-encoded image data |
| `total_pages` | integer | Total number of pages in the PDF |

### Error

```json
{
  "error": "Failed to convert PDF to images",
  "message": "Error description"
}
```

**Status codes:**

| Code | Description |
|------|-------------|
| 200 | Success - Images returned |
| 401 | Unauthorized - Missing or invalid Authorization header |
| 403 | Forbidden - Invalid API key or OAuth token |
| 500 | Internal Server Error - Conversion failed |

---

## Python example

```python
import requests
import base64

API_KEY = "YOUR_API_KEY"
API_URL = "https://api.pdf-mcp.io/pdfToImage"

# Convert PDF from URL
response = requests.post(
    API_URL,
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "pdf_url": "https://example.com/document.pdf",
        "format": "png",
        "dpi": 200
    }
)

if response.status_code == 200:
    data = response.json()
    print(f"Converted {len(data['images'])} of {data['total_pages']} pages")

    # Save each page as an image file
    for img in data['images']:
        image_data = base64.b64decode(img['image_base64'])
        with open(f"page-{img['page']}.{img['format']}", "wb") as f:
            f.write(image_data)
    print("Images saved successfully!")
else:
    print(f"Error: {response.status_code}")
```

### Base64 input

```python
import requests
import base64

API_KEY = "YOUR_API_KEY"
API_URL = "https://api.pdf-mcp.io/pdfToImage"

# Read and encode PDF to base64
with open("document.pdf", "rb") as f:
    pdf_base64 = base64.b64encode(f.read()).decode("utf-8")

response = requests.post(
    API_URL,
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "pdf_base64": pdf_base64,
        "pages": [1, 2],  # Convert only first two pages
        "format": "jpeg",
        "dpi": 150
    }
)

if response.status_code == 200:
    data = response.json()
    for img in data['images']:
        image_data = base64.b64decode(img['image_base64'])
        with open(f"page-{img['page']}.{img['format']}", "wb") as f:
            f.write(image_data)
    print("Images saved successfully!")
else:
    print(f"Error: {response.status_code}")
```

---

## Node.js example

```javascript
const fs = require('fs');

const API_KEY = 'YOUR_API_KEY';
const API_URL = 'https://api.pdf-mcp.io/pdfToImage';

async function convertPdfToImages() {
  const response = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      pdf_url: 'https://example.com/document.pdf',
      format: 'png',
      dpi: 200
    })
  });

  if (response.ok) {
    const data = await response.json();
    console.log(`Converted ${data.images.length} of ${data.total_pages} pages`);

    // Save each page as an image file
    for (const img of data.images) {
      const buffer = Buffer.from(img.image_base64, 'base64');
      fs.writeFileSync(`page-${img.page}.${img.format}`, buffer);
    }
    console.log('Images saved successfully!');
  } else {
    console.error('Error:', response.status);
  }
}

convertPdfToImages();
```

### Base64 input

```javascript
const fs = require('fs');

const API_KEY = 'YOUR_API_KEY';
const API_URL = 'https://api.pdf-mcp.io/pdfToImage';

async function convertPdfToImages() {
  // Read and encode PDF to base64
  const pdfBase64 = fs.readFileSync('document.pdf').toString('base64');

  const response = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      pdf_base64: pdfBase64,
      pages: [1, 2],  // Convert only first two pages
      format: 'jpeg',
      dpi: 150
    })
  });

  if (response.ok) {
    const data = await response.json();
    for (const img of data.images) {
      const buffer = Buffer.from(img.image_base64, 'base64');
      fs.writeFileSync(`page-${img.page}.${img.format}`, buffer);
    }
    console.log('Images saved successfully!');
  } else {
    console.error('Error:', response.status);
  }
}

convertPdfToImages();
```

---

## Decode base64 images

### JavaScript

```javascript
const response = await fetch('https://api.pdf-mcp.io/pdfToImage', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    pdf_url: 'https://example.com/document.pdf'
  })
});

const data = await response.json();

// Display first page as image
const img = document.createElement('img');
img.src = `data:image/png;base64,${data.images[0].image_base64}`;
document.body.appendChild(img);

// Or download as file
const link = document.createElement('a');
link.href = `data:image/png;base64,${data.images[0].image_base64}`;
link.download = `page-${data.images[0].page}.png`;
link.click();
```

### Python

```python
import base64
import requests

response = requests.post(
    'https://api.pdf-mcp.io/pdfToImage',
    headers={'Authorization': 'Bearer YOUR_API_KEY'},
    json={'pdf_url': 'https://example.com/document.pdf'}
)

data = response.json()

# Save each page as a file
for img in data['images']:
    image_data = base64.b64decode(img['image_base64'])
    with open(f"page-{img['page']}.{img['format']}", 'wb') as f:
        f.write(image_data)
```

### Node.js

```javascript
const fs = require('fs');

const response = await fetch('https://api.pdf-mcp.io/pdfToImage', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    pdf_url: 'https://example.com/document.pdf'
  })
});

const data = await response.json();

// Save each page to disk
for (const img of data.images) {
  const buffer = Buffer.from(img.image_base64, 'base64');
  fs.writeFileSync(`page-${img.page}.${img.format}`, buffer);
}
```

---

## Examples

### Thumbnails

Generate preview thumbnails for PDF documents:

```bash
curl -X POST https://api.pdf-mcp.io/pdfToImage \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_url": "https://example.com/document.pdf",
    "pages": [1],
    "format": "jpeg",
    "dpi": 72
  }'
```

### Print-quality previews

Generate print-quality images:

```bash
curl -X POST https://api.pdf-mcp.io/pdfToImage \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_url": "https://example.com/document.pdf",
    "format": "png",
    "dpi": 300
  }'
```

---

## Implementation notes

### Performance

- Use lower DPI (72-150) for web previews to reduce file size
- Convert only the pages you need using the `pages` parameter
- Use JPEG format for smaller file sizes when transparency is not needed

### Choose a format

- Use PNG for documents with text, graphics, or transparency
- Use JPEG for photos or when file size matters more

### Memory use

- Large PDFs with many pages will produce multiple images
- High DPI settings (300+) significantly increase output size
- Consider processing large PDFs in batches using the `pages` parameter

---

## Related endpoints

- [HTML to PDF](https://pdf-mcp.io/docs/api-html-to-pdf): create PDFs from HTML
- [Image to PDF](https://pdf-mcp.io/docs/api-image-to-pdf): convert images to PDF
- [Extract text](https://pdf-mcp.io/docs/api-extract-text): extract text content from PDFs
- [Page count](https://pdf-mcp.io/docs/api-page-count): check the page count before processing

## Credit usage

The first page costs **1 credit**. Each additional page costs **0.01 credits**.
