Q:
How to convert the document to greyscale
A:
There are multiple ways to do it, the idea is to manipulate the canvas image and change the color.
Method 1:
Use .filter()
Webviewer({
//...
}, document.getElementById('viewer')).then(instance => {
const tempCanvas = document.createElement('canvas');
instance.Core.documentViewer.on('pageComplete', function(pageIndex, canvas) {
if (canvas) {
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
var tempCtx = tempCanvas.getContext('2d');
tempCtx.filter = 'grayscale(1)';
tempCtx.drawImage(canvas, 0, 0);
var ctx = canvas.getContext('2d');
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(tempCanvas, 0, 0);
ctx.restore();
}
})
});
Note that this method is not supported by IE and Safari:
Method 2:
Iterate through every pixel in the canvas and manually convert it.
Webviewer({
//...
}, document.getElementById('viewer')).then(instance => {
const tempCanvas = document.createElement('canvas');
instance.Core.documentViewer.on('pageComplete', function(pageIndex, canvas) {
if (canvas) {
const ctx = canvas.getContext('2d');
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
const tempCtx = tempCanvas.getContext('2d');
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
let pixels = imgData.data;
for (var i = 0; i < pixels.length; i += 4) {
let lightness = parseInt((pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3);
pixels[i] = lightness;
pixels[i + 1] = lightness;
pixels[i + 2] = lightness;
}
tempCtx.drawImage(canvas, 0, 0);
tempCtx.putImageData(imgData, 0, 0);
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(tempCanvas, 0, 0);
ctx.restore();
}
})
});
Note that this method is a little slow.