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

Lua
local chilkat = require("chilkat")

-- 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

local pdf = chilkat.Pdf.new()
local success = pdf:load_file("qa_data/pdf/search_context.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()

-- The string to find.
json:update_string("query", "chilkat")

-- The number of characters returned before and after each match.  The default is 40.
json:update_int("context", 30)

success = pdf:extract_text("search", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

-- "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.
print("Matches: " .. jsonOut:int_of("count"))

local i = 0
local count_i = jsonOut:size_of_array("matches")
while i < count_i do
    jsonOut.i = i
    print("page " .. jsonOut:int_of("matches[i].page") .. ": ..." .. jsonOut:string_of("matches[i].before") .. "[" .. jsonOut:string_of("matches[i].text") .. "]" .. jsonOut:string_of("matches[i].after") .. "...")
    i = i + 1
end

-- The search ignores case by default.  Set caseSensitive to find only the exact spelling.
json:update_bool("caseSensitive", true)
json:update_string("query", "Chilkat")
success = pdf:extract_text("search", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

print("Case-sensitive matches for Chilkat: " .. jsonOut:int_of("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