Only searching on the visible pages

39 views
Skip to first unread message

Matt Parizeau

unread,
Sep 27, 2018, 6:36:42 PM9/27/18
to PDFTron WebViewer
Q:

If I do a full search using textSearchInit it will search through every page starting at the first one. Is it possible to only search the visible pages and update the results as the user navigates to new pages?

A:

You can use lower level APIs to get the text, search through it yourself and then get the quads to generate the result:

var hasSearched = {};

var searchPage = function(searchString, pageIndex) {
 
if (hasSearched[pageIndex]) {
   
return;
 
}
  hasSearched
[pageIndex] = true;

 
var strLength = searchString.length;

 
var doc = readerControl.docViewer.getDocument();
  doc
.loadPageText(pageIndex, function(text) {
   
var start = 0;
   
var index;

   
// search through the text for the indices that the search string starts at
   
while ((index = text.indexOf(searchString, start)) !== -1) {
     
// pass in the index of the text relative to all text on the page
      doc
.getTextPosition(pageIndex, index, index + strLength, function(quads) {
       
var firstChar = quads[0];
       
var lastChar = quads[quads.length - 1];
       
var quad = {
          x1
: firstChar.x1,
          y1
: firstChar.y1,
          x2
: lastChar.x2,
          y2
: lastChar.y2,
          x3
: lastChar.x3,
          y3
: lastChar.y3,
          x4
: firstChar.x4,
          y4
: firstChar.y4
       
};

       
var result = {
          quads
: [quad],
          page_num
: pageIndex
       
};

        readerControl
.docViewer.displayAdditionalSearchResult(result);
     
});

      start
= index + strLength;
   
}
 
});
};

var searchPages = function(searchString, pages) {
 
for (var i = 0; i < pages.length; ++i) {
   
var pageIndex = pages[i];
    searchPage
(searchString, pageIndex);
 
}
};

var startNewSearch = function(searchString) {
 
var displayMode = readerControl.docViewer.getDisplayModeManager().getDisplayMode();
  searchPages
(searchString, displayMode.getVisiblePages());

  readerControl
.docViewer.on('visiblePagesChanged.search', function(e, visiblePages) {
    searchPages
(searchString, visiblePages);
 
});
};

// call this function when you want to stop the current search
var stopSearch = function() {
  readerControl
.docViewer.off('visiblePagesChanged.search');
  readerControl
.docViewer.clearSearchResults();
};

$
(document).on('documentLoaded', function() {
  startNewSearch
('the');
});

Reply all
Reply to author
Forward
0 new messages