Q:
Do you have a tool to display a rectangle to select a zone and when we release it (or when we click a button) the annotation disappears and we create the image with the selected zone of the rectangle?
A:
You can create a custom tool that does this. For example:
WebViewer({
path: 'lib',
initialDoc: 'myfile.pdf'
}, document.getElementById('viewer'))
.then(function(instance) {
var Tools = instance.Tools;
var Annotations = instance.Annotations;
var docViewer = instance.docViewer;
var annotManager = instance.annotManager;
var ImageSelectTool = function(docViewer) {
Tools.RectangleCreateTool.apply(this, arguments);
};
ImageSelectTool.prototype = new Tools.RectangleCreateTool();
var getPageCanvas = function(pageIndex) {
return instance.iframeWindow.document.querySelector('#pageContainer' + pageIndex + ' .canvas' + pageIndex);
};
docViewer.on("documentLoaded", function(event) {
var imageSelectToolName = 'ImageSelect';
var imageSelectTool = new ImageSelectTool(docViewer);
instance.registerTool({
toolName: imageSelectToolName,
toolObject: imageSelectTool,
buttonImage: 'https://example.com/button/image.png',
buttonName: 'imageSelectToolButton',
tooltip: 'Image selection'
});
instance.setHeaderItems(function(header) {
var imageSelectButton = {
type: 'toolButton',
toolName: imageSelectToolName,
dataElement: 'imageSelectToolButton'
};
header.get('freeHandToolGroupButton').insertBefore(imageSelectButton);
});
imageSelectTool.on('annotationAdded', function(annotation) {
var pageIndex = annotation.PageNumber;
// get the canvas for the page
var pageCanvas = getPageCanvas(pageIndex);
var topOffset = parseFloat(pageCanvas.style.top) || 0;
var leftOffset = parseFloat(pageCanvas.style.left) || 0;
var zoom = docViewer.getZoom() * instance.iframeWindow.utils.getCanvasMultiplier();
var x = annotation.X * zoom - leftOffset;
var y = annotation.Y * zoom - topOffset;
var width = annotation.Width * zoom;
var height = annotation.Height * zoom;
var copyCanvas = document.createElement('canvas');
copyCanvas.width = width;
copyCanvas.height = height;
var ctx = copyCanvas.getContext('2d');
// copy the image data from the page to a new canvas so we can get the data URL
ctx.drawImage(pageCanvas, x, y, width, height, 0, 0, width, height);
// create a new stamp annotation that will have the image data that was under the rectangle
var stampAnnot = new Annotations.StampAnnotation();
stampAnnot.PageNumber = annotation.PageNumber;
stampAnnot.X = annotation.X;
stampAnnot.Y = annotation.Y;
stampAnnot.Width = annotation.Width;
stampAnnot.Height = annotation.Height;
stampAnnot.Author = annotManager.getCurrentUser();
stampAnnot.ImageData = copyCanvas.toDataURL();
annotManager.addAnnotation(stampAnnot);
annotManager.selectAnnotation(stampAnnot);
// we don't need the rectangle anymore so we can remove it
annotManager.deleteAnnotation(annotation);
});
});
});