# Page count

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

## Endpoint

```
POST /pageCount
```

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

---

## Request body

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

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `pdf_base64` | string | Conditional | Base64-encoded PDF file |
| `pdf_url` | string | Conditional | URL to fetch the PDF from |
| `file` | file | Conditional | PDF 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

```bash
# 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

```bash
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

```bash
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:**

| Field | Type | Description |
|-------|------|-------------|
| `page_count` | integer | Total number of pages in the PDF |

### Error

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

**Status codes:**

| Code | Description |
|------|-------------|
| 200 | Success - Page count returned as JSON |
| 401 | Unauthorized - Missing or invalid Authorization header |
| 403 | Forbidden - Invalid API key or OAuth token |
| 500 | Internal 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:

```bash
# 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:

```bash
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:

```bash
# 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

---

## Related endpoints

- [Extract text](https://pdf-mcp.io/docs/api-extract-text): extract text from PDF pages
- [Extract pages](https://pdf-mcp.io/docs/api-extract-pages): create a PDF from selected pages
- [PDF to image](https://pdf-mcp.io/docs/api-pdf-to-image): convert PDF pages to images

## Credit usage

Each request costs **0.01 credits**.
