PDFBox解析PDF文档

1.下载PDFBox第三方jar包(本例中只需要下载pdfbox-2.0.2.jar以及fontbox-2.0.2.jar,示例程序包含在pdfbox-2.0.2-src.zip文件中,本例使用的jdk为1.8版本),以及commons-logging-1.2.jar包。

PDFBox下载地址:https://pdfbox.apache.org/download.cgi

commons-logging-1.2.jar包下载地址:http://commons.apache.org/proper/commons-logging/download_logging.cgi

2.在eclipse里面建立相应的工程,在工程文件下建立lib目录,复制下载的jar文件到lib目录下,依次选中jar文件右键选择buildpath->add to build path

3.编辑源代码如下:

package org.apache.pdfbox.examples.util;

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

import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;

/**
 * This is an example on how to extract text from a specific area on the PDF document.
 *
 * @author Ben Litchfield
 */
public final class ExtractTextByArea
{
    private ExtractTextByArea()
    {
        //utility class and should not be constructed.
    }


    /**
     * This will print the documents text in a certain area.
     *
     * @param args The command line arguments.
     *
     * @throws IOException If there is an error parsing the document.
     */
    public static void main( String[] args ) throws IOException
    {
        if( args.length != 1 )
        {
            usage();
        }
        else
        {
            PDDocument document = null;
            try
            {
                document = PDDocument.load( new File(args[0]) );
                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition( true );
                Rectangle rect = new Rectangle( 0, 0, 700, 700 );
                stripper.addRegion( "class1", rect );
                PDPage firstPage = document.getPage(0);
                stripper.extractRegions( firstPage );
                System.out.println( "Text in the area:" + rect );
                System.out.println( stripper.getTextForRegion( "class1" ) );
            }
            finally
            {
                if( document != null )
                {
                    document.close();
                }
            }
        }
    }

    /**
     * This will print the usage for this document.
     */
    private static void usage()
    {
        System.err.println( "Usage: java " + ExtractTextByArea.class.getName() + " " );
    }

}


4.右键run as->run configurations->Arguments.在Program Arguments里添加待解析的PDF文件的路径

5.Apply->run

注解:commons-logging-1.2.jar包是必须得,另外如果程序抛出如下异常,建议重新配置环境变量并更换eclipse的工作空间

PDFBox解析PDF文档_第1张图片

你可能感兴趣的:(Java)