Skip to Content
NexPDF

Real-time collaboration

Keep several copies of a PDF in step with NexPDF Sync and the NexPdfSync client over WebSocket or Server-Sent Events, push and receive changes to pages, annotations, comments, form values and bookmarks, show who else is in the document, with NexPDF for the web.

English

License module

Sync needs the annotations module (Indie tier and above).

NexPDF Sync lets several copies of one PDF (the browser viewer, apps, a server) edit the same document at the same time and converge. Copies exchange records with stable ids, not whole files:

Record typeWhatid
pageOne page: its dictionary and its place in the documentStored on the page
annotationAn annotation that is not a replyIts /NM
commentA reply in a comment threadIts /NM
fieldThe value of a form fieldfield:<full name>
bookmarkOne outline itemIts /NM
objectA shared object: an appearance stream, font, image or content streamobj:<hash> of its content

Page operations sync: inserting, deleting, moving, rotating and cropping pages and editing their content merge into one page order on every copy, and /Dest destinations follow their page. An object record is sent once, however many records use it, and a copy that already holds the same object uses its own: shared, not copied. Change sets have the format nexpdf-sync/2; format 1 is still read.

Edits made with any other call are picked up automatically: every export and apply first finds the records that were added, changed or removed since the last sync. The sync state is saved in the PDF, so a reopened file continues where it left off.

The sync client

NexPdfSync from @nexdevit/nexpdf-web/sync connects a document to a NexPDF WebViewer server (see The sync server). It streams the others' changes into your document, pushes yours about once a second, reconnects on its own and tells you who else is there.

It talks WebSocket (/api/sync/ws) first. If the socket never reaches the server's hello (a proxy that does not pass upgrades, a refused token), it switches to Server-Sent Events plus POST for the rest of the session. transport: 'websocket' or 'sse' forces one.

import { loadNexPdf } from '@nexdevit/nexpdf-web/engine';
import { NexPdfSync } from '@nexdevit/nexpdf-web/sync';

const nex = await loadNexPdf();
const base = 'https://pdf.example.com/s/8f3c2a';          // the server, or a session URL

// Every copy starts from the server's document.
const res = await fetch(`${base}/api/sync/document`, { headers: { Authorization: `Bearer ${token}` } });
let doc = nex.PdfDocument.fromBytes(new Uint8Array(await res.arrayBuffer()));

const sync = new NexPdfSync(doc, {
  url: base,
  token,                                  // omit it when the page holds the session cookie
  name: 'Ana Silva',
  color: '#2563EB',
  since: Number(res.headers.get('X-Sync-Seq')) || 0,
});

sync.on('remote', (report) => redrawPages());            // other people's changes were applied
sync.on('presence', (peers) => showCursors(peers));
sync.on('status', (status) => showBadge(status));        // connecting, online, offline, closed
sync.on('error', (e) => console.warn('sync', e));

await sync.connect();                                    // resolves when the server says hello

doc.addAnnotation({ page: 0, kind: 'Highlight', color: '#FFD400', rect: [72, 700, 300, 716] });
await sync.flush();                                      // or let the timer push it

new NexPdfSync(doc, options) takes a PdfDocument (or its doc.raw) and sets the document's client id at once.

Options

