# Rotate pages in a PDF

Rotate the pages of a PDF by a fixed angle, clockwise or counter-clockwise. Every page rotates by default; use the pages parameter to target a subset.

Rotate the pages of a PDF document by a fixed angle. Positive angles rotate
clockwise, negative angles counter-clockwise. By default every page is rotated:
use the [`pages`](#selecting-pages) parameter to target a subset. The API is
stateless: your document is processed in-region and never stored.

## Endpoint

<Endpoint method="POST" path="/v1/rotate_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/rotate_pages`  |
| United States  | `https://us.api.pdfblocks.com/v1/rotate_pages` |
| US HIPAA       | `https://hipaa.api.pdfblocks.com/v1/rotate_pages` |
| European Union | `https://eu.api.pdfblocks.com/v1/rotate_pages` |
| United Kingdom | `https://uk.api.pdfblocks.com/v1/rotate_pages` |
| Canada         | `https://ca.api.pdfblocks.com/v1/rotate_pages` |
| Australia      | `https://au.api.pdfblocks.com/v1/rotate_pages` |
| Japan          | `https://jp.api.pdfblocks.com/v1/rotate_pages` |
| India          | `https://in.api.pdfblocks.com/v1/rotate_pages` |
| Brazil         | `https://br.api.pdfblocks.com/v1/rotate_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="angle" type="integer" required>
  The rotation to apply, in degrees. One of [the valid angles](#rotation-angles).
  Positive values rotate clockwise, negative values counter-clockwise.
</ParamField>

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

### Rotation angles

Pass one of the following values to the `angle` parameter.

| Angle   | Rotation                                   |
| ------- | ------------------------------------------ |
| `0`     | No rotation                                |
| `90`    | 90° clockwise                              |
| `180`   | 180°                                       |
| `270`   | 270° clockwise (90° counter-clockwise)     |
| `-90`   | 90° counter-clockwise                      |
| `-180`  | 180°                                       |
| `-270`  | 270° counter-clockwise (90° clockwise)     |

Positive angles rotate clockwise, negative angles counter-clockwise; each
rotation adds to the page's current rotation.

### 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 pages
are always rotated in document order.

| 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

Rotate the first three pages 90° clockwise:

<CodeGroup>

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

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

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

response.raise_for_status()
with open('rotated.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('angle', '90');
body.set('pages', '1..3');

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

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

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/rotate_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'),
        'angle' => '90',
        'pages' => '1..3',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('rotated.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/rotate_pages', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    angle: '90',
    pages: '1..3',
  })

File.write('rotated.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("angle", "90")
	form.WriteField("pages", "1..3")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/rotate_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("rotated.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("90"), "angle" },
    { new StringContent("1..3"), "pages" },
};

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

</CodeGroup>

## Response

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

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

The output keeps the same pages and content as the input: only the selected
pages' rotation changes. 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 `angle` isn't one of the supported
values 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": {
    "angle": ["The angle must be one of 0, 90, 180, 270, -90, -180, -270."]
  }
}
```

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="Turn a landscape scan upright">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/rotate_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F angle=90 \
  -o upright.pdf
```

```python title="Python"
import requests

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

response.raise_for_status()
with open('upright.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('angle', '90');

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

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

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/rotate_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'),
        'angle' => '90',
    ],
]);

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

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

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

File.write('upright.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("angle", "90")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/rotate_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("upright.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("90"), "angle" },
};

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

</CodeGroup>

</Accordion>

<Accordion title="Flip every page 180°">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/rotate_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F angle=180 \
  -o flipped.pdf
```

```python title="Python"
import requests

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

response.raise_for_status()
with open('flipped.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('angle', '180');

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

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

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/rotate_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'),
        'angle' => '180',
    ],
]);

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

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

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

File.write('flipped.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("angle", "180")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/rotate_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("flipped.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("180"), "angle" },
};

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

</CodeGroup>

</Accordion>

</AccordionGroup>

## Related actions

<CardGroup cols={2}>

<Card title="Reverse pages" href="/docs/api/reverse-pages-of-pdf">
  Reverse the page order.
</Card>

<Card title="Reorder pages" href="/docs/api/reorder-pages-of-pdf">
  Rearrange pages into any order.
</Card>

<Card title="Extract pages" href="/docs/api/extract-pages-from-pdf">
  Pull out a subset of pages.
</Card>

<Card title="Remove pages" href="/docs/api/remove-pages-from-pdf">
  Drop pages from the document.
</Card>

</CardGroup>
