Skip to Content
NexPDF

Editing pages and documents

Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images with NexPDF for Node.js.

English

License module

Page and content editing needs the editor module (Startup tier and above). Inserting pictures as pages needs no module.

Page indices start at 0. Save with await doc.save(path), get the bytes with doc.toBytes(), or use doc.raw.saveLinearized() for a "Fast Web View" file.

Merge and split

import { PdfDocument } from '@nexdevit/nexpdf-node';

const a = await PdfDocument.open('a.pdf');
const b = await PdfDocument.open('b.pdf');
a.merge(b);                                 // a now has the pages of a, then b
await a.save('merged.pdf');

const firstThree = a.extractPages([0, 1, 2]);
await firstThree.save('part1.pdf');

Insert, duplicate, delete and reorder

import { readFile } from 'node:fs/promises';

doc.raw.addBlankPage();               // appends a blank page
doc.raw.duplicatePage(0);             // inserts a copy of page 0 after it
doc.raw.movePage(3, 0);               // moves page 3 to the front
doc.deletePage(5);
doc.raw.reversePages();

doc.raw.insertImagePages(2, await readFile('scan.jpg'));   // one page per picture, before page 2

Rotate and crop

doc.rotatePage(0, 90);                        // multiples of 90 degrees
doc.raw.cropPage(1, 36, 36, 576, 756);        // new crop box in PDF points

Page backgrounds

doc.setBackground({ color: '#fbf4e2', pages: [] });   // every page
doc.removeBackground();

Pass a picture as RGB pixels (width x height x 3 bytes), setBackground(options, { rgb, width, height }), and fit (cover, stretch or center), scale and opacity in the options.

Edit page text and images

doc.raw.pageContentJson(page) lists the text lines and images of a page with an id for each:

const items = JSON.parse(doc.raw.pageContentJson(0));
const line = items.find((i) => i.kind === 'text' && i.text.includes('Draft'));

doc.raw.editText(0, line.id, JSON.stringify({ text: 'Final', color: '#111827' }));
doc.raw.addPageText(0, JSON.stringify({ text: 'Approved', x: 72, y: 60, size: 14, color: '#16A34A', bold: true }));

Ids stay valid until the next edit of that page, so read the content again after each change. For images use transformImage(page, id, llx, lly, urx, ury) to move or resize, replaceImage(page, id, rgb, width, height) to swap the picture and deleteContent(page, id) to remove it, all on doc.raw.

On this page