Reorder pages with an order array
Takes a 1-based array with every page in the new order and returns the reorganized PDF.
typescript
import { PDFDocument } from "pdf-lib";
// order: 1-based array with EVERY page in the new order, e.g. [3, 1, 2]
export async function reorderPdfPages(file: File, order: number[]): Promise<Uint8Array> {
const source = await PDFDocument.load(await file.arrayBuffer(), { ignoreEncryption: true });
const result = await PDFDocument.create();
const pages = await result.copyPages(source, order.map((n) => n - 1));
pages.forEach((page) => result.addPage(page));
return result.save();
}Dependencias
pdf-libNotas de uso
- order must include every page exactly once. For 3 pages: [3, 1, 2].
- To download, wrap the bytes in a Blob of type application/pdf.
Limitaciones
- If order doesn't cover every page or repeats any, the result will be incorrect: validate first.
- An encrypted or damaged PDF may not be processable.