Sample code for 30+ languages & platforms
Classic ASP 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 Classic ASP Downloads

Classic ASP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
success = 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

set pdf = Server.CreateObject("Chilkat.Pdf")
success = pdf.LoadFile("qa_data/pdf/search_context.pdf")
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( pdf.LastErrorText) & "</pre>"
    Response.End
End If

set json = Server.CreateObject("Chilkat.JsonObject")
set jsonOut = Server.CreateObject("Chilkat.JsonObject")

'  The string to find.
success = json.UpdateString("query","chilkat")

'  The number of characters returned before and after each match.  The default is 40.
success = json.UpdateInt("context",30)

success = pdf.ExtractText("search",json,jsonOut)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( pdf.LastErrorText) & "</pre>"
    Response.End
End If

'  "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.
Response.Write "<pre>" & Server.HTMLEncode( "Matches: " & jsonOut.IntOf("count")) & "</pre>"

i = 0
count_i = jsonOut.SizeOfArray("matches")
Do While i < count_i
    jsonOut.I = i
    Response.Write "<pre>" & Server.HTMLEncode( "page " & jsonOut.IntOf("matches[i].page") & ": ..." & jsonOut.StringOf("matches[i].before") & "[" & jsonOut.StringOf("matches[i].text") _
         & "]" & jsonOut.StringOf("matches[i].after") & "...") & "</pre>"
    i = i + 1
Loop

'  The search ignores case by default.  Set caseSensitive to find only the exact spelling.
success = json.UpdateBool("caseSensitive",1)
success = json.UpdateString("query","Chilkat")
success = pdf.ExtractText("search",json,jsonOut)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( pdf.LastErrorText) & "</pre>"
    Response.End
End If

Response.Write "<pre>" & Server.HTMLEncode( "Case-sensitive matches for Chilkat: " & jsonOut.IntOf("count")) & "</pre>"

'  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

%>
</body>
</html>