viewerElement.addEventListener('documentLoaded', async () => {
const { docViewer } = viewer.getInstance();
const doc = docViewer.getDocument();
const top_x = 310, top_y = 320;
const bottom_x = 250, bottom_y = 150;
const pageIndex = 0;
const text = await extractText(doc, pageIndex, top_x, top_y, bottom_x, bottom_y);
console.log(text);
})
const extractText = (doc, pageIndex, top_x, top_y, bottom_x, bottom_y) => {
return new Promise(resolve => {
doc.loadPageText(pageIndex, text => {
doc.getTextPosition(pageIndex, 0, text.length, (arr) => {
// temp array to store the position of characters
var indies = []
// filter out array with given x, y coordinates
arr = arr.filter((item, index) => {
if (item.x4 >= top_x && item.y4 >= top_y &&
item.x2 <= (top_x + bottom_x) && item.y2 <= (top_y + bottom_y)) {
indies.push(index)
return true;
}
return false;
})
// concatenate chars into string
let str = '';
for (let i = 0, len = indies.length; i < len; i++) {
str += text[indies[i]];
}
// filtered arr can be used for other purposes, e.g. debugging
// return/resolve concatenated string
resolve(str)
});
});
});
}