|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/unidoc/unipdf/v3/extractor" |
| 9 | + "github.com/unidoc/unipdf/v3/model" |
| 10 | +) |
| 11 | + |
| 12 | +func main() { |
| 13 | + // Input parameters |
| 14 | + filePath := "./test-data/file1.pdf" // Path to the PDF file |
| 15 | + pattern := "Australia" // Text pattern to search for |
| 16 | + pages := []int{1} // Page numbers to search on |
| 17 | + |
| 18 | + // Create a new PDF reader |
| 19 | + reader, _, err := model.NewPdfReaderFromFile(filePath, nil) |
| 20 | + if err != nil { |
| 21 | + fmt.Printf("Failed to create PDF reader: %v\n", err) |
| 22 | + os.Exit(1) |
| 23 | + } |
| 24 | + |
| 25 | + // Create an Editor object for searching |
| 26 | + editor := extractor.NewEditor(reader) |
| 27 | + |
| 28 | + // Perform the search for the specified pattern on the given pages |
| 29 | + matchesPerPage, err := editor.Search(pattern, pages) |
| 30 | + if err != nil { |
| 31 | + fmt.Printf("Failed to search pattern: %v\n", err) |
| 32 | + os.Exit(1) |
| 33 | + } |
| 34 | + |
| 35 | + // Print formatted search results |
| 36 | + printSearchResults(matchesPerPage, pages, pattern) |
| 37 | +} |
| 38 | + |
| 39 | +// printSearchResults formats and prints the search results. |
| 40 | +// It displays indexes as [beg:end] and locations as {Llx Lly Urx Ury}. |
| 41 | +// If no matches are found for a page, it prints a not found message. |
| 42 | +func printSearchResults(matchesPerPage map[int]extractor.Match, pages []int, pattern string) { |
| 43 | + foundAny := false // Flag to check if any match is found across all pages |
| 44 | + |
| 45 | + for _, page := range pages { |
| 46 | + result, exists := matchesPerPage[page] |
| 47 | + if exists && len(result.Indexes) > 0 { |
| 48 | + foundAny = true |
| 49 | + fmt.Printf("Page %d:\n", page) |
| 50 | + |
| 51 | + // Prepare index strings |
| 52 | + var indexStrings []string |
| 53 | + for _, idx := range result.Indexes { |
| 54 | + indexStrings = append(indexStrings, fmt.Sprintf("[%d:%d]", idx[0], idx[1])) |
| 55 | + } |
| 56 | + fmt.Printf("indexes: %s\n", strings.Join(indexStrings, ", ")) |
| 57 | + |
| 58 | + // Prepare location strings |
| 59 | + var locationStrings []string |
| 60 | + for _, box := range result.Locations { |
| 61 | + locationStrings = append(locationStrings, fmt.Sprintf("{%.2f %.2f %.2f %.2f}", box.BBox.Llx, box.BBox.Lly, box.BBox.Urx, box.BBox.Ury)) |
| 62 | + } |
| 63 | + fmt.Printf("locations: %s\n\n", strings.Join(locationStrings, ", ")) |
| 64 | + } else { |
| 65 | + // If no matches found for the current page |
| 66 | + fmt.Printf("Page %d:\n", page) |
| 67 | + fmt.Println("pattern didn't match any text\n") |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + if !foundAny { |
| 72 | + // If no matches found in any of the pages |
| 73 | + fmt.Println("pattern didn't match any text in the specified pages.") |
| 74 | + } |
| 75 | +} |
0 commit comments