Real-time collaboration
Keep several copies of a PDF in step with NexPDF Sync and the NexPdfSync client, syncing annotations, comments, form values, bookmarks and pages with per-property last-writer-wins merging, with NexPDF for Python.
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 |
Shared objects are content-addressed: the same object has the same id on every copy, is sent once however many records use it, and a copy that already holds it uses its own (shared, not copied).
Page operations sync too: inserting, deleting, moving, rotating and cropping pages and editing page
content. Pages are ordered by position keys, so every copy reaches the same page order, 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.
The sync client
nexpdf.NexPdfSync keeps a document in sync with a NexPDF web viewer server. It uses only the
standard library: a WebSocket (ws:// and wss://, with host name checks), else Server-Sent
Events and POST.
import nexpdf
url = "https://viewer.example.com/s/abc"
probe = nexpdf.NexPdfSync(None, url, token="nxt_...")
doc = nexpdf.Document.from_bytes(probe.download_document()) # the server's copy; sets probe.seq
sync = nexpdf.NexPdfSync(doc, url, token="nxt_...", name="Ana", color="#FF0000", since=probe.seq)
sync.on("remote", lambda report, changes: redraw())
sync.on("presence", lambda peers: show_cursors(peers))
sync.on("error", lambda e: print("sync:", e))
if sync.connect(): # True once the server said hello
with sync.lock: # remote changes are applied on the client's own thread
doc.add_annotation(0, "Square", "#FF0000", 1, "hi", 50, 50, 150, 120)
sync.flush() # push now, or wait for the next automatic push
sync.set_presence(0, (120, 300)) # page index and cursor in PDF points
print(sync.status, sync.transport, sync.seq, [p.name for p in sync.peers])
sync.close()NexPdfSync(engine, url, **options) takes the document (or None until you have one; attach(doc)
sets it later) and the session URL https://host/s/<session>. Keyword options:
| Option | Default | Meaning |
|---|---|---|
client_id | random UUID | The id this copy versions its changes under |
name, color | "" | Shown to the others with your presence |
token | Session token (nxt_...), sent as Authorization: Bearer | |
since | 0 | Server sequence to resume from |
flush_interval | 1.0 | Seconds between automatic pushes; 0 pushes only on flush() |
reconnect_delay | 1.0 | First retry delay, doubling up to 30 s |
transport | "auto" | "auto", "websocket" or "sse" |
connect_timeout | 15.0 | Seconds for a connection |
ssl_context | default context | An ssl.SSLContext for https and wss |
With transport="auto" the client opens a WebSocket and, if the socket never reaches hello (a
proxy without upgrades, a refused token), uses Server-Sent Events and POST for the rest of the
session. It applies the others' changes and skips its own echoes, pushes local changes every
flush_interval, and reconnects with backoff from 1 s up to 30 s, resuming from the last sequence.
It does not reconnect after HTTP 401, 402, 403 or 404.
| Member | Use |
|---|---|
connect(wait=True, timeout=30.0) | Starts the background threads; with wait, returns True once online |
on(event, fn) / off(event, fn) | Adds or removes a callback; on returns a function that removes it |
flush(timeout=120.0) | Pushes local changes now; returns the server's result, or None when there was nothing to push. Raises SyncError when the server refused |
set_presence(page, cursor) | Shares your page index and cursor (x, y) in PDF points (None = no cursor) |
download_document() | The server's current PDF; sets seq |
attach(doc) | Switches to another document, for example after reload |
close() | Stops syncing. Pending local edits stay in the document; call flush() first to send them |
status | connecting, online, offline or closed |
transport | "websocket" or "sse" while connected, else None |
seq, peers, lock | Last server sequence; the others as SyncPeer (client, name, color, page, cursor, user); the lock held during every engine call |
Events and their arguments: remote(report, change_set), pushed(result), conflict(conflicts),
presence(peers), status(status), reload(seq) and error(exc). Callbacks run on the client's
threads. Hold sync.lock around your own edits of the synced document. NexPdfSync is also a
context manager that closes on exit.
On reload the server's document was replaced: download it again and attach the new copy.
def on_reload(seq):
global doc
doc = nexpdf.Document.from_bytes(sync.download_document())
sync.attach(doc)
sync.on("reload", on_reload)Exchange changes without a server
import nexpdf
with nexpdf.Document.open("shared.pdf") as a, nexpdf.Document.open("shared.pdf") as b:
a.sync_set_client_id("alice")
b.sync_set_client_id("bob")
a.add_annotation(0, "Highlight", "#FFD400", 1.0, "", 72, 700, 300, 716)
changes = a.sync_export_local_json(0) # what alice pushes
report = nexpdf.loads(b.sync_apply_json(changes))
print(report["applied"], report["ignored"], report["conflicts"])
since = nexpdf.loads(changes)["clock"] # pass it next time| Call | Returns |
|---|---|
sync_set_client_id(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 |
sync_export_local_json(since) | Only this copy's own changes with a clock above since: what a client sends. Keep the returned clock for the next call |
sync_export_json(since) | Every change above since, from any client |
sync_apply_json(changes) | Applies a change set and returns a report |
sync_snapshot_json() | 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. Change sets use the format nexpdf-sync/2; format 1
change sets are still read.
How changes merge
Every property of a record has its own version {"lamport", "client"}. On apply, the higher
version wins per property (last writer wins): a higher Lamport clock, then the higher client id,
so every copy picks the same winner in whatever order changes arrive. Some keys merge as one
property: an annotation's geometry, a page's content and resources, a bookmark's parent and order.
So Alice changing 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 combines 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: an edit newer than the deletion brings the record back with every property.
The apply report has ok, clock, applied and ignored (changes that lost to a newer local
version) 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 that NexPdfSync talks to:
| Endpoint | Use |
|---|---|
GET /api/sync/ws?since=<seq>&client=<id>&name=…&color=… | WebSocket (subprotocol nexpdf-sync, optionally bearer.<token>): the stream events plus pushed and error; the client sends pushes and presence over it |
GET /api/sync/document | The PDF to start from (header X-Sync-Seq) |
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 |
Viewers may connect and send presence; only editors may push. Page operations, 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, so a restarted server rebuilds the document. The data directory is NEXPDF_DATA_DIR
(off, none or memory keeps everything in memory), else a per-user default: on macOS
~/Library/Application Support/NexPDF/WebViewer, on Windows %LOCALAPPDATA%\NexPDF\WebViewer,
elsewhere $XDG_DATA_HOME/nexpdf/webviewer.
Limits
- Attachments are not records and are not synced.
- Replacing the document on the server sends
reload: download it again andattachit.