使用PDFbox从区域中提取文本

时间:2016-10-18 07:09:14

标签: pdf pdfbox

是否可以仅使用二进制文件从PDFbox区域中提取文本,而不必创建自己的代码?

1 个答案:

答案 0 :(得分:3)

将这个简单程序编译并装入jar

import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class ExtractText {

    // Usage: xxx.jar filepath page x y width height
    public static void main(String[] args) throws IOException {

        if (args.length != 6) {
            System.out.println("Help info");
            return;
        }



        // Parameters
        String filepath = args[0];

        int page = Integer.parseInt(args[1]);
        int x = Integer.parseInt(args[2]);
        int y = Integer.parseInt(args[3]);
        int width = Integer.parseInt(args[4]);
        int height = Integer.parseInt(args[5]);

        PDDocument document = PDDocument.load(new File(filepath));

        PDFTextStripperByArea textStripper = new PDFTextStripperByArea();
        Rectangle2D rect = new java.awt.geom.Rectangle2D.Float(x, y, width, height);
        textStripper.addRegion("region", rect);


        PDPage docPage = document.getPage(page);

        textStripper.extractRegions(docPage);

        String textForRegion = textStripper.getTextForRegion("region");

        System.out.println(textForRegion);
    }
}

从命令行运行它,例如:

xxx.jar  filepathToPdf pageToExtract  x   y   width height

添加参数和一些使用信息的验证码。

修改

还添加PDFbox库

java -cp "..." -jar xxx.jar  filepathToPdf  pageToExtract  x  y  width   height