Skip to Content
NexPDF

Real-time collaboration

Keep several copies of a PDF in step with NexPDF Sync from the Electron main process, export and apply changes to pages, annotations, comments, form values and bookmarks, or connect to a sync server over WebSocket or Server-Sent Events with the Node.js client.

English

License module

Sync needs the annotations module (Indie tier and above), activated for the document API.

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.

Where it runs

  • The sync calls and the client run in the main process: the document calls on doc.raw of the document API, and the NexPdfSync client of the Node.js SDK (see The ready-made client). Electron ships no sync client of its own.
  • The window's engine is a NexPDF WebViewer server on a loopback port (127.0.0.1), so it serves the sync endpoints below for the document it shows, and the window's edits, page operations included, become changes from client server. It is reachable only from this machine.
  • A renderer can run the web SDK's engine and its client, @nexdevit/nexpdf-web/sync, with the renderer's own WebSocket and fetch; see the web collaboration guide.

Exchange changes

const { openDocumentFile } = require('@nexdevit/nexpdf-electron');

const a = await openDocumentFile('shared.pdf');
const b = await openDocumentFile('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.

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 (on macOS ~/Library/Application Support/NexPDF/WebViewer, on Windows %LOCALAPPDATA%\NexPDF\WebViewer). This applies to the window's engine too; pass startEngine({ env: { NEXPDF_DATA_DIR: 'off' } }) to keep its sync state in memory.

The ready-made client

The Node.js SDK's sync client, NexPdfSync from @nexdevit/nexpdf-node/sync, runs this loop for you in the main process: it streams the others' changes into the document, pushes local changes about once a second (or on flush()), shares presence and reconnects with backoff (1 s up to 30 s, never after 401, 402, 403 or 404). It talks WebSocket first, with the main process's global WebSocket (or the WebSocket option), and falls back to Server-Sent Events plus POST for the session when the socket never reaches hello; transport: 'websocket' or 'sse' forces one. It takes a PdfDocument from openDocumentFile (it uses doc.raw). The module is ES-only, so load it with import() from a CommonJS main process:

const { app } = require('electron');
const { PdfDocument } = require('@nexdevit/nexpdf-electron').documents();

const { NexPdfSync } = await import('@nexdevit/nexpdf-node/sync');
const base = 'https://docs.example.com/s/8f3c2a';           // the server session
const res = await fetch(`${base}/api/sync/document`, { headers: { Authorization: `Bearer ${token}` } });
const doc = PdfDocument.fromBytes(new Uint8Array(await res.arrayBuffer()));

const sync = new NexPdfSync(doc, { url: base, name: 'Ana', token, transport: 'auto' });
sync.on('remote', () => refreshMyView());           // your code
sync.on('presence', (peers) => showPeers(peers));
sync.on('status', (status) => console.log('sync', status, sync.transport));
sync.on('reload', () => reopenFromServer());        // download the document again
await sync.connect();
await sync.setPresence({ page: 0, cursor: null });
// after a local edit (or let the timer do it):
await sync.flush();

app.on('before-quit', () => { sync.flush().finally(() => sync.close()); });

See the Node.js collaboration guide for its options, events and methods.

Limits

  • Attachments are not records and are not synced.
  • Replacing the document on the server sends reload: download it again and attach it.
  • A document in the window and a document of the document API are separate copies. To show synced changes in a window, send the document's bytes to it with openDocument.

On this page