Skip to Content
NexPDF

Real-time collaboration

Keep several copies of a PDF in step with NexPDF Sync and the NexPdfSync client, exchanging pages, annotations, comments, form values and bookmarks with deterministic per-property merging, with NexPDF for .NET.

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

Change sets use the format nexpdf-sync/2 (format 1 is still read). 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. Page operations sync too: inserting, deleting, moving and rotating pages, cropping and content edits. Pages keep a deterministic order on every copy, and /Dest destinations follow their page.

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

using System.Text.Json.Nodes;
using Nexdevit.NexPdf;

using var a = NexPdfDocument.Open("shared.pdf");
using var b = NexPdfDocument.Open("shared.pdf");
a.SyncSetClientId("alice");
b.SyncSetClientId("bob");

a.AddAnnotation(0, "Highlight", "#FFD400", 1.0, "", 72, 700, 300, 716);

var changes = a.SyncExportLocalJson(0);                  // what alice pushes
var report = JsonNode.Parse(b.SyncApplyJson(changes))!;
Console.WriteLine($"{report["applied"]!.ToJsonString()} {report["ignored"]!.ToJsonString()} {report["conflicts"]!.ToJsonString()}");

var since = JsonNode.Parse(changes)!["clock"]!.GetValue<ulong>();   // 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

since is a ulong. 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 Contents and Resources, a bookmark's parent and order. So Alice changing an annotation's text while Bob moves it keeps both edits; a page rotated by one person and cropped by another keeps both.

After a merge that mixes 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 props, the properties in conflict), 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, receive 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): the events below plus pushed and error; pushes and presence go over it too
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 (on the WebSocket, the subprotocol bearer.<token>). Viewers may connect; only editors may push. Page operations and undo and redo in the browser viewer become changes too. A changes batch with reset: true means the server's log restarted and the batch is the full state.

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 keep everything in memory), else ~/Library/Application Support/NexPDF/WebViewer on macOS, %LOCALAPPDATA%\NexPDF\WebViewer on Windows and $XDG_DATA_HOME/nexpdf/webviewer elsewhere.

The .NET client

NexPdfSync connects a NexPdfDocument to the server. It opens a WebSocket first and falls back to Server-Sent Events + POST for the session when the socket never reaches hello. It applies the others' changes (skipping its own), pushes local edits every second, and reconnects with a backoff from 1 s to 30 s, but never after 401, 402, 403 or 404.

using Nexdevit.NexPdf;

var options = new NexPdfSyncOptions("https://viewer.example.com/s/<session id>")
{
    Name = "Ana",
    Color = "#E5484D",
    Token = token,
};
using var sync = new NexPdfSync(options);
using var doc = NexPdfDocument.OpenBytes(await sync.DownloadDocumentAsync());   // sets sync.Seq
sync.Attach(doc);

sync.Remote += (_, e) => Redraw();               // e.Report, e.ChangesJson
sync.Presence += (_, peers) => ShowCursors(peers);
sync.Reload += async (_, seq) =>                 // the server's document was replaced
    sync.Attach(NexPdfDocument.OpenBytes(await sync.DownloadDocumentAsync()));
sync.Error += (_, e) => Console.WriteLine(e.Message);

await sync.ConnectAsync();                        // completes on hello; throws on a refusal

await sync.EngineLock.WaitAsync();               // engine calls are serialised by this lock
try { doc.AddAnnotation(0, "Square", "#FF0000", 1, "note", 50, 50, 150, 120); }
finally { sync.EngineLock.Release(); }
await sync.FlushAsync();                          // or let the 1 s timer push it

await sync.SetPresenceAsync(0, (100, 200));      // page and cursor in PDF points

DownloadDocumentAsync() returns the server's current document and sets Seq. Pass a saved Seq as Since to resume. Close() stops syncing (call FlushAsync() first to send pending edits); Dispose() also closes.

NexPdfSyncOptionsDefaultMeaning
UrlServer base URL: https://host or https://host/s/<session id>
ClientIdrandom UUIDStable id of this device
Name, ColorShown to the others (#RRGGBB)
TokenSession token: Authorization: Bearer, and bearer.<token> on the socket
Since0Sequence to catch up from
FlushInterval1 sHow often local edits are pushed; TimeSpan.Zero pushes only on FlushAsync()
ReconnectDelay1 sFirst reconnect delay (doubles up to 30 s)
TransportAutoNexPdfSyncTransport.Auto, WebSocket or Sse
EngineLocka new lockThe SemaphoreSlim held around every engine call; share the one your app holds while editing or rendering
EventContextnullSynchronizationContext the events are raised on (such as the UI thread's); null raises them on the client's threads
HttpHandlerSocketsHttpHandlerHandler for the SSE stream and the POST requests
MemberMeaning
RemoteA batch of remote changes was applied (NexPdfSyncRemoteEventArgs: Report, ChangesJson)
PushedLocal changes reached the server (NexPdfSyncPushResult)
ConflictConflicts of an apply or of a push
PresenceThe people connected (NexPdfSyncPeer: Client, Name, Color, Page, Cursor, User), own client excluded
StatusChangedConnecting, Online, Offline or Closed
ReloadThe server's document was replaced: download it again and Attach it
ErrorA request failed; a NexPdfSyncException with IsFatal set will not be retried
ClientId, Seq, PushedClock, Peers, Status, TransportThe client's state

The engine is any INexPdfSyncEngine; NexPdfDocument is one.

Limits

  • Attachments are not records. Replacing the document on the server sends reload.

On this page