X Enterprises
fastify-xpdf

extractPages

Extract specific pages from a PDF into a new document using pdf-lib. Pages are zero-indexed.

extractPages

Extract specific pages from a PDF into a new document using pdf-lib. Pages are zero-indexed (page 1 = index 0).

Signature

fastify.xPDF.extractPages(
  pdfBuffer: Buffer,
  pageIndices: number[],
  options?: ExtractOptions,
): Promise<MergeResult>

interface ExtractOptions {
  filename?: string
  saveToStorage?: boolean
  folder?: string
}

// Returns same shape as mergePDFs
interface MergeResult {
  buffer: Buffer
  filename: string
  size: number
  pageCount: number   // number of pages extracted
  storageKey?: string
  url?: string
}

Params

NameTypeRequiredDescription
pdfBufferBufferYesSource PDF buffer
pageIndicesnumber[]YesZero-based page indices to extract, in desired output order
options.filenamestringNoOutput filename
options.saveToStoragebooleanNoUpload result to xStorage
options.folderstringNoStorage folder override

Returns

MergeResult — includes pageCount (number of pages in the extracted document).

Throws

ErrorWhen
[xPDF] Invalid PDF bufferpdfBuffer doesn't start with %PDF
[xPDF] pageIndices must be a non-empty array...pageIndices is empty, null, or not an array
[xPDF] Each page index must be a non-negative integerAny index is not a non-negative integer
[xPDF] Page index N out of range...Any index ≥ document page count

Examples

Extract the first and last pages of a contract

fastify.get("/contracts/:id/summary", async (request, reply) => {
  const pdfBuffer = await fetchContractBuffer(request.params.id);
  const count = await fastify.xPDF.getPageCount(pdfBuffer);

  // Extract page 1 (index 0) and the last page
  const { buffer } = await fastify.xPDF.extractPages(
    pdfBuffer,
    [0, count - 1],
    { filename: `contract-${request.params.id}-summary.pdf` },
  );

  return reply
    .header("Content-Type", "application/pdf")
    .header("Content-Disposition", `attachment; filename="summary.pdf"`)
    .send(buffer);
});

Reorder pages — build a custom page order

// Original: pages 1-5 (indices 0-4)
// Desired output order: page 3, page 1, page 5 (indices 2, 0, 4)
const { buffer, pageCount } = await fastify.xPDF.extractPages(
  sourcePdf,
  [2, 0, 4],
);
console.log(pageCount); // 3

See Also

AI Context

package: "@xenterprises/fastify-xpdf"
method: fastify.xPDF.extractPages(pdfBuffer, pageIndices, options?)
use-when: Extract specific pages from a PDF into a new document using pdf-lib (0-indexed)
params: pdfBuffer (Buffer), pageIndices (number[]), options ({ saveToStorage })
returns: { buffer, size, pageCount }
Copyright © 2026