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

Get Every Occurrence of a Label in a PDF

See more PDF Text Extraction Examples

Demonstrates the "labelOccurrence" option. When the same label appears more than once (for example "Total:" on each of several receipts), "first" (the default) uses the first occurrence, "all" returns every occurrence with its page, and a number selects one occurrence.

Chilkat Rust Downloads

Rust

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

// The PDF used in this example (three receipts, one per page) is available at three_receipts.pdf

let pdf = chilkat::Pdf::new();
if pdf.load_file("qa_data/pdf/three_receipts.pdf").is_err() {
    println!("{}", pdf.last_error_text());
    return;
}

let json = chilkat::JsonObject::new();
let json_out = chilkat::JsonObject::new();

// Each of the three pages is a receipt with a "Total:" line.
let _ = json.update_string("label", "Total");
let _ = json.update_string("labelValue", "right");

// By default only the first occurrence (in reading order) is used.
if pdf.extract_text("text", &json, &json_out).is_err() {
    println!("{}", pdf.last_error_text());
    return;
}

println!("First total: {}", json_out.string_of("text").unwrap_or_default());

// labelOccurrence "all" returns every occurrence.  The "text" member holds the values joined
// by line breaks, and labelMatches has one entry per occurrence with its page.
let _ = json.update_string("labelOccurrence", "all");
if pdf.extract_text("text", &json, &json_out).is_err() {
    println!("{}", pdf.last_error_text());
    return;
}

let mut i = 0;
let count_i = json_out.size_of_array("labelMatches");
while i < count_i {
    json_out.set_i(i);
    println!("Page {} total: {}", json_out.int_of("labelMatches[i].page"), json_out.string_of("labelMatches[i].text").unwrap_or_default());
    i = i + 1;
}

// A number selects one occurrence: 2 is the second.
let _ = json.update_int("labelOccurrence", 2);
if pdf.extract_text("text", &json, &json_out).is_err() {
    println!("{}", pdf.last_error_text());
    return;
}

println!("Second total: {}", json_out.string_of("text").unwrap_or_default());

// The occurrences are counted over the selected pages, so combining "pages" with the label
// is another way to pick one receipt:
let _ = json.update_string("labelOccurrence", "first");
let _ = json.update_string("pages", "3");
let _ = json.update_string("label", "Receipt No.");
if pdf.extract_text("text", &json, &json_out).is_err() {
    println!("{}", pdf.last_error_text());
    return;
}

println!("Receipt number on page 3: {}", json_out.string_of("text").unwrap_or_default());

// Sample output:

// First total: $19.86
// Page 1 total: $19.86
// Page 2 total: $17.34
// Page 3 total: $23.62
// Second total: $17.34
// Receipt number on page 3: 1003