Get the total number of pages in a PDF document. This lightweight endpoint is ideal for validating PDFs before processing, planning batch operations, or displaying document metadata to users.

Endpoint

POST /pageCount

Authentication

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

Authorization: Bearer YOUR_API_KEY

See Authentication for details.


Request Body

Content-Type: application/json or multipart/form-data

FieldTypeRequiredDescription
pdf_base64stringConditionalBase64-encoded PDF file
pdf_urlstringConditionalURL to fetch the PDF from
filefileConditionalPDF file upload (multipart only)

Note: You must provide exactly one of: pdf_base64, pdf_url, or file.

Field Details

pdf_base64 (conditional)

A base64-encoded PDF file. Use this when you have the PDF data in memory or need to send it as part of a JSON payload. The encoded string should not include the data URI prefix.

pdf_url (conditional)

A publicly accessible URL where the PDF can be fetched. The server will download the PDF from this URL before processing. Supports redirects.

file (conditional, multipart only)

Direct file upload via multipart form data. This is the simplest option when you have the PDF file available locally.


Example Request

Get Page Count (JSON with Base64)

# First, encode your PDF to base64
PDF_BASE64=$(base64 -i document.pdf)

curl -X POST https://api.pdf-mcp.io/pageCount \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_base64": "'"$PDF_BASE64"'"
  }'

Get Page Count from URL

curl -X POST https://api.pdf-mcp.io/pageCount \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_url": "https://example.com/documents/report.pdf"
  }'

Using File Upload (Multipart)

curl -X POST https://api.pdf-mcp.io/pageCount \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@document.pdf"

Response

Success

Returns JSON with the page count.

{
  "page_count": 42
}

Response Fields:

FieldTypeDescription
page_countintegerTotal number of pages in the PDF

Error

{
  "error": "Failed to get page count",
  "message": "Error description"
}

Status Codes:

CodeDescription
200Success - Page count returned as JSON
401Unauthorized - Missing or invalid Authorization header
403Forbidden - Invalid API key or OAuth token
500Internal Server Error - Failed to process PDF

Use Cases

Validate PDF Before Processing

Check if a PDF is valid and get its page count before performing expensive operations:

# Check page count first
RESPONSE=$(curl -s -X POST https://api.pdf-mcp.io/pageCount \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_url": "https://example.com/documents/large-report.pdf"
  }')

PAGE_COUNT=$(echo $RESPONSE | jq -r '.page_count')

# Only process if under 100 pages
if [ "$PAGE_COUNT" -lt 100 ]; then
  echo "Processing $PAGE_COUNT page document..."
  # Continue with PDF processing
fi

Estimate Processing Costs

Calculate expected credit usage before batch processing:

curl -X POST https://api.pdf-mcp.io/pageCount \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@quarterly-report.pdf"

Use the page count to estimate credits needed for text extraction or image conversion.

Display Document Metadata

Show document information to users in your application:

async function getDocumentInfo(pdfUrl) {
  const response = await fetch('https://api.pdf-mcp.io/pageCount', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ pdf_url: pdfUrl })
  });

  const data = await response.json();
  return {
    pages: data.page_count
  };
}

Plan Page Extraction

Determine valid page ranges before extracting specific pages:

# Get total pages
curl -X POST https://api.pdf-mcp.io/pageCount \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_url": "https://example.com/documents/manual.pdf"
  }'

# Response: { "page_count": 150 }
# Now you know valid pages are 1-150 for extraction

Example: Python Integration

import requests

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

# Get page count from a URL
response = requests.post(
    API_URL,
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "pdf_url": "https://example.com/documents/report.pdf"
    }
)

if response.status_code == 200:
    data = response.json()
    print(f"PDF has {data['page_count']} pages")
else:
    print(f"Error: {response.status_code}")

Using File Upload (Python)

import requests

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

# Get page count from a local file
with open("document.pdf", "rb") as f:
    response = requests.post(
        API_URL,
        headers={
            "Authorization": f"Bearer {API_KEY}"
        },
        files={
            "file": ("document.pdf", f, "application/pdf")
        }
    )

if response.status_code == 200:
    data = response.json()
    print(f"PDF has {data['page_count']} pages")
else:
    print(f"Error: {response.status_code}")

Example: Node.js Integration

const fs = require('fs');

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

async function getPageCount(pdfUrl) {
  const response = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      pdf_url: pdfUrl
    })
  });

  if (response.ok) {
    const data = await response.json();
    console.log(`PDF has ${data.page_count} pages`);
    return data.page_count;
  } else {
    console.error('Error:', response.status);
    return null;
  }
}

getPageCount('https://example.com/documents/report.pdf');

Using File Upload (Node.js)

const fs = require('fs');
const path = require('path');

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

async function getPageCountFromFile(filePath) {
  const fileBuffer = fs.readFileSync(filePath);
  const formData = new FormData();
  formData.append('file', new Blob([fileBuffer]), path.basename(filePath));

  const response = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    },
    body: formData
  });

  if (response.ok) {
    const data = await response.json();
    console.log(`PDF has ${data.page_count} pages`);
    return data.page_count;
  } else {
    console.error('Error:', response.status);
    return null;
  }
}

getPageCountFromFile('document.pdf');

Tips and Best Practices

Choosing Input Method

  • File upload: Best for local files, simplest to implement
  • Base64: Best for programmatic access when PDF is already in memory
  • URL: Best for processing PDFs already hosted online

Performance

This is a lightweight operation that only reads PDF metadata without processing the full document content. It’s ideal for:

  • Pre-flight checks before expensive operations
  • Batch processing validation
  • Quick document info retrieval

Error Handling

  • Validate that the file is a PDF before sending
  • Handle network errors when using URL input
  • Implement retry logic for transient failures

Common Issues

  • Invalid PDF: Ensure the file is a valid PDF, not a renamed image or corrupted file
  • URL access: The PDF URL must be publicly accessible
  • Encrypted PDFs: Password-protected PDFs cannot be processed

Credit Usage

No credits charged - This is a metadata-only operation.