Skip to Content
NexPDF

Real-time collaboration

Keep several copies of a PDF in step with NexPDF Sync and the Sync client, syncing annotations, comments, form values, bookmarks and pages with per-property last-writer-wins merging, with NexPDF for PHP.

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

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

Nexdevit\NexPdf\Sync keeps a document in sync with a NexPDF web viewer server. It uses only the standard library: a WebSocket (a built-in RFC 6455 client over stream sockets, tls:// with certificate and host name checks), else Server-Sent Events and POST.

PHP runs one thread, so the client has an explicit event loop: callbacks run inside connect(), poll(), run() and flush(), and you edit the document between those calls. Engine calls never interleave with your own. Run it in a long-lived CLI worker; in a short web request, connect, push with flush() and close.

use Nexdevit\NexPdf\{Document, Sync};

$url = 'https://viewer.example.com/s/abc';
// Any document (or SyncEngine) until the server's copy is attached.
$sync = new Sync(Document::open('shared.pdf'), ['url' => $url, 'token' => $token,
    'name' => 'Ana', 'color' => '#FF0000']);
$doc = Document::openBytes($sync->downloadDocument());   // the server's copy; sets seq
$sync->attach($doc);

$sync->on('remote', fn (array $report, object $changes) => print(count($report['applied']) . " merged\n"));
$sync->on('presence', fn (array $peers) => print(count($peers) . " others\n"));
$sync->on('error', fn (\Throwable $e) => print('sync: ' . $e->getMessage() . "\n"));

if ($sync->connect()) {                                   // true once the server said hello
    $doc->addAnnotation(0, 'Square', '#FF0000', 1.0, 'note', 50, 50, 150, 120);
    $sync->flush();                                       // or let poll()/run() push it
    $sync->setPresence(0, ['x' => 120, 'y' => 300]);      // page index and cursor in PDF points
    echo $sync->status(), ' ', $sync->transport(), ' ', $sync->seq(), "\n";
    $sync->run(null, 30.0);                               // serve events for 30 s
}
$sync->close();

new Sync($doc, $options) takes a Document (used through DocumentSyncEngine) or anything that implements SyncEngine, and an options array:

OptionDefaultMeaning
urlrequiredThe session URL, https://host/s/<session>
clientIdrandom UUIDThe id this copy versions its changes under
name, color''Shown to the others with your presence
tokenSession token (nxt_...), sent as Authorization: Bearer
since0Server sequence to resume from
flushInterval1.0Seconds between pushes inside poll() and run(); 0 pushes only on flush()
reconnectDelay1.0First retry delay, doubling up to 30 s
connectTimeout15.0Seconds for a connection and its hello
transportautoauto, websocket or sse
ssl[]Extra ssl stream context options, such as cafile

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 flushInterval, 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; connect() then throws the error.

MethodUse
connect(float $timeout = 15.0)Opens the connection and serves events until the server said hello: true once online, false after the timeout (later poll() and run() calls keep trying)
poll(float $timeout = 0.0)One turn of the event loop: reads events, applies remote changes, pushes when the flush interval is due, reconnects when it is time
run(?callable $until = null, float $timeout = INF)Runs the loop until $until($sync) returns true (returns true), the timeout passes or the client closes (false)
on($event, $handler)Adds a callback; returns a closure that removes it
flush()Pushes local changes now; returns the server's result, or null when there was nothing to push. Throws NexPdfException when the server refused
setPresence(int $page, ?array $cursor = null)Shares your page index and cursor (['x' => .., 'y' => ..] or [x, y] in PDF points; null = no cursor)
downloadDocument()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 (also Sync::STATUS_*)
transport()websocket or sse while connected, else null
seq(), pushedClock(), peers(), clientIdLast server sequence; clock of the last push; the others (client, name, color, page, cursor, user); this client's id

Events and their arguments: remote (array $report, object $changeSet), pushed (array $result), conflict (array $conflicts), presence (array $peers), status (string), reload (int $seq) and error (\Throwable).

On reload the server's document was replaced: download it again and attach the new copy.

$sync->on('reload', function (int $seq) use ($sync, &$doc) {
    $doc = Document::openBytes($sync->downloadDocument());
    $sync->attach($doc);
});

Exchange changes without a server

use Nexdevit\NexPdf\Document;

$a = Document::open('shared.pdf');
$b = Document::open('shared.pdf');
$a->syncSetClientId('alice');
$b->syncSetClientId('bob');

$a->addAnnotation(0, 'Highlight', '#FFD400', 1.0, null, 72, 700, 300, 716);

$changes = $a->syncExportLocalJson(0);               // what alice pushes
$report = json_decode($b->syncApplyJson($changes), true);
echo count($report['applied']), ' ', count($report['ignored']), ' ', count($report['conflicts']), "\n";

$since = json_decode($changes, true)['clock'];       // 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

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: syncApplyJson throws NexPdfException.

The sync server

The NexPDF web viewer server hosts the sync endpoint that Sync 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 pushes and presence over it
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
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

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 and attach it.

On this page