Real-time collaboration
Keep several copies of a PDF in step with NexPDF Sync and the NexPdfSync client, exchange changes to pages, annotations, comments, form values and bookmarks, with deterministic per-property last-writer-wins merging, with NexPDF for Java.
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: insert, delete, move and reorder, rotate, crop and content edits merge
into the same page order on every copy. /Dest destinations follow their page. A shared object is
sent once, however many records use it, and a copy that already holds it uses its own: shared, not
copied. Change sets use the format nexpdf-sync/2; format 1 change sets are 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.
Exchange changes
ObjectMapper json = new ObjectMapper(); // Jackson, one JSON library among many
try (NexPdfDocument a = NexPdfDocument.open(Path.of("shared.pdf"));
NexPdfDocument b = NexPdfDocument.open(Path.of("shared.pdf"))) {
a.syncSetClientId("alice");
b.syncSetClientId("bob");
a.addAnnotation(0, "Highlight", "#FFD400", 1.0, "", 72, 700, 300, 716);
String changes = a.syncExportLocalJson(0); // what alice pushes
JsonNode report = json.readTree(b.syncApplyJson(changes));
System.out.println(report.get("applied") + " " + report.get("ignored") + " " + report.get("conflicts"));
long since = json.readTree(changes).get("clock").asLong(); // pass it next time
}| 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 |
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 |
since is a long. 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
A version is {"lamport", "client"}: a higher Lamport clock wins, then the higher 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. Keys that only make sense
together are one property: an annotation's geometry, a page's content and resources, a bookmark's
parent and order. So Alice editing an annotation's text while Bob moves it keeps both edits, and a
page rotated by one person and cropped by another keeps both. When a merge 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; a newer edit 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 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 client
NexPdfSync connects a document to the sync endpoint of a NexPDF web viewer session. It uses only
java.net.http: a WebSocket first, else Server-Sent Events + POST for the rest of the session when
the socket never reaches hello (a proxy without upgrades, for example). Remote changes are merged
into the document (skipping this client's own), local changes are pushed every second or on
flush(), and the connection reconnects with backoff (1 s up to 30 s) and resumes from the last
sequence, but never on 401, 402, 403 or 404.
NexPdfSync.Options o = new NexPdfSync.Options("https://host/s/abc"); // the viewer session
o.token = "nxt_…"; // Authorization: Bearer
o.name = "Ana";
o.color = "#1E88E5";
o.transport = NexPdfSync.Transport.AUTO; // or WEBSOCKET, SSE
NexPdfSync.Listener listener = new NexPdfSync.Listener() {
@Override public void onRemote(String applyReportJson, int changeCount) { /* repaint */ }
@Override public void onPresence(List<NexPdfSync.Peer> peers) { /* show cursors */ }
@Override public void onStatus(NexPdfSync.Status status) { System.out.println(status); }
@Override public void onReload(long seq) { /* downloadDocument(), then attach(doc) */ }
@Override public void onError(Throwable error) { error.printStackTrace(); }
};
NexPdfDocument doc = NexPdfDocument.openBytes(downloadedPdf); // every copy starts from the same file
NexPdfSync sync = new NexPdfSync(doc, o, listener);
sync.connect().get(20, TimeUnit.SECONDS); // completes on the server's hello
synchronized (sync.lock) { doc.rotatePage(0, 90); } // the document is not thread-safe: use the lock
sync.flush(); // push now
sync.setPresence(0, new double[] {100, 200}); // page index and cursor in PDF points (or null)
sync.close();| Member | Use |
|---|---|
new NexPdfSync(doc, options, listener) | A client for a document. NexPdfSync.Engine lets tests pass a stub instead |
connect() | Opens the stream in the background. The CompletableFuture<Void> completes on hello, or exceptionally when the client closes first or the token is refused |
awaitOnline(timeoutMs) | Waits for hello; false on timeout |
flush() | Pushes local changes now and returns the server's result JSON, or null when there were none |
setPresence(page, cursor) | Shares this person's page and cursor |
downloadDocument() | The server's current PDF, for a fresh copy or after onReload |
attach(doc) | Switches to another document |
status(), transport(), peers(), seq() | CONNECTING, ONLINE, OFFLINE or CLOSED; the transport in use; the other people connected; the last server sequence |
close() | Stops syncing. Call flush() first to send pending edits |
Options also has clientId (a random UUID by default), since, flushIntervalMs (default
1000; 0 pushes only on flush()), reconnectDelayMs, connectTimeoutMs, idleTimeoutMs
(default 90 000) and callbackExecutor (where listener callbacks run; null is the client's own
thread). Listener also has onPushed and onConflict. Each Peer has client, name,
color, user, page and cursor.
The client calls the engine on its own threads while holding sync.lock. Make your own calls on
the same document inside synchronized (sync.lock) too.
The sync server
The NexPDF web viewer server hosts the sync endpoint under the viewer session (/s/<session>/…):
| Endpoint | Use |
|---|---|
GET /api/sync/document | The PDF to start from |
GET /api/sync/ws?since=<seq>&client=<id> | WebSocket (subprotocol nexpdf-sync, optionally bearer.<token>): the stream 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/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 stream; only editors may push. Edits 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. A changes batch with reset: true
means the server's log restarted and the batch is the full state.
Limits
- Attachments are not records. Replacing the document on the server sends
reload.