/* * Created on Sept 12, 2017 * */ package jPDFTextSamples; import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.util.Vector; import com.qoppa.pdf.TextPosition; import com.qoppa.pdf.annotations.TextMarkup; import com.qoppa.pdfProcess.PDFDocument; import com.qoppa.pdfProcess.PDFPage; public class SearchAndHighlightText { public static void main(String[] args) { try { // Open the document PDFDocument inDoc = new PDFDocument("C:\\temp\\test_markup.pdf", null); // Loop through the pages, searching for text for (int pageIx = 0; pageIx < inDoc.getPageCount(); ++pageIx) { // Search for the text in a page PDFPage page = inDoc.getPage(pageIx); Vector searchResults = page.findText("JavaOne", false, false); if (searchResults.size() > 0) { AffineTransform viewToPDF = getViewToPDFXForm(page); for (int count = 0; count < searchResults.size(); ++count) { // Get the position of the text TextPosition textPos = searchResults.get(count); Vector quadList = textPos.getQuadrilaterals(); for (int quadCount = 0; quadCount < quadList.size(); ++quadCount) { Point2D[] quad = quadList.get(quadCount); viewToPDF.transform(quad, 0, quad, 0, quad.length); } // Create markup annotation and add it to the page TextMarkup markup = inDoc.getAnnotationFactory().createTextMarkup("Test Markup", quadList, "Highlight"); markup.setColor(Color.yellow); page.addAnnotation(markup); } } } inDoc.saveDocument("C:\\temp\\test_markup_output.pdf"); } catch (Throwable t) { t.printStackTrace(); } } private static AffineTransform getViewToPDFXForm(PDFPage page) { double width = page.getDisplayWidth(); double height = page.getDisplayHeight(); if (page.getPageRotation() % 180 != 0) { width = page.getDisplayHeight(); height = page.getDisplayWidth(); } // Handle the crop box location AffineTransform xForm = AffineTransform.getTranslateInstance(page.getDisplayX(), page.getDisplayY()); // Handle the page rotation AffineTransform rotXForm = AffineTransform.getRotateInstance(Math.toRadians(-page.getPageRotation())); Point2D.Double widthHeight = new Point2D.Double(width, height); rotXForm.transform(widthHeight, widthHeight); if (widthHeight.getX() < 0) { rotXForm.translate(0, -height); } if (widthHeight.getY() < 0) { rotXForm.translate(-width, 0); } xForm.concatenate(rotXForm); return xForm; } }