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.

1PDFDoc doc = new PDFDoc(filename);
2Int32 page_num = 0;
3String result_str = "", ambient_string = "";
4Highlights hlts = new Highlights();
5TextSearch txt_search = new TextSearch();
6Int32 mode = (Int32)(TextSearch.SearchMode.e_whole_word | TextSearch.SearchMode.e_page_stop | TextSearch.SearchMode.e_highlight);
7String pattern = "";
8
9//use regular expression to find credit card number
10mode |= (Int32)(TextSearch.SearchMode.e_reg_expression | TextSearch.SearchMode.e_highlight);
11txt_search.SetMode(mode);
12String pattern = "\\d{4}-\\d{4}-\\d{4}-\\d{4}"; //or "(\\d{4}-){3}\\d{4}"
13txt_search.SetPattern(pattern);
14
15//call Begin() method to initialize the text search.
16txt_search.Begin( doc, pattern, mode, -1, -1 );
17TextSearch.ResultCode code = txt_search.Run(ref page_num, ref result_str, ref ambient_string, hlts );
18
19if ( code == TextSearch.ResultCode.e_found )
20{
21 //add a link annotation based on the location of the found instance
22 hlts.Begin(doc);
23 while (hlts.HasNext())
24 {
25 Page cur_page = doc.GetPage(hlts.GetCurrentPageNumber());
26 double[] quads = hlts.GetCurrentQuads();
27 int quad_count = quads.Length / 8;
28 for (int i = 0; i < quad_count; ++i)
29 {
30 //assume each quad is an axis-aligned rectangle
31 int offset = 8 * i;
32 double x1 = Math.Min(Math.Min(Math.Min(quads[offset + 0], quads[offset + 2]), quads[offset + 4]), quads[offset + 6]);
33 double x2 = Math.Max(Math.Max(Math.Max(quads[offset + 0], quads[offset + 2]), quads[offset + 4]), quads[offset + 6]);
34 double y1 = Math.Min(Math.Min(Math.Min(quads[offset + 1], quads[offset + 3]), quads[offset + 5]), quads[offset + 7]);
35 double y2 = Math.Max(Math.Max(Math.Max(quads[offset + 1], quads[offset + 3]), quads[offset + 5]), quads[offset + 7]);
36
37 Annots.Link hyper_link = Annots.Link.Create(doc, new Rect(x1, y1, x2, y2), Action.CreateURI(doc, "http://www.apryse.com"));
38 hyper_link.RefreshAppearance();
39 cur_page.AnnotPushBack(hyper_link);
40 }
41 hlts.Next();
42 }
43}

Search PDF files for text
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