PDF Blocks
料金サポート
無料で始める
ページへ移動

PDF のページを並べ替える

PDF のページを指定したとおりの順序に並べ替えます。同じページを繰り返し指定すると複製され、指定しなかったページは除外されます。

PDF のページを、page_order パラメーターで指定した任意の順序に並べ替えます。page_order順序付きのページ構文を使用するため、このアクションは抽出と並べ替えを組み合わせた処理としても機能します。指定しなかったページは除外され、2回指定したページは繰り返されます。この API はステートレスです。ドキュメントはリージョン内で処理され、保存されることはありません。

エンドポイント

POST
/v1/reorder_pages

すべてのリージョンで利用できます。ルーティングとデータレジデンシーについては、リージョンとデータレジデンシーを参照してください。

リージョン URL
グローバル https://api.pdfblocks.com/v1/reorder_pages
日本 https://jp.api.pdfblocks.com/v1/reorder_pages
米国 https://us.api.pdfblocks.com/v1/reorder_pages
HIPAA 米国 https://hipaa.api.pdfblocks.com/v1/reorder_pages
欧州連合 https://eu.api.pdfblocks.com/v1/reorder_pages
英国 https://uk.api.pdfblocks.com/v1/reorder_pages
カナダ https://ca.api.pdfblocks.com/v1/reorder_pages
オーストラリア https://au.api.pdfblocks.com/v1/reorder_pages
インド https://in.api.pdfblocks.com/v1/reorder_pages
ブラジル https://br.api.pdfblocks.com/v1/reorder_pages

認証

すべてのリクエストは、X-API-Key ヘッダーにシークレット API キーを設定し、HTTPS 経由で認証してください。キーの作成と管理はダッシュボードから行えます。詳細は認証を参照してください。

リクエスト

このエンドポイントは multipart/form-data 形式のリクエストボディを受け付けます。

filefilerequired

入力 PDF ドキュメントです。

page_orderstringrequired

希望するページの順序を、順序付きのページ構文3,1,2 のように指定します。指定しなかったページは除外され、複数回指定したページは繰り返されます。最大1000文字です。

ページの順序

page_order集合ではなく順序付きリストとして読み取られます。ページは指定したとおりの順序でそのまま出力されます。2回指定したページは2回出力され、指定しなかったページは除外されます。範囲は逆方向に指定することもでき、10..5 はページ10からページ5まで下る形になります。

番号は1から始まり、負のインデックスは末尾から数えます。したがって -1 は最後のページを指します。

page_order 結果
3,1,2 ページ3、1、2の順
2.. ページ2から最後まで、順番どおり
-1,1..-2 最後のページ、続いてそれより前のすべてのページ
1,1,2.. ページ1を2回、続いてページ2以降
10..5 ページ10からページ5まで、逆順

順序付きの page_order と集合ベースの pages フィールドの違いを含め、完全なリファレンスについてはページの選択を参照してください。

ページ3を先頭にし、続けてページ1と2を配置します。

cURLbash
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='3,1,2' \
  -o reordered.pdf
Pythonpython
# pip install requests
import requests

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

response.raise_for_status()
with open('reordered.pdf', 'wb') as output:
    output.write(response.content)
Node.jsjavascript
// 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('page_order', '3,1,2');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('reordered.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/reorder_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'),
        'page_order' => '3,1,2',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('reordered.pdf', $pdf);
}
Rubyruby
# gem install http
require 'http'

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

File.write('reordered.pdf', response.body) if response.status.success?
Gogo
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("page_order", "3,1,2")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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("reordered.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
C#csharp
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,2"), "page_order" },
};

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

レスポンス

成功すると、レスポンスは 200 OK となり、ボディに並べ替えられた PDF が入ります。

HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 39184

上記の例のように、ボディを直接ファイルへストリーミングしてください。当社側には何も保存されません。

エラー

失敗したリクエストは application/problem+json 形式のボディを返します。このエンドポイントで最も多いのは 400 で、page_order の形式が不正な場合や、ドキュメントに存在しないページを指定した場合に返されます。errors オブジェクトには、該当するフィールドが示されます。

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

X-API-Key が存在しないか無効な場合は 401 が返されます。ステータスコードとレスポンスの完全な形式については、エラーを参照してください。

バリエーション

よく使われるバリエーションです。展開すると、各言語での実装を確認できます。

最後のページを先頭に移動
cURLbash
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='-1,1..-2' \
  -o last-first.pdf
Pythonpython
import requests

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

response.raise_for_status()
with open('last-first.pdf', 'wb') as output:
    output.write(response.content)
Node.jsjavascript
import { readFile, writeFile } from 'node:fs/promises';

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

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('last-first.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/reorder_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'),
        'page_order' => '-1,1..-2',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('last-first.pdf', $pdf);
}
Rubyruby
require 'http'

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

File.write('last-first.pdf', response.body) if response.status.success?
Gogo
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("page_order", "-1,1..-2")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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-first.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
C#csharp
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,1..-2"), "page_order" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/reorder_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "last-first.pdf", await response.Content.ReadAsByteArrayAsync());
表紙ページを複製
cURLbash
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='1,1..-1' \
  -o doubled-cover.pdf
Pythonpython
import requests

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

response.raise_for_status()
with open('doubled-cover.pdf', 'wb') as output:
    output.write(response.content)
Node.jsjavascript
import { readFile, writeFile } from 'node:fs/promises';

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

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('doubled-cover.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/reorder_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'),
        'page_order' => '1,1..-1',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('doubled-cover.pdf', $pdf);
}
Rubyruby
require 'http'

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

File.write('doubled-cover.pdf', response.body) if response.status.success?
Gogo
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("page_order", "1,1..-1")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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("doubled-cover.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
C#csharp
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,1..-1"), "page_order" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/reorder_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "doubled-cover.pdf", await response.Content.ReadAsByteArrayAsync());

関連アクション