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

PDF からページを抽出する

既存の PDF の一部のページから、新しい PDF を作成します。

PDF から1ページ以上を抽出し、新しいドキュメントを作成します。ページの選択には pages パラメーターを使用します。省略した場合はすべてのページが抽出され、結果は常にドキュメントの順序で並びます。この API はステートレスです。ドキュメントはリージョン内で処理され、保存されることはありません。

エンドポイント

POST
/v1/extract_pages

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

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

認証

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

リクエスト

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

filefilerequired

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

pagesstring

抽出するページを、ページ範囲として 1..3,5 のように指定します。省略した場合はすべてのページが抽出されます。最大1000文字です。

ページの選択

pages パラメーターには、1から始まるページ番号と範囲をカンマ区切りで指定します。これは集合として扱われるため、順序や重複は無視され、抽出されたページは常にドキュメントの順序で並びます。任意の順序にページを並べ替えるには、代わりにページの並べ替えを使用してください。

パターン 選択されるページ
(省略) すべてのページ
1 最初のページのみ
1..3,5 1、2、3、5ページ
2.. 2ページ目から最後まで
..-2 最初のページから、最後から2番目のページまで
-1 最後のページ

完全なリファレンスについては、ページの選択を参照してください。

ページ1〜3と5を新しい PDF に抽出します。

cURLbash
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
Pythonpython
# 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)
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('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()));
PHPphp
<?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);
}
Rubyruby
# 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?
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("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)
}
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..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());

レスポンス

成功すると、レスポンスは 200 OK となり、ボディに抽出された PDF が入ります。

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

出力には選択したページのみが、ドキュメントの順序で含まれます。上記の例のように、ボディを直接ファイルへストリーミングしてください。当社側には何も保存されません。

エラー

失敗したリクエストは application/problem+json 形式のボディを返します。このエンドポイントで最も多いのは 400 で、pages がドキュメントに存在しないページを参照している場合や、file が読み取り可能な PDF でない場合に返されます。errors オブジェクトには、フィールドごとの内容が示されます。

{
  "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."]
  }
}

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

レシピ

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

1ページだけを抽出
cURLbash
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
Pythonpython
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)
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('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()));
PHPphp
<?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);
}
Rubyruby
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?
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("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)
}
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"), "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());
最後の3ページを抽出
cURLbash
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
Pythonpython
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)
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('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()));
PHPphp
<?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);
}
Rubyruby
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?
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("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)
}
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"), "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());

関連アクション