使用PDFBox

时间:2017-12-08 13:08:21

标签: java pdf pdfbox

我有一个从word创建的PDF,其中包含有关其内容树和标签树中的结构的大量信息,可以在Adobe Acrobat中看到(参见下面的图片) View of the Content Tree or Table View of the Tags Tree or Table

在你建议之前,不,我没有访问原始word文档所以我被迫处理PDF解析。

我已经设法在Java PDFBox上取得了一些进展,它允许我在每个页面上找到注释并提取信息(注释是内容树的一部分)。 挖掘PDPage原始文档PDFBox PDPage documentation我发现了一些看似有希望的方法,如getContents()和getCOSDictionary()。现在从我的理解处理COSObjects是痛苦的,而不是健壮的getContents产生和难以处理的字节的InputStream。

有人设法以干净简单的方式从提到的表格中获取信息吗?如果使用了不同的包/语言,这也有效:)

package acs.pdf2isosts.TestPDFBox;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;

import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;

public class ReadPdf  {
    public static void main( String[] args ) throws IOException{

        PDDocument document = PDDocument.load(new File(
                "/sample.pdf")); 
        document.getClass();

        if (!document.isEncrypted()) {

            Iterator<PDPage> it = document.getPages().iterator();
            while (it.hasNext()) {
                PDPage pg = it.next();
                //System.out.println(pg.toString());
                List<PDAnnotation> annotations = pg.getAnnotations();
                for (PDAnnotation annotation : annotations)
                {
                    if (annotation instanceof PDAnnotationLink)
                    {
                        PDAnnotationLink annotationLink = (PDAnnotationLink)annotation;
                        System.out.println(annotationLink.getAction().getCOSObject());
                    }
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pg.getContents()));
                String line;
                while( (line = bufferedReader.readLine()) != null )
                { 
                    System.out.println(line.getClass());
                    System.out.printf("%s\n", line);
                }


            }

        }

        document.close();


    }
        }
}

0 个答案:

没有答案