Highlighting text can help users quickly jump to the
location of the text in a document. In this blog, I will introduce how to
search specific text in a PDF document and highlight the searched text in Java application.
The below example uses Free Spire.PDF for Java library.
The sample PDF document looks like below:
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.general.find.PdfTextFind;
import java.awt.*;
public class HighlightText {
public static void main(String[] args) throws Exception
{
//load the PDF file
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("Additional.pdf");
PdfTextFind[] result;
//loop through the pages in the PDF file
for(PdfPageBase page:(Iterable<PdfPageBase>) pdf.getPages())
{
//search the text "The Man Who Laughs" on every PDF page
result = page.findText("The Man Who Laughs").getFinds();
//highlight the searched text with yellow color
for (PdfTextFind find:result)
{
find.applyHighLight(Color.yellow);
}
}
//save the resultant file
pdf.saveToFile("HighlightText.pdf");
}
}
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.general.find.PdfTextFind;
import java.awt.*;
public class HighlightText {
public static void main(String[] args) throws Exception
{
//load the PDF file
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("Additional.pdf");
PdfTextFind[] result;
//loop through the pages in the PDF file
for(PdfPageBase page:(Iterable<PdfPageBase>) pdf.getPages())
{
//search the text "The Man Who Laughs" on every PDF page
result = page.findText("The Man Who Laughs").getFinds();
//highlight the searched text with yellow color
for (PdfTextFind find:result)
{
find.applyHighLight(Color.yellow);
}
}
//save the resultant file
pdf.saveToFile("HighlightText.pdf");
}
}
Screenshot after highlighting:
Comments
Post a Comment