OptionDefaultMeaning
urlrequiredServer base URL: https://host (local mode) or https://host/s/<session id>
clientIdrandomStable id of this device or tab: 1 to 64 characters of A-Z a-z 0-9 - _ . : @
nameShown to the others (the server uses the token's name when it has one)
color#RRGGBB for this person's cursor and selection
tokenSession token, sent as Authorization: Bearer
since0Server sequence to catch up from (a previous seq); 0 is everything
flushInterval1000How often local edits are looked for and pushed, in ms. 0 pushes only on flush()
reconnectDelay1000First reconnect delay in ms; it doubles up to 30 s
fetchglobalThis.fetchThe fetch to use (tests, proxies)
transportautoauto (WebSocket, else SSE + POST), websocket or sse
WebSocketthe global oneThe WebSocket class to use; null means none, SSE only
credentialsBrowser credentials mode, for example include for a cross-site session cookie

Events

sync.on(event, handler) adds a handler and returns a function that removes it.

EventHandler argumentsWhen
remote(report, changes)A batch from the server was applied. report is the engine's apply report, changes the change set without your own echoes
pushed(result)Your changes were accepted: ok, seq, applied, ignored, conflicts, errors
conflict(conflicts)An apply or push reported conflicts. They are informational: the merge is already decided
presence(peers)The people in the document changed. Each peer has client, name, color, page, cursor ({x, y} in PDF points, or null) and user; you are left out
status(status)connecting, online, offline (waiting to reconnect) or closed
reload(seq)The server's document was replaced: download it again and attach it
error(error)A socket, stream, push or handler failed, or the server sent an error event. The client keeps going unless the server answered 401, 402, 403 or 404

Methods and properties

MemberDoes
connect()Opens the WebSocket (or the event stream) and starts the push timer. Resolves once the server said hello; rejects, and closes the client, when the server answers 401, 402, 403 or 404 (bad token, read-only, unlicensed, no such session). Other failures reconnect with backoff
flush()Pushes the local changes made since the last push, over the socket when it is open. Resolves to the push result, or null when there was nothing to send; throws when the server refuses the push
setPresence({ page, cursor })Shares the page this person is on and a cursor in PDF points (null hides it)
downloadDocument()The server's current document as a Uint8Array, and updates seq from the X-Sync-Seq header
attach(doc)Switches to another document, for example one reopened after reload
close()Stops syncing. Edits not pushed yet stay in the document: call flush() first to send them
clientId, seq, pushedClock, peers, status, transportThis copy's id, the last server sequence seen (pass it as since to resume), the clock of the last successful push, the other people, the connection status, and websocket or sse (null when not connected)

Pushes and applies run one at a time, so a remote batch never lands in the middle of a push.

Presence and reload

canvas.addEventListener('pointermove', (e) => {
  const [x, y] = doc.pageView(page).toPdf(e.offsetX, e.offsetY, scale);
  sync.setPresence({ page, cursor: { x, y } }).catch(() => {});
});

sync.on('reload', async () => {
  const bytes = await sync.downloadDocument();
  doc.close();
  doc = nex.PdfDocument.fromBytes(bytes);
  sync.attach(doc);
  redrawPages();
});

window.addEventListener('pagehide', () => { sync.flush().finally(() => sync.close()); });

Throttle setPresence in a real app; one update every 100 ms or so is plenty. A viewer (read-only) session may stream and send presence, but its pushes are refused: flush() throws and the timer reports error.

Exchange changes

The client is built on five document calls on doc.raw. Use them directly for another transport, or to sync two documents in the same page:

const a = await nex.PdfDocument.fromUrl('/shared.pdf');
const b = await nex.PdfDocument.fromUrl('/shared.pdf');
a.raw.syncSetClientId('alice');
b.raw.syncSetClientId('bob');

a.addAnnotation({ page: 0, kind: 'Highlight', color: '#FFD400', rect: [72, 700, 300, 716] });

const changes = a.raw.syncExportLocalJson(0);           // what alice pushes
const report = JSON.parse(b.raw.syncApplyJson(changes));
console.log(report.applied, report.ignored, report.conflicts);

const since = JSON.parse(changes).clock;                 // pass it next time
CallReturns
syncSetClientId(id)Sets the id this copy versions its changes under (1 to 64 characters of A-Z a-z 0-9 - _ . : @). Random when not set
syncExportLocalJson(since)Only this copy's own changes with a clock above since: what a client sends. Keep the returned clock for the next call
syncExportJson(since)Every change above since, from any client
syncApplyJson(changes)Applies a change set and returns a report
syncSnapshotJson()Every record with its version, base records and tombstones included

Every copy must start from the same file. Records that exist when a document is first synced get the base version and are not sent as changes.

How changes merge

Each record carries a version {"lamport", "client"}, and every property of a record has its own version. On apply, the higher version wins per property (last writer wins): a higher Lamport clock, then the higher client id, so every copy picks the same winner in whatever order changes arrive. Some keys merge as one property: an annotation's geometry, a page's content and resources, a bookmark's parent and order. So Alice changing an annotation's text while Bob moves it keeps both edits; two people changing the same property keep the later one.

When a merge combines properties from different writers, the appearance is redrawn the same way on every copy, for every annotation kind the engine creates. Deletion is a version too: an edit newer than the deletion brings the record back with all its properties.

The apply report has ok, clock, applied and ignored (changes that lost to a newer local version) ids, conflicts (id, winner, local, remote, and the props that met a concurrent edit), which are informational because the merge is already decided, and errors for single records that could not be written. A malformed change set fails as a whole.

The sync server

The NexPDF web viewer server hosts a sync endpoint. Clients download the document, stream the others' changes and push their own:

EndpointUse
GET /api/sync/documentThe PDF to start from (header X-Sync-Seq)
GET /api/sync/ws?since=<seq>&client=<id>&name=&color=WebSocket, subprotocol nexpdf-sync (and bearer.<token> for a token): the stream's events plus pushed and error; the client sends push and presence messages
GET /api/sync/stream?since=<seq>&client=<id>Server-Sent Events: hello, changes, presence, reload
POST /api/sync/pushA change set of the client's own changes
POST /api/sync/presenceName, colour, page and cursor of this client
GET /api/sync/changes?since=<seq>Catch-up as JSON, for polling
GET /api/sync/snapshotEvery record and version

Each request sends X-Client: <client id> and, outside a browser session, a session token as Authorization: Bearer. Viewers may stream; only editors may push. Edits made in the viewer itself, page operations and undo and redo included, reach the other copies as changes from client server. hello reports the transport and the format.

The server appends every accepted record to <data dir>/sync/<key>/changes.jsonl, next to the base document, and a restarted server rebuilds the document from both. The data directory is NEXPDF_DATA_DIR (off, none or memory keep everything in memory), else a per-user folder. A changes batch with reset: true means the server's log restarted and the batch is the full state. The same client runs in Node.js as @nexdevit/nexpdf-node/sync.

Limits

  • Attachments are not records and are not synced.
  • Replacing the document on the server sends reload: download it again and attach it.

On this page