Skip to Content
NexPDF

Real-time collaboration

Keep several copies of a PDF in step with NexPDF Sync and the C++ sync client, with pages, annotations, comments, form values and bookmarks merged per property, last writer wins, with NexPDF for C++.

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: insert, delete, move, rotate, crop and content edits merge into the same page order on every copy, and /Dest destinations follow their page. Shared objects are content-addressed, so each is sent once and copies that already hold it use their own.

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.

Exchange changes

#include <nexpdf.hpp>
#include <nlohmann/json.hpp>   // an example; use your JSON library

namespace nexpdf = nexdevit::nexpdf;

auto a = nexpdf::Document::open("shared.pdf");
auto b = nexpdf::Document::open("shared.pdf");
a.sync_set_client_id("alice");
b.sync_set_client_id("bob");

a.add_annotation(0, "Highlight", "#FFD400", 1.0, std::nullopt, 72, 700, 300, 716);

std::string changes = a.sync_export_local_json(0);   // what alice pushes
auto report = nlohmann::json::parse(b.sync_apply_json(changes));
std::cout << report["applied"] << " " << report["ignored"] << " " << report["conflicts"] << "\n";

auto since = nlohmann::json::parse(changes)["clock"].get<uint64_t>();   // pass it next time
CallReturns
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

The sync methods are not const: they record the sync state in the document. 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

Every property of a record has its own version {"lamport", "client"}, and 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 are one property: an annotation's geometry, a page's Contents and Resources, a bookmark's parent and order. So Alice editing an annotation's text while Bob moves it keeps both edits; two people changing the same property keep the later one.

After a mixed merge 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 brought nothing newer) ids, conflicts (id, winner, local, remote, props), 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: sync_apply_json throws nexdevit::nexpdf::Error.

The sync client

nexpdf::Sync, in the separate header nexpdf/sync.hpp, keeps a Document in sync with a NexPDF web viewer server. nexpdf.hpp stays free of networking; link nexdevit::nexpdf_sync (it adds threads). The client talks WebSocket (/api/sync/ws) and falls back to Server-Sent Events plus POST for the session when the socket never reaches hello. It applies the others' changes (skipping its own), pushes sync_export_local_json every second, and reconnects by itself (1 s doubling up to 30 s, never after 401, 402, 403 or 404).

#include <nexpdf/sync.hpp>

namespace nexpdf = nexdevit::nexpdf;

nexpdf::Sync::Options o;
o.url = "http://viewer.local:8080/s/abc";   // the viewer session
o.token = "nxt_...";                         // Authorization: Bearer / bearer.<token> subprotocol
o.name = "Ana";
o.color = "#E91E63";

nexpdf::Sync::Listener on;
on.on_remote = [](const std::string& report_json, size_t change_count) { /* redraw */ };
on.on_presence = [](const std::vector<nexpdf::Sync::Peer>& peers) { /* cursors */ };
on.on_status = [](nexpdf::Sync::Status s) { /* Connecting, Online, Offline, Closed */ };
on.on_reload = [](uint64_t seq) { /* download_document() again and attach() it */ };
on.on_error = [](const nexpdf::Error& e) { std::cerr << e.what() << "\n"; };

auto doc = nexpdf::Document::open_bytes(nexpdf::Sync::download_document(o, &o.since));   // and its seq
nexpdf::Sync sync(doc, o, on);               // doc must outlive sync
sync.connect();                              // waits up to 15 s for the server's hello
{
    std::lock_guard<std::mutex> g(sync.lock());   // every engine call holds this lock
    doc.add_annotation(0, "Highlight", "#FFD400", 1.0, std::nullopt, 72, 700, 300, 716);
}
sync.flush();                                // else pushed within flush_interval (1 s)
sync.set_presence(0, std::array<double, 2>{120, 300});
Sync::Options memberMeaning
urlBase URL of the viewer session, such as http://host/s/<session>
client_idStable id of this device; a random UUID when empty
name, colorShown to the others
tokenSession token, sent as Authorization: Bearer and as the bearer.<token> subprotocol
sinceServer sequence to resume from; 0 = everything
flush_intervalPush interval (1 s); 0 = only on flush()
reconnect_delayFirst reconnect delay (1 s), doubling up to 30 s
connect_timeoutConnection timeout (15 s)
transportTransport::Auto (default), Transport::WebSocket or Transport::Sse
connectorA factory of net::Connection; empty = built in
MemberUse
connect(timeout)Starts syncing in the background and waits up to timeout (15 s) for hello; returns whether it is online
wait_online(timeout)Waits for hello; false on timeout or when the client closed
flush()Pushes the local changes now; the server's result JSON, std::nullopt when there was nothing to push. Throws Error when the push failed (the next flush retries it)
set_presence(page, cursor)Shares the page and a cursor in PDF points
lock()The mutex every engine call holds; hold it while you edit the document
download_document()The server's current document (also Sync::download_document(options, &seq) before a client exists)
attach(doc)Switches to another document, for example after on_reload
close()Stops syncing (also the destructor); pending local edits stay in the document (flush() first)
status(), transport(), peers(), seq(), client_id()Current state

The Listener callbacks (on_remote, on_pushed, on_conflict, on_presence, on_status, on_reload, on_error) are optional and run on the client's two threads (stream and periodic push). A final HTTP status sets the status to Closed and comes to on_error with the status in code().

Networking is built in for http:// and ws:// over POSIX sockets (macOS, Linux, BSD). For https:// and wss://, configure with -DNEXPDF_SYNC_OPENSSL=ON (links OpenSSL: system trust store, SNI, host name check) or set Options::connector to a function returning your own nexdevit::nexpdf::net::Connection over your TLS library or platform sockets (on Windows, where the built-in sockets are not available).

The sync server

The NexPDF web viewer server hosts the sync endpoint the client above talks to:

EndpointUse
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 push and presence messages
GET /api/sync/documentThe PDF to start from (header X-Sync-Seq)
GET /api/sync/stream?since=<seq>&client=<id>Server-Sent Events: hello, changes, presence, reload (the fallback)
POST /api/sync/pushA change set of the client's own changes (the fallback)
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

Viewers may connect and send presence; only editors may push. hello reports the transport and the change-set format. Page operations and undo and redo in the browser viewer become changes too. 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 (macOS ~/Library/Application Support/NexPDF/WebViewer, Windows %LOCALAPPDATA%\NexPDF\WebViewer, others $XDG_DATA_HOME/nexpdf/webviewer). A changes batch with reset: true means the server log restarted and the batch is the full state.

Limits

  • Document attachments (embedded files) are not records and are not synced; file attachment annotations are.
  • Replacing the document on the server sends reload: download it again and attach() it.

On this page