Real-time collaboration
Keep several copies of a PDF in step with NexPDF Sync and the NexPdfSync client, annotations, comments, form values, bookmarks and pages, with per-property last-writer-wins merging, presence and reconnection, with NexPDF for React Native.
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 type | What | id |
|---|---|---|
page | One page: its dictionary and its place in the document | Stored on the page |
annotation | An annotation that is not a reply | Its /NM |
comment | A reply in a comment thread | Its /NM |
field | The value of a form field | field:<full name> |
bookmark | One outline item | Its /NM |
object | A shared object: an appearance stream, font, image or content stream | obj:<hash> of its content |
Page operations sync too: inserting, deleting, moving and rotating pages, cropping them and
editing their content. Every copy ends with the same page order, 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 (a font of the base file, for example) uses its own: shared, not copied.
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. Change sets use the format nexpdf-sync/2;
format 1 change sets are still read.
The React Native package has two levels: the sync… methods of a document, which work without a
network, and NexPdfSync, a ready-made client for the NexPDF web viewer server.
The NexPdfSync client
NexPdfSync connects a document to a sync server: it receives the others' changes and applies
them, pushes your edits about once a second, shares presence and reconnects by itself. It talks
WebSocket (/api/sync/ws, React Native's WebSocket) and falls back to Server-Sent Events, read
through XMLHttpRequest, plus POST when the socket cannot be opened.
Every copy must start from the same file, so download the server's document first. The client can be created without a document for that:
import { NexPdf, NexPdfSync } from '@nexdevit/nexpdf-react-native';
const base = 'https://viewer.example.com/s/3f9c2a'; // a viewer session
const token = 'nxt_…'; // the session token
const sync = new NexPdfSync(null, { url: base, token, name: 'Ana', color: '#2563EB' });
const doc = await NexPdf.open(await sync.downloadDocument()); // base64; sets sync.seq
await sync.attach(doc);
sync.on('remote', (report, changes) => redraw()); // others' changes are in `doc`
sync.on('presence', (peers) => showCursors(peers));
sync.on('status', (status) => setStatus(status));
sync.on('error', (e) => console.warn('sync', e));
await sync.connect(); // resolves once the server said hello
// later, after a local edit (or let flushInterval push it):
await sync.run(() => doc.addHighlight(0, [72, 700, 300, 716]));
await sync.flush();
await sync.setPresence({ page: 0, cursor: { x: 100, y: 200 } });on(event, handler) returns a function that removes the handler. Any object with
syncSetClientId, syncExportLocalJson and syncApplyJson (the SyncEngine interface) can be the
engine; a document from NexPdf.open is one.
Options
| Option | Default | Meaning |
|---|---|---|
url | required | The server URL, or a viewer session URL https://host/s/<id> |
clientId | a random UUID | Stable id of this device: 1 to 64 characters of A-Z a-z 0-9 - _ . : @ |
name | The person's name, shown to the others | |
color | #RRGGBB, the colour of this person's cursor | |
token | Session token, sent as Authorization: Bearer (and the bearer.<token> subprotocol) | |
since | 0 | Server sequence to catch up from: the seq after downloadDocument(), or a saved seq. 0 replays everything |
flushInterval | 1000 | Milliseconds between automatic pushes of local edits. 0 pushes only on flush() |
reconnectDelay | 1000 | First reconnect delay in milliseconds. It doubles up to 30 seconds |
transport | 'auto' | 'auto' (WebSocket, else Server-Sent Events plus POST), 'websocket' or 'sse' |
WebSocket, XMLHttpRequest, fetch | the global ones | Replacements for the networking classes; WebSocket: null uses Server-Sent Events only |
Events
| Event | Handler gets |
|---|---|
remote | The engine's apply report and the change set applied (own echoes removed) |
pushed | The server's answer to a push (seq, applied, ignored, conflicts) |
conflict | The conflicts of an apply or a push, when there are any |
presence | The other people connected, as SyncPeer[] (client, name, color, page, cursor in PDF points or null, user) |
status | 'connecting', 'online', 'offline' or 'closed' |
reload | The new seq after the server's document was replaced |
error | Network and engine errors. The client keeps running unless it closed itself |
Methods and state
| Member | Does |
|---|---|
connect() | Opens the connection and starts the push timer; resolves once the server said hello |
flush() | Pushes the local edits made since the last push and resolves to the server's answer, or null when there was nothing to push |
setPresence({ page, cursor }) | Shares the page this person is on and, optionally, a cursor in PDF points |
run(fn) | Runs fn between the client's own engine calls (pushes and applies never interleave) |
downloadDocument() | The server's current PDF as base64; also sets seq from X-Sync-Seq |
attach(doc) | Switches to another document, for example the one reopened after reload |
close() | Stops syncing. Local edits not yet pushed stay in the document; call flush() first |
handleEvent(event, data) | Handles one server event, for custom transports |
clientId, seq, pushedClock, status, peers, transport | State. Save seq to resume later with since |
When the server replaces the document, reopen it and attach it:
sync.on('reload', async () => {
const fresh = await NexPdf.open(await sync.downloadDocument());
await sync.attach(fresh);
show(fresh);
});Reconnection
With 'auto' the client opens the WebSocket first. If the socket never reaches hello (a proxy
that does not pass upgrades, for example), it switches to Server-Sent Events plus POST for the rest
of the session; pushes and presence go over the socket while it is open. When the connection drops,
the status becomes 'offline' and the client reconnects after reconnectDelay, doubling the delay
up to 30 seconds, and resumes from the last seq. It stops for good when the server answers 401
(bad token), 402 (unlicensed), 403 (read-only or not allowed) or 404 (no such session). Changes the
client pushed itself come back and are skipped.
The reader does not connect to a sync server by itself: open the
document, start NexPdfSync, and redraw on remote.
Exchange changes without a server
The sync… methods move change sets between copies any way you like (files, your own backend,
peer-to-peer):
import { NexPdf } from '@nexdevit/nexpdf-react-native';
const a = await NexPdf.open(sharedBase64);
const b = await NexPdf.open(sharedBase64);
await a.syncSetClientId('alice');
await b.syncSetClientId('bob');
await a.addAnnotation(0, 'Highlight', '#FFD400', 1, '', 72, 700, 300, 716);
const changes = await a.syncExportLocalJson(0); // what alice pushes
const report = JSON.parse(await b.syncApplyJson(changes));
console.log(report.applied, report.ignored, report.conflicts);
const since = JSON.parse(changes).clock; // pass it next time| Call | Resolves to |
|---|---|
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 version is {"lamport", "client"}, ordered by the Lamport clock and then by the client id, so
every copy picks the same winner in whatever order changes arrive. Every property of a record has
its own version, and the merge is last writer wins per property. A few keys that only make sense
together are one property: an annotation's geometry (Rect, QuadPoints, InkList, Vertices
and the like), a page's Contents and Resources, and 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. A page rotated by one person and cropped by another keeps both. After a merge that mixes 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. A delete followed by an older edit stays deleted; an edit newer than the delete brings the record back with all its properties.
The apply report has ok, clock, applied and ignored (changes that brought nothing newer)
ids, conflicts (id, winner, local, remote and props, the properties where your own
edit met a concurrent one), 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, and the promise rejects with NexPdfError.
The sync server
The NexPDF web viewer server hosts the sync endpoints the client talks to:
| Endpoint | Use |
|---|---|
GET /api/sync/document | The PDF to start from (header X-Sync-Seq) |
GET /api/sync/ws?since=<seq>&client=<id>&name=…&color=… | WebSocket, subprotocol nexpdf-sync (and optionally bearer.<token>): the events below plus pushed and error; the client sends push and presence messages on it |
GET /api/sync/stream?since=<seq>&client=<id> | Server-Sent Events: hello, changes, presence, reload |
POST /api/sync/push | A change set of the client's own changes |
POST /api/sync/presence | Name, colour, page and cursor of this client |
GET /api/sync/changes?since=<seq> | Catch-up as JSON, for polling |
GET /api/sync/snapshot | Every record and version |
Each request sends X-Client: <client id> and, outside a browser session, a session token as
Authorization: Bearer. Viewers may connect and send presence; only editors may push. hello
reports the transport and the change-set format. A changes batch with reset: true means the
server's log restarted and the batch is the full state.
Edits made in the browser viewer, page operations and undo and redo included, become changes too.
The server appends every accepted record to <data dir>/sync/<key>/changes.jsonl next to
base.pdf, and a restarted server rebuilds the document from both. The data directory is
NEXPDF_DATA_DIR (off, none or memory keeps everything in memory), else
~/Library/Application Support/NexPDF/WebViewer on macOS, %LOCALAPPDATA%\NexPDF\WebViewer on
Windows and $XDG_DATA_HOME/nexpdf/webviewer elsewhere.
Every NexPDF SDK has a client for the same protocol, for example the Web, Node.js, iOS, Android and Flutter SDKs, so all of them can edit one document together.
Limits
- Attachments are not records and are not synced; replacing the document on the server sends
reload. - Local edits are pushed on the flush interval or on
flush(), not instantly.