Skip to Content
NexPDF

Real-time collaboration

Keep several copies of a PDF in step with NexPDF Sync and the ready-made NexPdfSyncClient, pages, annotations, comments, form values and bookmarks, with live presence and deterministic per-property last-writer-wins merging, with NexPDF for Android.

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

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.

The Android SDK has two layers: NexPdfSyncClient, a ready-made client for the NexPDF sync server, and NexPdfSyncJni, the sync calls on a document handle for your own transport.

Connect to a sync server

Every copy must start from the server's file. Download it from GET <url>/api/sync/document (with the same Authorization header; the X-Sync-Seq response header is the sequence to pass as since), open it, wrap its handle with NexPdfSyncJni.engine(handle) and connect. The client connects over a WebSocket (a built-in RFC 6455 client, NexPdfSyncSocket, for ws:// and wss:// with host name checks), streams the others' changes into the document and pushes your edits about once a second. When the socket never reaches hello (a proxy that does not pass upgrades, for example), it switches to Server-Sent Events + POST for the rest of the session.

import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfSyncClient
import com.nexdevit.nexpdf.NexPdfSyncJni

val options = NexPdfSyncClient.Options("https://viewer.example.com/s/abc123").apply {
    token = sessionToken                 // sent as Authorization: Bearer
    name = "Ana"
    color = "#2563EB"
    since = serverSeq                    // X-Sync-Seq of the download, or 0
    callbackExecutor = mainExecutor      // listener callbacks on the main thread
    transport = NexPdfSyncClient.Transport.AUTO   // or WEBSOCKET, SSE
}

val listener = object : NexPdfSyncClient.Listener {
    override fun onRemote(applyReportJson: String, changeCount: Int) = pageView.invalidate()
    override fun onPresence(peers: List<NexPdfSyncClient.Peer>) = showCursors(peers)
    override fun onStatus(status: NexPdfSyncClient.Status) = showStatus(status)
    override fun onError(error: Throwable) { Log.w("NexPDF", "sync", error) }
}

val doc = NexPdfDocument.openBytes(serverPdf)
val sync = NexPdfSyncClient(NexPdfSyncJni.engine(doc.handle()), options, listener)
sync.connect()
if (!sync.awaitOnline(10_000)) Log.w("NexPDF", "sync still offline: ${sync.status()}")   // off the main thread

Once a client exists, sync.downloadDocument() fetches the current file and updates seq(), which is what you use after onReload.

Add the INTERNET permission to the manifest. Keep the document open while the client uses it, and close() the client before you close the document.

Edit the document while syncing

The client calls the engine from its own threads, holding sync.lock. Make your own edits of the same document inside that lock, so they never run at the same time as a merge:

synchronized(sync.lock) {
    NexPdfJni.addAnnotation(doc.handle(), 0, "Highlight", "#FFD400", 1.0, "", 72.0, 700.0, 300.0, 716.0)
}
withContext(Dispatchers.IO) { sync.flush() }   // push now instead of waiting for the timer

Remote changes are merged into the document before onRemote runs: redraw the pages there. The client skips its own changes when the server echoes them back.

NexPdfSyncClient

MemberDoes
NexPdfSyncClient(engine, options, listener)Creates the client and sets the engine's client id. listener may be null
connect()Opens the change stream in the background and starts the push timer
awaitOnline(timeoutMs)Waits until the server said hello; false on timeout or when the client closed
close()Stops syncing. Local edits not yet pushed stay in the document; call flush() first to send them
flush()Pushes the local changes made since the last push and returns the server's result JSON, or null when there were none. Throws IOException
setPresence(page, cursor)Shares the page this person is on and a cursor in PDF points (doubleArrayOf(x, y), or null)
downloadDocument()The server's current PDF as a ByteArray; also updates seq()
attach(engine)Switches to another document, for example one reopened after onReload
handleEvent(event, data)Handles one server event, for custom transports and tests
seq(), pushedClock(), status(), peers()Last server sequence seen, Lamport clock of the last push, the Status and the other people connected
transport()WEBSOCKET or SSE while connected, else null
clientId, lockThis device's client id, and the lock held during every engine call

