Sample code for 30+ languages & platforms
Visual FoxPro Requires Chilkat v11.7.0+

Search for Text in a PDF

See more PDF Text Extraction Examples

Demonstrates the "search" operation, which finds every occurrence of a string in a PDF and returns each match with its page number and the text around it. Matching ignores case unless caseSensitive is true.

Chilkat Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loPdf
LOCAL loJson
LOCAL loJsonOut
LOCAL i
LOCAL lnCount_i

lnSuccess = 0

*  This example requires the Chilkat API to have been previously unlocked.
*  See Global Unlock Sample for sample code.

*  The three-page PDF used in this example is available at search_context.pdf

loPdf = CreateObject('Chilkat.Pdf')
lnSuccess = loPdf.LoadFile("qa_data/pdf/search_context.pdf")
IF (lnSuccess = 0) THEN
    ? loPdf.LastErrorText
    RELEASE loPdf
    CANCEL
ENDIF

loJson = CreateObject('Chilkat.JsonObject')
loJsonOut = CreateObject('Chilkat.JsonObject')

*  The string to find.
loJson.UpdateString("query","chilkat")

*  The number of characters returned before and after each match.  The default is 40.
loJson.UpdateInt("context",30)

lnSuccess = loPdf.ExtractText("search",loJson,loJsonOut)
IF (lnSuccess = 0) THEN
    ? loPdf.LastErrorText
    RELEASE loPdf
    RELEASE loJson
    RELEASE loJsonOut
    CANCEL
ENDIF

*  "count" is the number of matches.  Each match has the page, the matched text as it appears
*  in the PDF, and the text before and after it.
? "Matches: " + STR(loJsonOut.IntOf("count"))

i = 0
lnCount_i = loJsonOut.SizeOfArray("matches")
DO WHILE i < lnCount_i
    loJsonOut.I = i
    ? "page " + STR(loJsonOut.IntOf("matches[i].page")) + ": ..." + loJsonOut.StringOf("matches[i].before") + "[" + loJsonOut.StringOf("matches[i].text") + "]" + loJsonOut.StringOf("matches[i].after") + "..."
    i = i + 1
ENDDO

*  The search ignores case by default.  Set caseSensitive to find only the exact spelling.
loJson.UpdateBool("caseSensitive",1)
loJson.UpdateString("query","Chilkat")
lnSuccess = loPdf.ExtractText("search",loJson,loJsonOut)
IF (lnSuccess = 0) THEN
    ? loPdf.LastErrorText
    RELEASE loPdf
    RELEASE loJson
    RELEASE loJsonOut
    CANCEL
ENDIF

? "Case-sensitive matches for Chilkat: " + STR(loJsonOut.IntOf("count"))

*  Sample output:

*  Matches: 5
*  page 1: ...[Chilkat] River Field Notes The Chilkat...
*  page 1: ...Chilkat River Field Notes The [Chilkat] River runs for about fifty mi...
*  page 2: ...DAY ONE: UPPER [CHILKAT] FLATS Clear and cold, minus e...
*  page 2: ...he river is sometimes spelled [chilkat] in older records, and the val...
*  page 3: ...y because the fish run on the [Chilkat] was thinning. Two tagged bird...
*  Case-sensitive matches for Chilkat: 3

RELEASE loPdf
RELEASE loJson
RELEASE loJsonOut