# 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

<Endpoint method="POST" path="/v1/merge_documents" />

Disponible en todas las regiones. Consulte [Regiones y residencia de
datos](/docs/api/regions-and-data-residency) 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](https://dashboard.pdfblocks.com). Consulte
[Autenticación](/docs/api/authentication) para más detalles.

## Solicitud

El endpoint acepta un cuerpo de solicitud `multipart/form-data`.

<ParamField name="file" type="file[]" required>
  Los 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](/docs/api/working-with-files) para ver cómo enviar varias partes
  `file`.
</ParamField>

## Ejemplos

Una tres PDFs en uno solo, en orden:

<CodeGroup>

```bash title="cURL"
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
```

```python title="Python"
# 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)
```

```javascript title="Node.js"
// 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 title="PHP"
<?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());
}
```

```ruby title="Ruby"
# 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?
```

```go title="Go"
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)
}
```

```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("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());
```

</CodeGroup>

## Respuesta

Si todo va bien, la respuesta es `200 OK` con el PDF unido como cuerpo:

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

El 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:

```json
{
  "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](/docs/api/errors) 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.

<AccordionGroup>

<Accordion title="Anteponer una portada a un informe">

<CodeGroup>

```bash title="cURL"
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
```

```python title="Python"
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)
```

```javascript title="Node.js"
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 title="PHP"
<?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());
}
```

```ruby title="Ruby"
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?
```

```go title="Go"
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)
}
```

```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("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());
```

</CodeGroup>

</Accordion>

</AccordionGroup>

## Acciones relacionadas

<CardGroup cols={2}>

<Card title="Extraer páginas" href="/docs/api/extract-pages-from-pdf">
  Extraiga un subconjunto de páginas del archivo unido.
</Card>

<Card title="Reordenar páginas" href="/docs/api/reorder-pages-of-pdf">
  Reordene las páginas después de unirlas.
</Card>

<Card title="Dividir en una página" href="/docs/api/split-pdf-at-page">
  Vuelva a dividir el documento combinado.
</Card>

<Card title="Añadir una marca de agua de texto" href="/docs/api/add-text-watermark-to-pdf">
  Estampe el documento unido.
</Card>

</CardGroup>
