pdf-mcp Documentation
Browse documentation
Markdown

PDF to image

Request and response details for converting PDF pages to images with /pdfToImage

On this page

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

Endpoint

Plain text
POST /pdfToImage

Authentication

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

Plain text
Authorization: Bearer YOUR_API_KEY

See Authentication for details.


JSON request body

Content-Type: application/json

FieldTypeRequiredDescription
pdf_base64string*Base64-encoded PDF file
pdf_urlstring*URL to fetch PDF from
pagesarrayNoSpecific pages to convert (1-indexed), or all if omitted
formatstringNoOutput image format: "png" or "jpeg" (default: "png")
dpiintegerNoImage 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

FieldTypeRequiredDescription
filefileYesPDF file upload
pagesstringNoComma-separated page numbers (e.g., “1,3,5”)
formatstringNoOutput image format: "png" or "jpeg" (default: "png")
dpiintegerNoImage resolution in DPI (default: 200)

Request examples

Convert every page with JSON

Shell
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

Shell
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

Shell
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:

FieldTypeDescription
imagesarrayArray of converted page images
images[].pageintegerPage number (1-indexed)
images[].formatstringImage format used
images[].image_base64stringBase64-encoded image data
total_pagesintegerTotal number of pages in the PDF

Error

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

Status codes:

CodeDescription
200Success - Images returned
401Unauthorized - Missing or invalid Authorization header
403Forbidden - Invalid API key or OAuth token
500Internal 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:

Shell
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
  }'

Generate print-quality images:

Shell
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

Credit usage

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