Search for text in a PDF on Server/Desktop

To search for text in a PDF using regular expression and then apply a link annotation on the highlighted result.

In this example, we add a link annotation but any other types of annotations can be applied here such as redaction annotations in the case of a search and redact workflow.

1doc = PDFDoc(filename)
2txt_search = TextSearch()
3mode = TextSearch.e_whole_word | TextSearch.e_page_stop
4pattern = ""
5
6# use regular expression to find credit card number
7mode |= TextSearch.e_reg_expression | TextSearch.e_highlight
8txt_search.SetMode(mode)
9pattern = "\\d{4}-\\d{4}-\\d{4}-\\d{4}" #or "(\\d{4}-){3}\\d{4}"
10txt_search.SetPattern(pattern)
11
12# call Begin() method to initialize the text search.
13txt_search.Begin(doc, pattern, mode)
14searchResult = txt_search.Run()
15
16if searchResult.IsFound():
17 # add a link annotation based on the location of the found instance
18 hlts = searchResult.GetHighlights()
19 hlts.Begin(doc)
20
21 while (hlts.HasNext()):
22 cur_page = doc.GetPage(hlts.GetCurrentPageNumber())
23 quadsInfo = hlts.GetCurrentQuads()
24
25 i = 0
26 while i < len(quadsInfo):
27 q = quadsInfo[i]
28 # assume each quad is an axis-aligned rectangle
29 x1 = min(min(min(q.p1.x, q.p2.x), q.p3.x), q.p4.x)
30 x2 = max(max(max(q.p1.x, q.p2.x), q.p3.x), q.p4.x)
31 y1 = min(min(min(q.p1.y, q.p2.y), q.p3.y), q.p4.y)
32 y2 = max(max(max(q.p1.y, q.p2.y), q.p3.y), q.p4.y)
33 hyper_link = Link.Create(doc.GetSDFDoc(), Rect(x1, y1, x2, y2), Action.CreateURI(doc.GetSDFDoc(), "http://www.apryse.com"))
34 cur_page.AnnotPushBack(hyper_link)
35 i = i + 1
36 hlts.Next()

Search PDF files for text - Full Sample
Full code sample which shows how to use TextSearch to search text on PDF pages using regular expressions.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales