Word-level comparison
Compare the text of two PDF versions word by word, list inserted, deleted, replaced and moved text, and produce an annotated PDF of the changes in the browser with NexPDF for the web.
License module
Comparison works without a key (viewer module).
Compare and optimise shows which pages changed and by how many pixels. Word-level comparison tells you what text changed: words inserted, deleted, replaced and moved, with their positions on both versions.
List the changes
old.raw.compareTextJson(new.raw, optionsJson) compares the document it is called on (the old
version) with the other one:
import { loadNexPdf } from '@nexdevit/nexpdf-web/engine';
const nex = await loadNexPdf();
const v1 = await nex.PdfDocument.fromUrl('/contract-v1.pdf');
const v2 = await nex.PdfDocument.fromUrl('/contract-v2.pdf');
const diff = JSON.parse(v1.raw.compareTextJson(v2.raw));
const s = diff.summary;
console.log(`${(s.similarity * 100).toFixed(1)}% similar: +${s.words_inserted} -${s.words_deleted} words, ${s.moved} moves`);
for (const c of diff.changes) {
console.log(c.type, JSON.stringify(c.old_text), '->', JSON.stringify(c.new_text), c.old_page, c.new_page);
}Each change has type (inserted, deleted, replaced or moved), old_text, new_text,
old_page, new_page, and old_rects / new_rects ({"page", "rect": [llx, lly, urx, ury]}) to
highlight it, for example with
pageView(page).rectToView over the
rendered pages. The summary counts words_old, words_new, words_equal, the changes by type,
the words inserted, deleted and moved, similarity (0 to 1) and truncated.
Words hyphenated across lines are joined before comparing, and compound hyphens are kept
(self-driving, long-term).
Options
| Option | Default | Meaning |
|---|---|---|
ignore_case | false | Treat upper and lower case as equal |
ignore_punctuation | false | Ignore punctuation differences |
detect_moves | true | Report text that moved as moved instead of deleted plus inserted |
min_move_words | 3 | Shortest run of words reported as a move |
align | document | document compares the whole text; index compares page 1 with page 1, and so on |
page_map | Explicit page pairs, [[old_page, new_page], …] |
An annotated PDF of the changes
old.raw.compareAnnotate(new.raw, optionsJson) returns a new PDF (Uint8Array) with highlight
annotations: deleted words in red on the old pages, inserted words in green on the new pages, moved
text in blue.
const pdf = v1.raw.compareAnnotate(v2.raw, JSON.stringify({ output: 'side_by_side', author: 'Review bot' }));
const changes = nex.PdfDocument.fromBytes(pdf); // render it, or offer it as a downloadIt takes the options above plus output (both: old pages then new pages, the default; old;
new; or side_by_side: one wide page per pair with the marks drawn in), author, and
deleted_color, inserted_color and moved_color (#RRGGBB).