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 iOS (Swift).
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 Swift package has two levels: the sync… methods of NexPdfDocument, 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, a URLSessionWebSocketTask) and falls back to Server-Sent Events plus
POST when the socket cannot be opened.
The client needs a document to start, and every copy must start from the same file, so download the server's document first:
import NexPdf
let base = URL(string: "https://viewer.example.com/s/3f9c2a")! // a viewer session
let token = "nxt_…" // the session token
var request = URLRequest(url: base.appendingPathComponent("api/sync/document"))
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (pdf, response) = try await URLSession.shared.data(for: request)
let since = ((response as? HTTPURLResponse)?.value(forHTTPHeaderField: "X-Sync-Seq")).flatMap(UInt64.init) ?? 0
let doc = try NexPdfDocument.open(data: pdf)
let sync = try NexPdfSync(engine: doc, options: .init(url: base, name: "Ana", color: "#2563EB",
token: token, since: since))
sync.onRemote = { report in pagesView.reload() } // others' changes are in `doc`
sync.onPresence = { peers in showCursors(peers) }
sync.onStatus = { status in statusLabel.text = status.rawValue }
sync.onError = { error in print("sync:", error) }
sync.connect()
// later, after a local edit (or let flushInterval push it):
try doc.addAnnotation(pageIndex: 0, kind: "Highlight", colorHex: "#FFD400", opacity: 1, contents: "",
llx: 72, lly: 700, urx: 300, ury: 716)
try await sync.flush()init(engine:options:) sets the document's client id and throws when the engine rejects it. Any
object that implements NexPdfSyncEngine (syncSetClientId, syncExportLocalJson,
syncApplyJson) can be the engine; NexPdfDocument does.
Options
NexPdfSync.Options(url:clientId:name:color:token:since:flushInterval:reconnectDelay:session:queue:transport:):
| Option | Default | Meaning |
|---|---|---|
url | required | The server URL, or a viewer session URL https://host/s/<id>. Requests go to url + api/sync/… |
clientId | a new UUID | Stable id of this device: 1 to 64 characters of A-Z a-z 0-9 - _ . : @ |
name | nil | The person's name, shown to the others |
color | nil | #RRGGBB, the colour of this person's cursor |
token | nil | Session token, sent as Authorization: Bearer |
since | 0 | Server sequence to catch up from: the X-Sync-Seq of the downloaded document, or a saved seq. 0 replays everything |
flushInterval | 1 | Seconds between automatic pushes of local edits. 0 pushes only on flush() |
reconnectDelay | 1 | First reconnect delay in seconds. It doubles up to 30 |
session | URLSession.shared | The session used for every request |
queue | .main | Where the document is used and every callback runs |
transport | .auto | NexPdfSyncTransport: .auto (WebSocket, else Server-Sent Events plus POST), .websocket or .sse |
Callbacks
| Property | Called with |
|---|---|
onRemote | The engine's apply report (applied, ignored, conflicts, errors) after others' changes were applied |
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 [NexPdfSyncPeer] (client, name, color, page, cursor in PDF points or nil, user) |
onStatus | NexPdfSyncStatus: connecting, online, offline or closed |
onReload | The new seq after the server's document was replaced |
onError | Network and engine errors. The client keeps running unless it closed itself |
Methods and state
| Member | Does |
|---|---|
connect() | Opens the connection (WebSocket or stream) and starts the push timer |
flush() | async throws: pushes the local edits made since the last push and returns the server's answer, or nil when there was nothing to push |
setPresence(page:cursor:) | async throws: shares the page this person is on and, optionally, a cursor in PDF points |
downloadDocument() | async throws: the server's current PDF; also sets seq from X-Sync-Seq |
attach(_:) | Switches to another document, for example the one reopened after onReload. Call it on queue |
close() | Stops syncing. Local edits not yet pushed stay in the document; call flush() first to send them |
handleEvent(_:_:) | Handles one server event (hello, changes, presence, reload), for custom transports |
transport | The transport of the current connection, .websocket or .sse, or nil while offline |
clientId, seq, pushedClock, status, peers | Read-only state. Save seq to resume later with since |
When the server replaces the document, reopen it and attach it:
sync.onReload = { _ in
Task {
let fresh = try NexPdfDocument.open(data: try await sync.downloadDocument())
try sync.attach(fresh)
pagesView.show(fresh)
}
}Threads and reconnection
The document is used only on options.queue, where every callback runs too. Make your own edits of
the same document on that queue (the main queue by default), and do not edit it from another
thread while syncing.
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, reporting the error and closing, 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. A batch that fails to
apply is not counted, so a reconnect replays it.
The reader does not connect to a sync server by itself: open the document,
start NexPdfSync, and reload the pages in 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):
let a = try NexPdfDocument.open(url: sharedURL)
let b = try NexPdfDocument.open(url: sharedURL)
try a.syncSetClientId(clientId: "alice")
try b.syncSetClientId(clientId: "bob")
try a.addAnnotation(pageIndex: 0, kind: "Highlight", colorHex: "#FFD400", opacity: 1, contents: "",
llx: 72, lly: 700, urx: 300, ury: 716)
let changes = try a.syncExportLocalJson(sinceVersion: 0) // what alice pushes
let report = NexPdf.json(try b.syncApplyJson(changesJson: changes)) as? [String: Any] ?? [:]
print(report["applied"] ?? [], report["ignored"] ?? [], report["conflicts"] ?? [])
let since = ((NexPdf.json(changes) as? [String: Any])?["clock"] as? NSNumber)?.uint64Value ?? 0 // pass it next time| Call | Returns |
|---|---|
syncSetClientId(clientId:) | 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(sinceVersion:) | Only this copy's own changes with a clock above sinceVersion: what a client sends. Keep the returned clock for the next call |
syncExportJson(sinceVersion:) | Every change above sinceVersion, from any client |
syncApplyJson(changesJson:) | 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 call throws 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, Android, Flutter 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.