# Extract pages from a PDF

Create a new PDF from a selection of pages of an existing one. Pick the pages with the pages parameter; omit it and every page is extracted, in document order.

Extract one or more pages from a PDF into a new document. Select the pages with
the [`pages`](#selecting-pages) parameter. When omitted, every page is
extracted, and the result always keeps them in document order. The API is
stateless: your document is processed in-region and never stored.

## Endpoint

<Endpoint method="POST" path="/v1/extract_pages" />

Available in every region. See [Regions & data residency](/docs/api/regions-and-data-residency)
for routing and data residency.

| Region         | URL                                                 |
| -------------- | --------------------------------------------------- |
| Global         | `https://api.pdfblocks.com/v1/extract_pages`        |
| United States  | `https://us.api.pdfblocks.com/v1/extract_pages`     |
| US HIPAA       | `https://hipaa.api.pdfblocks.com/v1/extract_pages`  |
| European Union | `https://eu.api.pdfblocks.com/v1/extract_pages`     |
| United Kingdom | `https://uk.api.pdfblocks.com/v1/extract_pages`     |
| Canada         | `https://ca.api.pdfblocks.com/v1/extract_pages`     |
| Australia      | `https://au.api.pdfblocks.com/v1/extract_pages`     |
| Japan          | `https://jp.api.pdfblocks.com/v1/extract_pages`     |
| India          | `https://in.api.pdfblocks.com/v1/extract_pages`     |
| Brazil         | `https://br.api.pdfblocks.com/v1/extract_pages`     |

## Authentication

Authenticate every request with your secret API key in the `X-API-Key` header,
over HTTPS. Create and manage keys from the
[dashboard](https://dashboard.pdfblocks.com). See
[Authentication](/docs/api/authentication) for details.

## Request

The endpoint accepts a `multipart/form-data` request body.

<ParamField name="file" type="file" required>
  The input PDF document.
</ParamField>

<ParamField name="pages" type="string">
  The pages to extract, written as a [page range](#selecting-pages) such as
  `1..3,5`. When omitted, every page is extracted. Maximum 1000 characters.
</ParamField>

### Selecting pages

The `pages` parameter takes a comma-separated list of 1-based page numbers and
ranges. It is treated as a **set**: order and duplicates are ignored, and the
extracted pages always stay in document order. To rearrange pages into an
arbitrary order, use [Reorder pages](/docs/api/reorder-pages-of-pdf) instead.

| Pattern   | Selects                                    |
| --------- | ------------------------------------------ |
| *(omit)*  | Every page                                 |
| `1`       | The first page only                        |
| `1..3,5`  | Pages 1, 2, 3, and 5                       |
| `2..`     | Page 2 through the last page               |
| `..-2`    | The first page through the second-to-last  |
| `-1`      | The last page                              |

See [Selecting pages](/docs/api/selecting-pages) for the complete reference.

## Examples

Extract pages 1–3 and 5 into a new PDF:

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/extract_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F pages='1..3,5' \
  -o extracted.pdf
```

```python title="Python"
# pip install requests
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/extract_pages',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'pages': '1..3,5'},
    )

response.raise_for_status()
with open('extracted.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
// Node.js 18+
import { readFile, writeFile } from 'node:fs/promises';

const body = new FormData();
body.set('file', new Blob([await readFile('input.pdf')]), 'input.pdf');
body.set('pages', '1..3,5');

const response = await fetch('https://api.pdfblocks.com/v1/extract_pages', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('extracted.pdf', Buffer.from(await response.arrayBuffer()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/extract_pages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: your_api_key'],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('input.pdf', 'application/pdf'),
        'pages' => '1..3,5',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('extracted.pdf', $pdf);
}
```

```ruby title="Ruby"
# gem install http
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/extract_pages', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    pages: '1..3,5',
  })

File.write('extracted.pdf', response.body) if response.status.success?
```

```go title="Go"
package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var buf bytes.Buffer
	form := multipart.NewWriter(&buf)

	file, _ := os.Open("input.pdf")
	defer file.Close()
	part, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(part, file)

	form.WriteField("pages", "1..3,5")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/extract_pages", &buf)
	req.Header.Set("Content-Type", form.FormDataContentType())
	req.Header.Set("X-API-Key", "your_api_key")

	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	out, _ := os.Create("extracted.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
```

```csharp title="C#"
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");

using var form = new MultipartFormDataContent
{
    { new ByteArrayContent(File.ReadAllBytes("input.pdf")), "file", "input.pdf" },
    { new StringContent("1..3,5"), "pages" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/extract_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "extracted.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

## Response

On success, the response is `200 OK` with the extracted PDF as the body:

```http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 22841
```

The output contains only the selected pages, in document order. Stream the body
straight to a file, as the examples above do; nothing is stored on our side.

## Errors

Failed requests return an `application/problem+json` body. The most common one
for this endpoint is a `400`, returned when `pages` references a page that isn't
in the document or `file` isn't a readable PDF. The `errors` object names each
field:

```json
{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "pages": ["The pages field references a page that does not exist in the document."]
  }
}
```

A missing or invalid `X-API-Key` returns a `401`. See
[Errors](/docs/api/errors) for every status code and the full response shape.

## Recipes

Common variations. Expand one to see it in every language.

<AccordionGroup>

<Accordion title="Extract a single page">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/extract_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F pages='1' \
  -o page-1.pdf
```

```python title="Python"
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/extract_pages',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'pages': '1'},
    )

response.raise_for_status()
with open('page-1.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
import { readFile, writeFile } from 'node:fs/promises';

const body = new FormData();
body.set('file', new Blob([await readFile('input.pdf')]), 'input.pdf');
body.set('pages', '1');

const response = await fetch('https://api.pdfblocks.com/v1/extract_pages', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('page-1.pdf', Buffer.from(await response.arrayBuffer()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/extract_pages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: your_api_key'],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('input.pdf', 'application/pdf'),
        'pages' => '1',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('page-1.pdf', $pdf);
}
```

```ruby title="Ruby"
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/extract_pages', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    pages: '1',
  })

File.write('page-1.pdf', response.body) if response.status.success?
```

```go title="Go"
package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var buf bytes.Buffer
	form := multipart.NewWriter(&buf)

	file, _ := os.Open("input.pdf")
	defer file.Close()
	part, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(part, file)

	form.WriteField("pages", "1")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/extract_pages", &buf)
	req.Header.Set("Content-Type", form.FormDataContentType())
	req.Header.Set("X-API-Key", "your_api_key")

	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	out, _ := os.Create("page-1.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
```

```csharp title="C#"
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");

using var form = new MultipartFormDataContent
{
    { new ByteArrayContent(File.ReadAllBytes("input.pdf")), "file", "input.pdf" },
    { new StringContent("1"), "pages" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/extract_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "page-1.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

</Accordion>

<Accordion title="Extract the last three pages">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/extract_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F pages='-3..-1' \
  -o last-three.pdf
```

```python title="Python"
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/extract_pages',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'pages': '-3..-1'},
    )

response.raise_for_status()
with open('last-three.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
import { readFile, writeFile } from 'node:fs/promises';

const body = new FormData();
body.set('file', new Blob([await readFile('input.pdf')]), 'input.pdf');
body.set('pages', '-3..-1');

const response = await fetch('https://api.pdfblocks.com/v1/extract_pages', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('last-three.pdf', Buffer.from(await response.arrayBuffer()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/extract_pages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: your_api_key'],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('input.pdf', 'application/pdf'),
        'pages' => '-3..-1',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('last-three.pdf', $pdf);
}
```

```ruby title="Ruby"
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/extract_pages', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    pages: '-3..-1',
  })

File.write('last-three.pdf', response.body) if response.status.success?
```

```go title="Go"
package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var buf bytes.Buffer
	form := multipart.NewWriter(&buf)

	file, _ := os.Open("input.pdf")
	defer file.Close()
	part, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(part, file)

	form.WriteField("pages", "-3..-1")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/extract_pages", &buf)
	req.Header.Set("Content-Type", form.FormDataContentType())
	req.Header.Set("X-API-Key", "your_api_key")

	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	out, _ := os.Create("last-three.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
```

```csharp title="C#"
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");

using var form = new MultipartFormDataContent
{
    { new ByteArrayContent(File.ReadAllBytes("input.pdf")), "file", "input.pdf" },
    { new StringContent("-3..-1"), "pages" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/extract_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "last-three.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

</Accordion>

</AccordionGroup>

## Related actions

<CardGroup cols={2}>

<Card title="Remove pages" href="/docs/api/remove-pages-from-pdf">
  Drop pages instead of keeping them.
</Card>

<Card title="Reorder pages" href="/docs/api/reorder-pages-of-pdf">
  Extract and reorder in one call.
</Card>

<Card title="Split at page" href="/docs/api/split-pdf-at-page">
  Split into two documents at a boundary.
</Card>

<Card title="Merge documents" href="/docs/api/merge-pdf-documents">
  Combine the extracted pages with others.
</Card>

</CardGroup>
