java使用pdfbox操作pdf文件示例

还有一个用于创建PDF文件的项目----iText。

PDFBox下面有两个子项目:FontBox一个处理PDF字体的java类库;JempBox一个处理XMP元数据的java类库。

一个简单示例:

要引入pdfBox-app-1.6.0.jar这个包。


package pdf;

import java.io.File;
import java.net.MalformedURLException;

import org.apache.pdfBox.pdmodel.PDDocument;
import org.apache.pdfBox.util.PDFTextStripper;

public class StripPDFContent {

    public static String getText(File file)throws Exception{
        boolean sort=false;
        int startPage=1;
        int endPage=10;
        PDDocument document=null;
        try{
            try{
                document=PDDocument.load(file);
            }catch(MalformedURLException e){

            }
            PDFTextStripper stripper=new PDFTextStripper();
            stripper.setSortByPosition(sort);
            stripper.setStartPage(startPage);
            stripper.setEndPage(endPage);
            return stripper.getText(document);
        }catch(Exception e){
            e.printstacktrace();
            return "";
        }finally{
            if(document!=null){
                document.close();
            }
        }
    }

    public static void main(String[] args){
        File file=new File("/home/orisun/123.pdf");
        try{
            String cont=getText(file);
            System.out.println(cont);
        }catch(Exception e){
            System.out.println("Strip Failed.");
            e.printstacktrace();
        }
    }
}

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...