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

PDF ドキュメントを結合する

複数の PDF ドキュメントを、指定した順序で1つに結合します。

複数の PDF ドキュメントを1つに結合します。ファイルはリクエスト内に現れる順序どおりに結合されるため、最終的なページの並び順を自分で制御できます。1回の呼び出しで必要な数だけファイルを指定できます。API はステートレスです。ドキュメントはリージョン内で処理され、保存されることはありません。

エンドポイント

POST
/v1/merge_documents

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

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

認証

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

リクエスト

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

filefile[]required

入力となる PDF ドキュメントを、file パートを繰り返し送信する形で指定します。少なくとも1つは指定してください。1回のリクエストで必要な数だけファイルを指定できます。ドキュメントは、パートがリクエスト内に現れる順序どおりに結合されます。複数の file パートを送信する方法については、ファイルの操作を参照してください。

3つの PDF を順序どおりに1つに結合します:

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

files = [
    ('file', open('chapter-1.pdf', 'rb')),
    ('file', open('chapter-2.pdf', 'rb')),
    ('file', open('chapter-3.pdf', 'rb')),
]

response = requests.post(
    'https://api.pdfblocks.com/v1/merge_documents',
    headers={'X-API-Key': 'your_api_key'},
    files=files,
)

response.raise_for_status()
with open('merged.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.append('file', new Blob([await readFile('chapter-1.pdf')]), 'chapter-1.pdf');
body.append('file', new Blob([await readFile('chapter-2.pdf')]), 'chapter-2.pdf');
body.append('file', new Blob([await readFile('chapter-3.pdf')]), 'chapter-3.pdf');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('merged.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
// composer require guzzlehttp/guzzle
require 'vendor/autoload.php';

use GuzzleHttp\Client;

// Repeat the `file` part once per document: they merge in the order sent.
$response = (new Client())->post('https://api.pdfblocks.com/v1/merge_documents', [
    'headers' => ['X-API-Key' => 'your_api_key'],
    'multipart' => [
        ['name' => 'file', 'contents' => fopen('chapter-1.pdf', 'r'), 'filename' => 'chapter-1.pdf'],
        ['name' => 'file', 'contents' => fopen('chapter-2.pdf', 'r'), 'filename' => 'chapter-2.pdf'],
        ['name' => 'file', 'contents' => fopen('chapter-3.pdf', 'r'), 'filename' => 'chapter-3.pdf'],
    ],
]);

if ($response->getStatusCode() === 200) {
    file_put_contents('merged.pdf', $response->getBody());
}
Rubyruby
# gem install http
require 'http'

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

File.write('merged.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)

	for _, name := range []string{"chapter-1.pdf", "chapter-2.pdf", "chapter-3.pdf"} {
		file, _ := os.Open(name)
		part, _ := form.CreateFormFile("file", name)
		io.Copy(part, file)
		file.Close()
	}
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/merge_documents", &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("merged.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("chapter-1.pdf")), "file", "chapter-1.pdf" },
    { new ByteArrayContent(File.ReadAllBytes("chapter-2.pdf")), "file", "chapter-2.pdf" },
    { new ByteArrayContent(File.ReadAllBytes("chapter-3.pdf")), "file", "chapter-3.pdf" },
};

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

レスポンス

処理に成功すると、レスポンスは 200 OK となり、結合された PDF を本文として返します:

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

出力は1つの PDF で、ページ数は入力ファイルのページ数の合計になり、リクエスト順に並びます。上記の例のように、レスポンスの本文はそのままファイルへストリーム保存してください。こちら側には何も保存されません。

エラー

リクエストが失敗すると、application/problem+json 形式のレスポンスボディが返されます。このエンドポイントで最も多いのは 400 で、いずれかの file パートが読み取り可能な PDF でない場合に返されます。errors オブジェクトには対象のフィールド名が含まれます:

{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "file": ["Could not parse the PDF document. The file may be invalid or corrupt."]
  }
}

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

レシピ

よくあるバリエーションをまとめています。項目を開くと、各言語のコード例を確認できます。

レポートの先頭に表紙を追加する
cURLbash
curl https://api.pdfblocks.com/v1/merge_documents \
  -H 'X-API-Key: your_api_key' \
  -F file=@cover.pdf \
  -F file=@report.pdf \
  -o report-with-cover.pdf
Pythonpython
import requests

files = [
    ('file', open('cover.pdf', 'rb')),
    ('file', open('report.pdf', 'rb')),
]

response = requests.post(
    'https://api.pdfblocks.com/v1/merge_documents',
    headers={'X-API-Key': 'your_api_key'},
    files=files,
)

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

const body = new FormData();
body.append('file', new Blob([await readFile('cover.pdf')]), 'cover.pdf');
body.append('file', new Blob([await readFile('report.pdf')]), 'report.pdf');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('report-with-cover.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
// composer require guzzlehttp/guzzle
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$response = (new Client())->post('https://api.pdfblocks.com/v1/merge_documents', [
    'headers' => ['X-API-Key' => 'your_api_key'],
    'multipart' => [
        ['name' => 'file', 'contents' => fopen('cover.pdf', 'r'), 'filename' => 'cover.pdf'],
        ['name' => 'file', 'contents' => fopen('report.pdf', 'r'), 'filename' => 'report.pdf'],
    ],
]);

if ($response->getStatusCode() === 200) {
    file_put_contents('report-with-cover.pdf', $response->getBody());
}
Rubyruby
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/merge_documents', form: {
    file: [
      HTTP::FormData::File.new('cover.pdf'),
      HTTP::FormData::File.new('report.pdf'),
    ],
  })

File.write('report-with-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)

	for _, name := range []string{"cover.pdf", "report.pdf"} {
		file, _ := os.Open(name)
		part, _ := form.CreateFormFile("file", name)
		io.Copy(part, file)
		file.Close()
	}
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/merge_documents", &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("report-with-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("cover.pdf")), "file", "cover.pdf" },
    { new ByteArrayContent(File.ReadAllBytes("report.pdf")), "file", "report.pdf" },
};

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

関連アクション