pdf-mcp Documentation
Browse documentation
Markdown

Page count

Request and response details for counting PDF pages with /pageCount

On this page

Use /pageCount to validate a PDF, plan a batch operation, or display its page count without processing the full document content.

Endpoint

Plain text
POST /pageCount

Authentication

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

Plain text
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)

Upload a local PDF as multipart form data.


Request examples

Base64 PDF in JSON

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

PDF URL

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

Multipart file upload

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

JSON
{
  "page_count": 42
}

Response fields:

FieldTypeDescription
page_countintegerTotal number of pages in the PDF

Error

JSON
{
  "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

Examples

Validate a PDF

Check that a PDF is valid and count its pages before running more expensive operations:

Shell
# 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 cost

Calculate expected credit usage before batch processing:

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

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

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

Python example

Python
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}")

Python 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}")

Node.js example

JavaScript
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');

Node.js file upload

JavaScript
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');

Implementation notes

Choose an input method

  • Upload a local file with multipart form data
  • Use base64 when the PDF is already in memory
  • Supply a URL for a PDF that is already hosted online

Performance

The operation reads PDF metadata without processing the full document content. Use it for:

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

Handle errors

  • 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

Each request costs 0.01 credits.