Extract a page range into a new PDF
Copies pages in the inclusive [from, to] range (1-based) into a new document.
typescript
import { PDFDocument } from "pdf-lib";
// Extracts an inclusive range (1-based) into a new PDF. E.g. extractPageRange(file, 2, 5)
export async function extractPageRange(file: File, from: number, to: number): Promise<Uint8Array> {
const source = await PDFDocument.load(await file.arrayBuffer(), { ignoreEncryption: true });
const result = await PDFDocument.create();
const indices: number[] = [];
for (let page = from; page <= to; page += 1) {
indices.push(page - 1);
}
const pages = await result.copyPages(source, indices);
pages.forEach((page) => result.addPage(page));
return result.save();
}Dependencias
pdf-libNotas de uso
- from and to are 1-based and inclusive: extractPageRange(file, 2, 5) returns pages 2 through 5.
- To download, wrap the bytes in a Blob of type application/pdf.
Limitaciones
- Returns a single PDF. For multiple outputs in a ZIP, combine this with the jszip library.
- An encrypted PDF may not load.