Skip to Content
NexPDF

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 control memory with NexPDF for PHP.

English

License module

Comparing documents, linearized saving and the memory calls 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 PNG.

use Nexdevit\NexPdf\Document;

$a = Document::open('v1.pdf');
$b = Document::open('v2.pdf');

$diff = json_decode($a->compareJson($b, 72), true);
echo $diff['pages_a'], ' pages before, ', $diff['pages_b'], " after\n";

foreach ($diff['pages'] as $page) {
    if ($page['text_changed'] || $page['visual_diff'] > 0.001) {
        printf("page %d: %.2f%% of the pixels changed\n", $page['page'] + 1, $page['visual_diff'] * 100);
        file_put_contents(sprintf('diff-%d.png', $page['page'] + 1), $a->compareOverlayPng($b, $page['page'], 110));
    }
}

To see which words changed (inserted, deleted, replaced and moved text, and an annotated PDF of the changes), use Word-level comparison.

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.

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 return a JSON report; save afterwards.

$doc = Document::open('large.pdf');

$r = json_decode($doc->optimize(), true);
printf("%d streams compressed, %d objects pruned, %d bytes saved\n",
    $r['streams_compressed'], $r['objects_pruned'], $r['bytes_saved']);

$f = json_decode($doc->subsetFonts(), true);
printf("%d fonts subset: %d -> %d bytes\n", $f['fonts_subset'], $f['bytes_before'], $f['bytes_after']);

$doc->save('small.pdf');

Fonts that may still be needed for new text are left whole and counted in fonts_skipped.

Fast Web View

Linearized files let a browser show the first page before the rest downloads:

$doc->save('web.pdf', linearized: true);

Memory

memoryUsageBytes() estimates the native memory a document uses (PHP's memory_get_usage() does not include it). trimMemory() compacts its internal buffers and drops objects nothing refers to any more, and returns the bytes reclaimed. Call it in long-running workers after large edits or batch work:

echo intdiv($doc->memoryUsageBytes(), 1024), " KiB\n";
$freed = $doc->trimMemory();

The document stays fully usable. close() frees everything. See Platform notes for workers and memory.

On this page