Compare PDFs by using image pixel by pixel comparison
If you would prefer to implement your own diffing algorithm, we provide APIs to retrieve image data from documents. You can use these images to compare the pixels between two documents by overlaying them and generating the output image. This is best for very custom uses. For most cases, we recommend using PDF Overlay.
The setup is similar to the previous example, except this time we don't need to enable the full API. We can rewrite our getDocument function to look like this:
Please note that the following code snippets are very generic and assume both documents are the same size and have the same amount of pages. Please make sure you handle these cases yourself if you plan to implement this into your own project.
For most cases, we recommend using PDF Overlay - as seen in our Image Overlay Demo or full code sample.
const [doc1, doc2] = await Promise.all([
Core.createDocument('https://s3.amazonaws.com/pdftron/pdftron/example/test_doc_1.pdf'),
Core.createDocument('https://s3.amazonaws.com/pdftron/pdftron/example/test_doc_2.pdf')
])const [doc1, doc2] = await Promise.all([
CoreControls.createDocument('https://s3.amazonaws.com/pdftron/pdftron/example/test_doc_1.pdf'),
CoreControls.createDocument('https://s3.amazonaws.com/pdftron/pdftron/example/test_doc_2.pdf')
])Now we can write a function to get image data from these documents.
const getImageData = (doc) => {
return new Promise(resolve => {
doc.loadCanvas({
pageNumber: 1,
drawComplete: (pageCanvas) => {
const ctx = pageCanvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, pageCanvas.width, pageCanvas.height);
resolve(imageData);
}
})
})
}
// get image data for the first page of both our documents
const [imageData1, imageData2] = await Promise.all([
getImageData(doc1, 0),
getImageData(doc2, 0)
]);Now, we can loop over these pixels, and compare them however we wish.
Last updated
Was this helpful?