我使用的是pdfbox-app-2.0.0-RC3,但在PDF解析器中使用RndomAccessFile时仍然出现错误



-您可以通过以下链接查看示例:http://radixcode.com/pdfbox-example-code-how-to-extract-text-from-pdf-file-with-java/

import java.io.IOException;
public class JavaPDFTest {
    public static void main(String[] args) throws IOException {
       PDFManager pdfManager = new PDFManager();
       pdfManger.setFilePath("E:test.pdf");
       System.out.println(pdfManager.ToText());       
    }    
}

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class PDFManager {
   private PDFParser parser;
   private PDFTextStripper pdfStripper;
   private PDDocument pdDoc ;
   private COSDocument cosDoc ;
   private String Text ;
   private String filePath;
   private File file;
    public PDFManager() {
    }
   public String ToText() throws IOException
   {
       this.pdfStripper = null;
       this.pdDoc = null;
       this.cosDoc = null;
       file = new File(filePath);
       parser = new PDFParser(new RandomAccessFile(file,"r")); // update for PDFBox V 2.0
       parser.parse();
       cosDoc = parser.getDocument();
       pdfStripper = new PDFTextStripper();
       pdDoc = new PDDocument(cosDoc);
       pdDoc.getNumberOfPages();
       pdfStripper.setStartPage(1);
       pdfStripper.setEndPage(10);
       // reading text from page 1 to 10
       // if you want to get text from full pdf file use this code
       // pdfStripper.setEndPage(pdDoc.getNumberOfPages());
       Text = pdfStripper.getText(pdDoc);
       return Text;
   }
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}

错误

线程"main"java.lang.ClassCastException中的异常:java.ioRandomAccessFile无法强制转换为org.apache.pdfbox.io.RandomAccessRead
在aechaec。PDFManager.ToText(PDFManager.java:43)
在aechaec。AechAEC.main(AechAEC.java:25)
Java结果:1

它是由安全特权引起的吗?因为我在mac上使用Netbeans?

有很多过时的例子,它们可能起作用,也可能不起作用。请替换此代码

file = new File(filePath);
parser = new PDFParser(new RandomAccessFile(file,"r"));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);

这个代码:

pdDoc = PDDocument.load(new File(filePath));
pdfStripper = new PDFTextStripper();

并更新到2.0的发布版本。

最新更新