Real-time collaboration
Keep several copies of a PDF in step with NexPDF Sync and the Go sync client, with pages, annotations, comments, form values and bookmarks merged per property, last writer wins, with NexPDF for Go.
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 |
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
a, err := nexpdf.Open("shared.pdf")
if err != nil {
log.Fatal(err)
}
defer a.Close()
b, err := nexpdf.Open("shared.pdf")
if err != nil {
log.Fatal(err)
}
defer b.Close()
a.SyncSetClientId("alice")
b.SyncSetClientId("bob")
a.AddAnnotation(0, "Highlight", "#FFD400", 1.0, "", 72, 700, 300, 716)
changes, err := a.SyncExportLocalJSON(0) // what alice pushes
if err != nil {
log.Fatal(err)
}
s, err := b.SyncApplyJSON(changes)
if err != nil {
log.Fatal(err)
}
var report struct {
Applied []string `json:"applied"`
Ignored []string `json:"ignored"`
Conflicts []json.RawMessage `json:"conflicts"`
}
json.Unmarshal([]byte(s), &report)
fmt.Println(report.Applied, report.Ignored, len(report.Conflicts))
var set struct {
Clock uint64 `json:"clock"` // pass it next time
}
json.Unmarshal([]byte(changes), &set)| Call | Returns |
|---|---|
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.
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: SyncApplyJSON returns a *nexpdf.Error.
The sync client
nexpdf.NewSync(doc, opts) keeps a *Document in sync with a NexPDF web viewer server. It talks
WebSocket (/api/sync/ws, a built-in client for ws:// and wss://) and falls back to
Server-Sent Events plus POST for the session when the socket never reaches hello (a proxy that
does not pass upgrades, a refused token). It applies the others' changes (skipping its own), pushes
SyncExportLocalJSON every second, and reconnects by itself (1 s doubling up to 30 s, never after
401, 402, 403 or 404).
doc, err := nexpdf.Open("shared.pdf") // the same file the server has
if err != nil {
log.Fatal(err)
}
defer doc.Close()
var s *nexpdf.Sync
s, err = nexpdf.NewSync(doc, nexpdf.SyncOptions{
URL: "https://viewer.example.com/s/abc",
Token: token,
Name: "Ana",
Color: "#E91E63",
OnRemote: func(report nexpdf.SyncApplyReport, changes nexpdf.SyncChangeSet) {
fmt.Println("applied", len(report.Applied)) // redraw
},
OnPresence: func(peers []nexpdf.SyncPeer) {
for _, p := range peers {
fmt.Println(p.Name, p.Page)
}
},
OnStatus: func(st nexpdf.SyncStatus) { fmt.Println(st) },
OnReload: func(seq int64) {
pdf, err := s.DownloadDocument(context.Background()) // also sets Seq
if err != nil {
return
}
if fresh, err := nexpdf.OpenBytes(pdf); err == nil {
s.Attach(fresh)
}
},
OnError: func(err error) { log.Println("sync:", err) },
})
if err != nil {
log.Fatal(err)
}
defer s.Close()
ctx := context.Background()
if err := s.Connect(ctx); err != nil { // returns once the server said hello
log.Fatal(err)
}
s.WithEngine(func() { // edit while no remote change is being applied
doc.AddAnnotation(0, "Highlight", "#FFD400", 1.0, "", 72, 700, 300, 716)
})
s.Flush(ctx) // or let the timer push within a second
s.SetPresence(ctx, 0, &nexpdf.SyncCursor{X: 120, Y: 300})SyncOptions field | Meaning |
|---|---|
URL | Server base URL: http://host (local mode) or https://host/s/<session id>. Required |
ClientID | Stable id of this device; random when empty |
Name, Color | Shown to the others (#RRGGBB for the cursor) |
Token | Session token, sent as Authorization: Bearer and as the bearer.<token> subprotocol |
Since | Sequence to catch up from (a previous Seq()); 0 = everything |
FlushInterval | How often local edits are pushed: 0 = 1 s, nexpdf.NoAutoFlush = only on Flush |
ReconnectDelay | First reconnect delay, doubling up to 30 s; 0 = 1 s |
Transport | nexpdf.SyncAuto (default), nexpdf.SyncWebSocket or nexpdf.SyncSSE |
HTTPClient, TLSConfig | The *http.Client for SSE, POST and download, and the *tls.Config for wss:// |
| Method | Use |
|---|---|
Connect(ctx) | Starts syncing and returns once the server said hello. If ctx ends first it returns ctx.Err() and keeps trying in the background |
Flush(ctx) | Pushes the local changes now; returns the *SyncPushResult, or nil, nil when there was nothing to push |
SetPresence(ctx, page, cursor) | Shares the page and a cursor in PDF points (nil for none) |
WithEngine(fn) | Runs fn holding the engine lock; edit the document there |
DownloadDocument(ctx) | The server's current document; sets Seq from X-Sync-Seq |
Attach(doc) | Switches to another document, for example after OnReload |
Close() | Stops syncing; pending local edits stay in the document (Flush first) |
Status(), Transport(), Peers(), Seq(), ClientID() | Current state |
Callbacks (OnRemote, OnPushed, OnConflict, OnPresence, OnStatus, OnReload, OnError)
run on the client's goroutines, never while the engine lock is held. OnReload means the
document on the server was replaced: download it again and Attach it. A fatal HTTP status comes
to OnError as a *nexpdf.SyncHTTPError.
The sync server
The NexPDF web viewer server hosts the sync endpoint the client above 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 push and presence messages |
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 (the fallback) |
POST /api/sync/push | A change set of the client's own changes (the fallback) |
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. 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 andAttachit.