Compare and optimise
Compare two PDF versions page by page, make files smaller by pruning objects and subsetting fonts, save for Fast Web View and keep memory in check with NexPDF for React Native.
License module
Comparing documents, linearized saving, memoryUsageBytes and trimMemory work without a key. optimize and
subsetFonts need the editor module (Startup tier and above).
Compare two versions
compareJson(other, dpi) compares two documents page by page: whether the text changed and how
much of the rendered page differs. compareOverlayPng(other, pageIndex, dpi) draws the differences
of one page as a base64 PNG.
import { NexPdf } from '@nexdevit/nexpdf-react-native';
const a = await NexPdf.open(v1Base64);
const b = await NexPdf.open(v2Base64);
try {
const diff = JSON.parse(await a.compareJson(b, 72));
console.log(diff.pages_a, 'pages before,', diff.pages_b, 'after');
for (const page of diff.pages) {
if (page.text_changed || page.visual_diff > 0.001) {
console.log(`page ${page.page + 1}: ${(page.visual_diff * 100).toFixed(2)}% of the pixels changed`);
const overlay = await a.compareOverlayPng(b, page.page, 110); // base64 PNG
}
}
} finally {
await a.close();
await b.close();
}visual_diff is the share of differing pixels, from 0 to 1. A low resolution (72 dpi) is enough to
find changed pages; the overlay resolution is clamped to 18-300 dpi. Show an overlay with
<Image source={{ uri: 'data:image/png;base64,' + overlay }} />.
To see which words changed (inserted, deleted, replaced and moved text, and an annotated PDF of the changes), use Word-level comparison.
Make files smaller
optimize() compresses uncompressed streams and removes objects nothing refers to.
subsetFonts() replaces embedded TrueType, OpenType and CFF fonts with subsets of the glyphs the
document uses. Both resolve to a JSON report; save afterwards.
const r = JSON.parse(await doc.optimize());
console.log(r.streams_compressed, 'streams compressed,', r.objects_pruned, 'objects pruned,',
r.bytes_saved, 'bytes saved');
const f = JSON.parse(await doc.subsetFonts());
console.log(`${f.fonts_subset} fonts subset: ${f.bytes_before} -> ${f.bytes_after} bytes`);
const small = await doc.saveBytes();Fonts that may still be needed for new text are left whole and counted in fonts_skipped. A
smaller file is also cheaper to move across the bridge.
Fast Web View
Linearized files let a browser show the first page before the rest downloads:
const web = await doc.saveLinearized();Memory
memoryUsageBytes() estimates the memory a document uses, and trimMemory() (1.1 and later)
compacts the buffers of a document that has been edited for a long time and resolves to the
approximate number of bytes reclaimed:
console.log(Math.round((await doc.memoryUsageBytes()) / 1024), 'KiB');
const reclaimed = await doc.trimMemory();Closing a document frees everything it holds. See Platform notes for threading and memory.