Java PDF查找和高亮文本

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/Eiceblue/article/details/84646274

这篇文章介绍如何在Java应用程序中查找PDF文档中的指定文本并高亮显示。

使用组件:

Spire.PDF for Java

下载Spire.PDF for JAVA包并解压缩,然后从lib文件夹下导入Spire.Pdf.jar包到Java应用程序中。

原PDF文档如下:

import com.spire.pdf.*;
import java.awt.*;
import com.spire.pdf.general.find.PdfTextFind;

public class findAndHighlightText {
    public static void main(String[] args) throws Exception {
        //加载PDF文档
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("乡愁.pdf");
        PdfTextFind[] result = null;
        //遍历文档页面
        for (PdfPageBase page : (Iterable) pdf.getPages()) {
            //查找文档中所有的"乡愁"字符串
            result = page.findText("乡愁").getFinds();
            for (PdfTextFind find : result) {
                //高亮显示查找结果
                find.applyHighLight(Color.yellow);
            }
        }
        //保存文档
        pdf.saveToFile("HighlightText.pdf");
        pdf.close();
    }
}

高亮文本效果:

猜你喜欢

转载自blog.csdn.net/Eiceblue/article/details/84646274