Real-time collaboration
Keep several copies of a PDF in step with NexPDF Sync - sync pages, annotations, comments, form values and bookmarks through a NexPDF server, with per-property last-writer-wins merging, with NexPDF for Rust.
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. The change-set format is nexpdf-sync/2 (format 1 change sets are still read).
Record type | What | id |
|---|---|---|
page | One page: its dictionary and its place in the document | Stored on the page as /NexPDFId |
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: insert, delete, move and reorder, rotate, crop and content edits. Pages are
ordered by position keys, so every copy reaches the same page order, and /Dest destinations
follow their page. Shared objects are sent once and shared, not copied, however many records use
them.
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.
Connect to a server
With the cargo feature sync, nexpdf_sdk::sync::SyncClient (alias sync::Sync) keeps a
Document in sync with a NexPDF web viewer server. It pushes local edits, merges the others' as
they arrive and reconnects by itself.
[dependencies]
nexpdf-sdk = { version = "1.1", features = ["sync"] }use nexpdf_sdk::sync::{download_document, SyncClient, SyncEvent, SyncOptions};
use nexpdf_sdk::Document;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut options = SyncOptions::new("http://127.0.0.1:8080"); // or http://host/s/<session>
options.name = "Ana".into();
options.color = "#E8590C".into();
options.token = Some("nxt_…".into());
// Every copy starts from the server's document.
let (pdf, seq) = download_document(&options)?;
options.since = seq.unwrap_or(0);
let sync = SyncClient::new(Document::from_bytes(&pdf)?, options)?;
sync.on_event(|e| match e {
SyncEvent::Remote { changes, .. } => println!("{changes} remote changes merged"),
SyncEvent::Presence(peers) => println!("{} others here", peers.len()),
SyncEvent::Status(status) => println!("{status:?}"),
SyncEvent::Error(message) => eprintln!("{message}"),
_ => {}
});
sync.connect()?; // returns once the server said hello
sync.engine().add_blank_page()?; // edit while holding the engine lock
sync.set_presence(0, Some((120.0, 640.0)))?;
sync.flush()?; // or let the timer push it (every second by default)
sync.close();
Ok(())
}The client runs two threads (the connection and the push timer) and serialises every engine call
behind one mutex: edit the document through sync.engine(), which returns the locked Document,
and do not keep the guard across another call of the client.
| Call | Use |
|---|---|
SyncClient::new(document, options) | A client for the document (sets its sync client id). Nothing is sent yet |
connect() | Opens the change stream and waits for hello (at most connect_timeout). A refusal (401, 402, 403, 404) closes the client and is returned |
start() / wait_online(timeout) | Connect in the background without waiting / wait until online |
engine() | The document, locked, for your edits |
on_event(handler) / events() | Events to a handler, or to an mpsc::Receiver<SyncEvent> |
set_presence(page, cursor) | Shares this person's page and cursor (PDF points, or None) |
peers() | The others connected, as SyncPeer (client, name, color, page, cursor, user) |
flush() | Pushes the local changes now. Returns the server's result, or None when there was nothing new |
close() | Stops syncing and waits for the client's threads. Dropping the client closes it too. Pending edits stay in the document: flush() first |
status() / transport() | Connecting, Online, Offline or Closed / WebSocket or Sse while connected |
seq() / client_id() | Last server sequence seen (pass it as since to resume) / this client's id |
download_document() / attach(document) | After Reload: download the server's document again and switch to it |
Events are SyncEvent::Remote { report, changes }, Pushed, Conflict (informational: already
merged), Presence, Status, Reload(seq) and Error. They arrive on the client's threads (on
the caller's for flush). Do not call flush or hold engine() for long from a handler.
Options and transport
SyncOptions field | Default | Meaning |
|---|---|---|
url | http://host:port (local mode) or http://host/s/<session id> | |
client_id | random UUID | Stable id of this device |
name, color | Shown to the others (#RRGGBB for the cursor) | |
token | None | Session token, sent as Authorization: Bearer |
since | 0 | Server sequence to catch up from |
flush_interval | 1 s | How often local edits are pushed; zero = only on flush() |
reconnect_delay | 1 s | First reconnect delay, doubling up to 30 s |
connect_timeout | 15 s | Timeout for connecting and for the server's first answer |
transport | SyncTransport::Auto | Auto, WebSocket or Sse |
connector | TcpConnector | How connections are opened |
With Auto the client talks WebSocket (/api/sync/ws) and, when the socket never reaches hello
(a proxy that does not pass upgrades, a refused token), uses Server-Sent Events plus POST for the
rest of the session. It skips changes that carry its own client id, and it never reconnects after
401, 402, 403 or 404.
http:// and ws:// work out of the box. The crate has no TLS dependency, so https:// and
wss:// need a SyncConnector that wraps a TLS stream (rustls, native-tls). Its connect
returns a Box<dyn SyncStream>, a Read + Write + Send stream with set_read_timeout; check the
host name against the certificate:
use std::{io, sync::Arc, time::Duration};
use nexpdf_sdk::sync::{SyncConnector, SyncStream};
struct Tls; // wraps your TLS library
impl SyncConnector for Tls {
fn connect(&self, host: &str, port: u16, tls: bool, timeout: Duration)
-> io::Result<Box<dyn SyncStream>> {
my_tls_connect(host, port, tls, timeout) // a TcpStream, wrapped when `tls` is true
}
}
options.connector = Some(Arc::new(Tls));Exchange changes yourself
Without the server, or with a transport of your own, call the engine directly. Every sync_*
method takes &mut self, because exporting records the sync state in the document.
use nexpdf_sdk::Document;
fn main() -> nexpdf_sdk::Result<()> {
let mut a = Document::open("shared.pdf")?;
let mut b = Document::open("shared.pdf")?;
a.sync_set_client_id("alice")?;
b.sync_set_client_id("bob")?;
a.add_annotation(0, "Highlight", "#FFD400", 1.0, "", 72.0, 700.0, 300.0, 716.0)?;
let changes = a.sync_export_local_json_value(0)?; // what alice pushes (`serde` feature)
let report = b.sync_apply_json_value(&changes.to_string())?;
println!("{} {} {}", report["applied"], report["ignored"], report["conflicts"]);
let since = changes["clock"].as_u64().unwrap_or(0); // pass it next time
println!("next export from clock {since}");
Ok(())
}| 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 (a u64): 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. SyncClient::handle_event(event, data) feeds one
server event to the client, for a custom transport.
How changes merge
Each version is {"lamport", "client"}, ordered by the Lamport clock, then by 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 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.
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 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.
The sync server
The NexPDF web viewer server hosts the sync endpoints:
| Endpoint | Use |
|---|---|
GET /api/sync/document | The PDF to start from (header X-Sync-Seq) |
GET /api/sync/ws?since=&client=&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/stream?since=<seq>&client=<id> | Server-Sent Events: hello, changes, presence, reload (the fallback) |
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 |
hello carries transport and format. 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, and a restarted server rebuilds the document from both (a torn last line is skipped).
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.
Limits
- Attachments are not records.
- Replacing the document on the server sends
reload: download it again andattachit.