Unir documentos PDF
Combine varios documentos PDF en uno solo, en el orden en que los envíe.
Combine varios documentos PDF en uno solo. Los archivos se unen exactamente en el orden en que aparecen en la solicitud, de modo que usted controla la secuencia final de páginas: envíe tantos archivos como necesite en una sola llamada. La API es stateless: su documento se procesa en la región y nunca se almacena.
Endpoint
/v1/merge_documentsDisponible en todas las regiones. Consulte Regiones y residencia de datos para el enrutamiento y la residencia de datos.
| Región | URL |
|---|---|
| Global | https://api.pdfblocks.com/v1/merge_documents |
| Estados Unidos | https://us.api.pdfblocks.com/v1/merge_documents |
| HIPAA de EE. UU. | https://hipaa.api.pdfblocks.com/v1/merge_documents |
| Unión Europea | https://eu.api.pdfblocks.com/v1/merge_documents |
| Reino Unido | https://uk.api.pdfblocks.com/v1/merge_documents |
| Canadá | https://ca.api.pdfblocks.com/v1/merge_documents |
| Australia | https://au.api.pdfblocks.com/v1/merge_documents |
| Japón | https://jp.api.pdfblocks.com/v1/merge_documents |
| India | https://in.api.pdfblocks.com/v1/merge_documents |
| Brasil | https://br.api.pdfblocks.com/v1/merge_documents |
Autenticación
Autentique cada solicitud con su clave de API secreta en la cabecera
X-API-Key, por HTTPS. Cree y administre sus claves desde el
dashboard. Consulte
Autenticación para más detalles.
Solicitud
El endpoint acepta un cuerpo de solicitud multipart/form-data.
filefile[]requiredLos documentos PDF de entrada, enviados como partes file repetidas. Envíe
al menos una; puede enviar tantos archivos como necesite en una sola
solicitud. Los documentos se unen exactamente en el orden en que las partes
aparecen en la solicitud. Consulte Trabajar con
archivos para ver cómo enviar varias partes
file.
Ejemplos
Una tres PDFs en uno solo, en orden:
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# 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.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()));<?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());
}# 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?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)
}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());Respuesta
Si todo va bien, la respuesta es 200 OK con el PDF unido como cuerpo:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 96124El resultado es un único PDF cuyo número de páginas es la suma de las de los documentos de entrada, en el orden de la solicitud. Escriba el cuerpo directamente en un archivo, como hacen los ejemplos anteriores; en nuestro lado no se almacena nada.
Errores
Las solicitudes fallidas devuelven un cuerpo application/problem+json. El
error más habitual en este endpoint es un 400, que se devuelve cuando
alguna de las partes file no es un PDF legible. El objeto errors indica
el campo:
{
"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."]
}
}Una X-API-Key ausente o no válida devuelve un 401. Consulte
Errores para ver todos los códigos de estado y la forma
completa de la respuesta.
Recetas
Variantes habituales. Despliegue una para verla en todos los lenguajes.
Anteponer una portada a un informe
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.pdfimport 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)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()));<?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());
}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?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)
}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());