PDF Blocks
PreciosSoporte
Empezar gratis
Ir a la página

Extraer páginas de un PDF

Cree un PDF nuevo a partir de una selección de páginas de uno existente.

Extraiga una o más páginas de un PDF a un documento nuevo. Seleccione las páginas con el parámetro pages: si se omite, se extraen todas, y el resultado siempre las mantiene en el orden del documento. La API es stateless: su documento se procesa en la región y nunca se almacena.

Endpoint

POST
/v1/extract_pages

Disponible 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/extract_pages
Estados Unidos https://us.api.pdfblocks.com/v1/extract_pages
HIPAA de EE. UU. https://hipaa.api.pdfblocks.com/v1/extract_pages
Unión Europea https://eu.api.pdfblocks.com/v1/extract_pages
Reino Unido https://uk.api.pdfblocks.com/v1/extract_pages
Canadá https://ca.api.pdfblocks.com/v1/extract_pages
Australia https://au.api.pdfblocks.com/v1/extract_pages
Japón https://jp.api.pdfblocks.com/v1/extract_pages
India https://in.api.pdfblocks.com/v1/extract_pages
Brasil https://br.api.pdfblocks.com/v1/extract_pages

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.

filefilerequired

El documento PDF de entrada.

pagesstring

Las páginas que se extraerán, escritas como un rango de páginas tipo 1..3,5. Si se omite, se extraen todas las páginas. Máximo 1000 caracteres.

Seleccionar páginas

El parámetro pages recibe una lista separada por comas de números de página en base 1 y de rangos. Se trata como un conjunto: el orden y los duplicados se ignoran, y las páginas extraídas se quedan siempre en el orden del documento. Para reorganizar las páginas en un orden arbitrario, use Reordenar páginas en su lugar.

Patrón Selecciona
(omitir) Todas las páginas
1 Solo la primera página
1..3,5 Las páginas 1, 2, 3 y 5
2.. De la página 2 a la última
..-2 De la primera página a la penúltima
-1 La última página

Consulte Seleccionar páginas para ver la referencia completa.

Ejemplos

Extraiga las páginas 1 a 3 y la 5 a un PDF nuevo:

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

Respuesta

Si todo va bien, la respuesta es 200 OK con el PDF extraído como cuerpo:

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

La salida contiene solo las páginas seleccionadas, en el orden del documento. 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 pages hace referencia a una página que no está en el documento o file no es un PDF legible: el objeto errors nombra cada campo:

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

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.

Extraer una sola página
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());
Extraer las últimas tres páginas
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());

Acciones relacionadas