The pagination here that I refer is null. Pls help me also if I made the correct implementation of highlighting the words in buffered image that match in the characters in the search field.
private void addSearchKeyEventFilter(Pagination pagination) {
if (searchPane.getScene() != null) {
setupKeyEventFilters(searchPane.getScene(), pagination);
} else {
searchPane.sceneProperty().addListener((observable, oldScene, newScene) -> {
if (newScene != null) {
setupKeyEventFilters(newScene, pagination);
}
});
}
}
private void setupKeyEventFilters(Scene scene, Pagination pagination) {
scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.F && event.isControlDown()) {
searchPane.setVisible(true);
searchField.requestFocus();
event.consume(); // Consume the event to prevent it from bubbling up
} else if (event.getCode() == KeyCode.ESCAPE) {
searchPane.setVisible(false);
event.consume(); // Consume the event to prevent it from bubbling up
}
});
searchField.setOnAction(event -> performSearch( pagination, pagePane, renderer));
searchButton.setOnAction(event -> performSearch( pagination, pagePane, renderer));
}
private void performSearch(Pagination pagination, Pane pagePane, PDFRenderer renderer) {
String searchText = searchField.getText();
if (searchText == null || searchText.isEmpty()) {
return;
}
if (pagination == null) {
System.err.println("Error: pagination is null");
return;
}
if (pagePane == null) {
System.err.println("Error: pagePane is null");
return;
}
try {
// Retrieve the current page index from the existing Pagination
int currentPageIndex = pagination.getCurrentPageIndex(); // Get the current page index
// Extract text from the current page
PDPage page = document.getPage(currentPageIndex); // Use the current page index
PDFTextExtractor extractor = new PDFTextExtractor();
extractor.setStartPage(currentPageIndex + 1); // Pages are 1-based in PDFTextExtractor
extractor.setEndPage(currentPageIndex + 1);
// Extract text from the specified page
extractor.processPage(page);
// Get word positions
List<PDFTextExtractor.WordPosition> wordPositions = extractor.getWordPositions();
// Search for matches
List<PDFTextExtractor.WordPosition> matches = SearchService.searchMatches(wordPositions, searchText);
// Highlight the matches on the specified pagePane
highlightMatches(pagePane, matches);
} catch (IOException e) {
e.printStackTrace();
}
}
private void highlightMatches(Pane pagePane, List<PDFTextExtractor.WordPosition> matches) {
pagePane.getChildren().clear(); // Clear existing highlights
for (PDFTextExtractor.WordPosition match : matches) {
Rectangle highlight = new Rectangle(match.getX(), match.getY(), match.getWidth(), match.getHeight());
highlight.setFill(Color.LIGHTBLUE);
highlight.setOpacity(0.5); // Semi-transparent
pagePane.getChildren().add(highlight);
}
// this is the pagination or this is should it based:
private void PdfxImage(AnchorPane anchorPane, Label label) {
dndPdf1.setOnDragOver(dragOverEvent -> {
Dragboard dragboard = dragOverEvent.getDragboard();
if (dragboard.hasFiles()) {
dragOverEvent.acceptTransferModes(TransferMode.COPY_OR_MOVE); // Allow copy or move
}
dragOverEvent.consume();
});
dndPdf1.setOnDragDropped(dragEvent -> {
Dragboard dragboard = dragEvent.getDragboard();
if (dragboard.hasFiles()) {
// Clear previous data
pageImageCache.clear();
RectAnnotations.clear();
dndPdf1.setCursor(Cursor.WAIT); // Set cursor to wait
droppedFilePath = dragboard.getFiles().get(0).toPath(); // Store the file path
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm", Locale.ENGLISH);
String formattedTime = currentDateTime.format(formatter);
ModifiedTime.setText("Modified: " + formattedTime);
new Thread(() -> {
try {
// Load the PDF document
document = PDDocument.load(droppedFilePath.toFile());
renderer = new PDFRenderer(document);
int pageCount = document.getNumberOfPages();
Platform.runLater(() -> {
try {
// Clear previous UI components
annotationList.clear();
dndPdf1.getChildren().clear();
dndPdf2.getChildren().clear();
rectAnnotation.setDisable(false);
twoPageView.setDisable(false);
reset.setDisable(false);
singlePageView.setDisable(false);
extractTextButton.setDisable(false);
save.setDisable(false);
ZoomLevel.setText("Zoom: Fit page");
// Create Pagination and navigation buttons
pagination = new Pagination(pageCount, 0); // Initialize pagination here
pagination.getStyleClass().add(Pagination.STYLE_CLASS_BULLET);
Button prevButton = new Button();
Button nextButton = new Button();
prevButton.getStyleClass().add("prevButton");
nextButton.getStyleClass().add("nextButton");
prevButton.setOnAction(event -> {
if (pagination != null) {
int currentPageIndex = pagination.getCurrentPageIndex();
if (currentPageIndex > 0) {
pagination.setCurrentPageIndex(currentPageIndex - 1);
}
}
});
nextButton.setOnAction(event -> {
if (pagination != null) {
int currentPageIndex = pagination.getCurrentPageIndex();
if (currentPageIndex < pageCount - 1) {
pagination.setCurrentPageIndex(currentPageIndex + 1);
}
}
});
HBox navButtons = new HBox(10, prevButton, pagination, nextButton);
navButtons.setAlignment(Pos.CENTER);
navButtons.setPadding(new Insets(10)); // Add some padding if needed
// Combine page number input and page info label
pageInfoLabel.setText("Total pages: " + pageCount);
Pageinformation.setText(" / " + pageCount);
HBox pageInfoBox = new HBox(5);
pageInfoBox.setAlignment(Pos.CENTER);
pageInfoBox.setPadding(new Insets(10));
// Page Factory
pagination.setPageFactory(pageIndex -> {
try {
return createPagePane(pageIndex, document, renderer, anchorPane);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
// Update page info and handle input
pageNumberInput.setOnAction(event -> {
if (pagination != null) {
String text = pageNumberInput.getText();
try {
int selectedPage = Integer.parseInt(text);
if (selectedPage >= 1 && selectedPage <= pageCount) {
pagination.setCurrentPageIndex(selectedPage - 1); // Adjusted for zero-based index
} else {
System.out.println("Page number out of range.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid page number format.");
}
}
});
extractTextButton.setOnAction(event -> {
if (pagination != null) {
int currentPageIndex = pagination.getCurrentPageIndex();
try {
String extractedText = extractTextFromPdf(document, currentPageIndex);
if (extractedText != null && !extractedText.isEmpty()) {
showExtractedTextPopup(extractedText, (Stage) anchorPane.getScene().getWindow());
} else {
System.out.println("No text extracted from the PDF.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
pagination.setOnScroll(this::handlePaginationScroll);
// Add Pagination, navigation buttons, and combined page info box to layout
dndPdf1.getChildren().addAll(navButtons, pageInfoBox);
lblPdfPath.setText("File name: " + droppedFilePath.getFileName().toString());
// Setup action handlers
twoPageView.setOnAction(event -> switchToTwoPageView(document, renderer, anchorPane));
singlePageView.setOnAction(event -> switchToSinglePageView(document, renderer, anchorPane));
dndPdf1.setCursor(Cursor.DEFAULT); // Set cursor back to default
} catch (Exception e) {
e.printStackTrace();
dndPdf1.setCursor(Cursor.DEFAULT); // Reset cursor on error
}
});
} catch (IOException e) {
e.printStackTrace();
Platform.runLater(() -> dndPdf1.setCursor(Cursor.DEFAULT)); // Reset cursor on error
}
}).start();
} else {
dndPdf1.setCursor(Cursor.DEFAULT); // Reset cursor if no files
}
dragEvent.setDropCompleted(dragboard.hasFiles());
dragEvent.consume();
});
rotate.setOnAction(event -> rotateImageView());
openMenuItem.setOnAction(event -> openMenuItem(anchorPane, label));
}
What am I expecting is that when I use the search function all that match word or character will will highlight in the buffered image and I already put a rectangle for representing the highlight.
This is my model:
package Model;
import java.util.ArrayList;
import java.util.List;
public class SearchService {
public static List<PDFTextExtractor.WordPosition> searchMatches(List<PDFTextExtractor.WordPosition> wordPositions, String searchText) {
List<PDFTextExtractor.WordPosition> matches = new ArrayList<>();
for (PDFTextExtractor.WordPosition wordPosition : wordPositions) {
if (wordPosition.getWord().contains(searchText)) {
matches.add(wordPosition);
}
}
return matches;
}
}