flush(), setPresence() and downloadDocument() do network I/O: call them off the main thread.

Options

FieldDefaultMeaning
url(constructor)Server URL, or a session URL such as https://host/s/<session>
clientIdrandom UUIDStable id of this device (1 to 64 characters of A-Z a-z 0-9 - _ . : @)
name, color""Shown to the others in presence (color is #RRGGBB)
tokennullSession token, sent as Authorization: Bearer
since0Server sequence to resume from (a previous seq()); 0 is everything since the document was loaded
flushIntervalMs1000Push interval; 0 pushes only on flush()
reconnectDelayMs1000First reconnect delay; it doubles up to 30 seconds
connectTimeoutMs15000HTTP connect timeout
transportAUTOAUTO (WebSocket, else SSE + POST), WEBSOCKET or SSE
callbackExecutornullWhere listener callbacks run, for example context.mainExecutor; null runs them on the client's threads

Listener

Every callback is optional (a default method).

CallbackWhen
onRemote(applyReportJson, changeCount)Remote changes were applied; the engine's apply report (applied, ignored, conflicts, errors)
onPushed(pushResultJson)A push was stored by the server
onConflict(conflictsJson)Records where a local edit lost or won against a concurrent one
onPresence(peers)The list of other people changed. Each Peer has client, name, color, user, page and cursor ([x, y] in PDF points, or null)
onStatus(status)CONNECTING, ONLINE, OFFLINE or CLOSED
onReload(seq)The server's document was replaced: download it again and attach it
onError(error)A stream, push or merge error

The stream reconnects by itself and resumes from the last seq(). When the server answers 401, 402, 403 or 404 (bad token, read-only session, unlicensed server or no such session), retrying will not help: the client reports the error and closes.

When the document is replaced

override fun onReload(seq: Long) {
    ioScope.launch {
        val fresh = NexPdfDocument.openBytes(sync.downloadDocument())
        sync.attach(NexPdfSyncJni.engine(fresh.handle()))
        val old = doc
        doc = fresh
        old.close()
    }
}

Exchange changes yourself

NexPdfSyncJni has the sync calls on a document handle. The JSON methods return null on error, with the reason in NexPdfJni.lastError():

import com.nexdevit.nexpdf.NexPdfJni
import com.nexdevit.nexpdf.NexPdfSyncJni
import org.json.JSONObject

NexPdfDocument.openBytes(shared).use { a ->
    NexPdfDocument.openBytes(shared).use { b ->
        NexPdfSyncJni.setClientId(a.handle(), "alice")
        NexPdfSyncJni.setClientId(b.handle(), "bob")

        NexPdfJni.addAnnotation(a.handle(), 0, "Highlight", "#FFD400", 1.0, "", 72.0, 700.0, 300.0, 716.0)

        val changes = NexPdfSyncJni.exportLocalJson(a.handle(), 0) ?: error(NexPdfJni.lastError())
        val report = JSONObject(NexPdfSyncJni.applyJson(b.handle(), changes))
        Log.i("NexPDF", "${report.get("applied")} ${report.get("ignored")} ${report.get("conflicts")}")

        val since = JSONObject(changes).getLong("clock")   // pass it next time
    }
}
CallReturns
setClientId(handle, id)Sets the id this copy versions its changes under (1 to 64 characters of A-Z a-z 0-9 - _ . : @). 1 on success, 0 on error. Random when not set
exportLocalJson(handle, since)Only this copy's own changes with a clock above since: what a client sends. Keep the returned clock for the next call
exportJson(handle, since)Every change above since, from any client
applyJson(handle, changes)Applies a change set and returns a report
snapshotJson(handle)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

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 server

The NexPDF web viewer server hosts the sync endpoint NexPdfSyncClient talks to, under the viewer session (/s/<session>/…):

EndpointUse
GET /api/sync/documentThe 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/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 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 Web, Node.js, iOS and Java SDKs have the same client, so all of them can edit one document together.

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.

On this page