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 Flutter.
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 Flutter plugin has two levels: the sync… methods of NexPdfDocument, which work without a
network, and NexPdfSync (in nexpdf_sync.dart, exported by nexpdf_flutter.dart), 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, with dart:io) and falls back to Server-Sent Events plus POST when the
socket cannot be opened.
Every copy must start from the same file, so download the server's document first. A client
built on NexPdfSyncEngine.none can download before any document is open:
import 'package:nexpdf_flutter/nexpdf_flutter.dart';
const base = 'https://viewer.example.com/s/3f9c2a'; // a viewer session
const token = 'nxt_…'; // the session token
final dl = NexPdfSync(NexPdfSyncEngine.none, const NexPdfSyncOptions(url: base, token: token));
final doc = sdk.open(await dl.downloadDocument()); // also sets dl.seq from X-Sync-Seq
dl.dispose();
final sync = NexPdfSync(NexPdfSyncEngine.document(doc),
NexPdfSyncOptions(url: base, token: token, name: 'Ana', color: '#2563EB', since: dl.seq));
sync.onRemote.listen((r) => redraw()); // others' changes are in `doc`
sync.onPresence.listen(showCursors);
sync.onStatus.listen((s) => print('sync: ${s.name}'));
sync.onError.listen((e) => print('sync error: $e'));
await sync.connect(); // completes once the server said hello
// later, after a local edit (or let flushInterval push it):
await sync.run(() => doc.replyToAnnotation(0, num, 0, author: 'Ana', text: 'OK'));
await sync.flush();
await sync.setPresence(0, (x: 100, y: 200));The constructor sets the document's client id. Any NexPdfSyncEngine (syncSetClientId,
syncExportLocalJson, syncApplyJson) can be the engine; NexPdfSyncEngine.document(doc) wraps a
NexPdfDocument.
Options
NexPdfSyncOptions({required url, clientId, name, color, token, since, flushInterval, reconnectDelay, transport}):
| 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 | null | The person's name, shown to the others |
color | null | #RRGGBB, the colour of this person's cursor |
token | null | 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 | 1 second | How often local edits are pushed. Duration.zero pushes only on flush() |
reconnectDelay | 1 second | First reconnect delay. It doubles up to 30 seconds |
transport | NexPdfSyncTransport.auto | auto (WebSocket, else Server-Sent Events plus POST), websocket or sse |
Streams
| Stream | Emits |
|---|---|
onRemote | NexPdfSyncRemote: the engine's apply report and the changes applied (own echoes removed) |
onPushed | The server's answer to a push (seq, applied, ignored, conflicts) |
onConflict | The conflicts of an apply or a push, when there are any |
onPresence | The other people connected, as List<NexPdfSyncPeer> (client, name, color, page, cursor in PDF points or null, user) |
onStatus | NexPdfSyncStatus: connecting, online, offline or closed |
onReload | The new seq after the server's document was replaced |
onError | Network and engine errors. NexPdfSyncException has the HTTP status when there was one |
Methods and state
| Member | Does |
|---|---|
connect() | Opens the connection and starts the push timer; completes once the server said hello |
flush() | Pushes the local edits made since the last push and returns 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 in the client's engine queue, between pushes and applies |
downloadDocument() | The server's current PDF as Uint8List; also sets seq from X-Sync-Seq |
attach(engine) | Switches to another document, for example the one reopened after onReload |
close() | Stops syncing. Local edits not yet pushed stay in the document; call flush() first. The client can connect() again |
dispose() | close(), and frees the HTTP client and the streams |
handleEvent(event, data) | Handles one server event, for custom transports |
clientId, seq, pushedClock, status, transport | State. Save seq to resume later with since |
When the server replaces the document, reopen it and attach it:
sync.onReload.listen((_) async {
final fresh = sdk.open(await sync.downloadDocument());
sync.attach(NexPdfSyncEngine.document(fresh));
show(fresh);
});Isolates and reconnection
Pushes and remote applies run one at a time through a queue, so the document is never used by two
of them at once. Make your own edits between awaits (the isolate is single threaded) or inside
run.
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. 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 the pages on onRemote.
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 'dart:io';
import 'package:nexpdf_flutter/nexpdf_flutter.dart';
final bytes = await File(sharedPath).readAsBytes();
final a = sdk.open(bytes), b = sdk.open(bytes);
a.syncSetClientId('alice');
b.syncSetClientId('bob');
// ... alice adds an annotation (see Annotations) ...
final changes = a.syncExportLocal(); // what alice pushes
final report = b.syncApply(changes);
print('${report['applied']} ${report['ignored']} ${report['conflicts']}');
final since = changes['clock'] as int; // pass it next time: syncExportLocal(sinceVersion: since)| Call | Returns |
|---|---|
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 |
syncExportLocal(sinceVersion: ...) | Only this copy's own changes with a clock above sinceVersion (default 0): what a client sends. Keep the returned clock for the next call |
syncExport(sinceVersion: ...) | Every change above sinceVersion, from any client |
syncApply(changes) | Applies a change set (a decoded map or JSON text) and returns a report |
syncSnapshot() | Every record with its version, base records and tombstones included |
The results are decoded maps, and failures throw NexPdfException.
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 call throws NexPdfException.
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 React Native 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.