开发者

What is the easiest way to extract data from a PDF?

I need to extract data from some PDF documents (using Java). I need to know what would be the easiest way to do it.

I tried iText. It's fairly 开发者_开发问答complicated for my needs. Besides I guess it is not available for free for commercial projects. So it is not an option. I also gave a try to PDFBox, and ran into various NoClassDefFoundError errors.

I googled and came across several other options such as PDF Clown, jPod, but I do not have time to experiment with all of these libraries. I am relying on community's experience with PDF reading thru Java.

Note that I do not need to create or manipulate PDF documents. I just need to exrtract textual data from PDF documents with moderate level layout complexity.

Please suggest the quickest and easiest way to extract text from PDF documents. Thanks.


I recommend trying Apache Tika. Apache Tika is basically a toolkit that extracts data from many types of documents, including PDFs.

The benefits of Tika (besides being free), is that is used to be a subproject of Apache Lucene, which is a very robust open-source search engine. Tika includes a built-in PDF parser that uses a SAX Content Handler to pass PDF data to your application. It can also extract data from encrypted PDFs and it allows you to create or subclass an existing parser to customize the behavior.

The code is simple. To extract the data from a PDF, all you need to do is create a Parser class that implements the Parser interface and define a parse() method:

public void parse(
   InputStream stream, ContentHandler handler,
   Metadata metadata, ParseContext context)
   throws IOException, SAXException, TikaException {

   metadata.set(Metadata.CONTENT_TYPE, HELLO_MIME_TYPE);
   metadata.set("Hello", "World");

   XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
   xhtml.startDocument();
   xhtml.endDocument();
}

Then, to run the parser, you could do something like this:

InputStream input = new FileInputStream(new File(resourceLocation));
ContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
PDFParser parser = new PDFParser();
parser.parse(input, textHandler, metadata);
input.close();
out.println("Title: " + metadata.get("title"));
out.println("Author: " + metadata.get("Author"));
out.println("content: " + textHandler.toString());


I am using JPedal and I'm really happy with the results. It isn't free but it's high quality and the output for image generation from pdfs or text extraction is really nice.

And as a paid library, the support is always there to answer.


I have used PDFBox to extract text for Lucene indexing without too many issues. Its error/warning logging is quite verbose if I remember right - what was the cause for those errors you received?


I understand this post is pretty old but I would recommend using itext from here: http://sourceforge.net/projects/itext/ If you are using maven you can pull the jars in from maven central: http://mvnrepository.com/artifact/com.itextpdf/itextpdf

I can't understand how using it can be difficult:

    PdfReader pdf = new PdfReader("path to your pdf file");
    PdfTextExtractor parser = new PdfTextExtractor();
    String output = parser.getTextFromPage(pdf, pageNumber);
    assert output.contains("whatever you want to validate on that page");


Import this Classes and add Jar Files 1.- pdfbox-app- 2.0.

   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.support.FindBy;
   import org.testng.Assert;
   import org.testng.annotations.Test;

   import java.io.File;
   import java.io.IOException;
   import java.text.ParseException;
   import java.util.List;

   import org.apache.log4j.Logger;
   import org.apache.log4j.PropertyConfigurator;
   import org.apache.pdfbox.pdmodel.PDDocument;
   import org.apache.pdfbox.text.PDFTextStripper;
   import org.openqa.selenium.By;
   import org.openqa.selenium.chrome.ChromeDriver;


   import com.coencorp.selenium.framework.BasePage;
   import com.coencorp.selenium.framework.ExcelReadWrite;
   import com.relevantcodes.extentreports.LogStatus;

Add this code inside the class.

   public void showList() throws InterruptedException, IOException {

   showInspectionsLink.click();
   waitForElement(hideInspectionsLink);
   printButton.click();
   Thread.sleep(10000);
   String downloadPath = "C:\\Users\\Updoer\\Downloads";
   File getLatestFile = getLatestFilefromDir(downloadPath);
   String fileName = getLatestFile.getName();
   Assert.assertTrue(fileName.equals("Inspections.pdf"), "Downloaded file name is not 
   matching with expected file name");
   Thread.sleep(10000);
   //testVerifyPDFInURL();
   PDDocument pd;
   pd= PDDocument.load(new File("C:\\Users\\Updoer\\Downloads\\Inspections.pdf"));
   System.out.println("Total Pages:"+ pd.getNumberOfPages());
   PDFTextStripper pdf=new PDFTextStripper();
   System.out.println(pdf.getText(pd));

Add this Method in same class.

   public void testVerifyPDFInURL() {
   WebDriver driver = new ChromeDriver();
   driver.get("C:\\Users\\Updoer\\Downloads\\Inspections.pdf");
   driver.findElement(By.linkText("Adeeb Khan")).click();
   String getURL = driver.getCurrentUrl();
   Assert.assertTrue(getURL.contains(".pdf"));
   }

   private File getLatestFilefromDir(String dirPath){
   File dir = new File(dirPath);
   File[] files = dir.listFiles();
   if (files == null || files.length == 0) {
        return null;
   }

   File lastModifiedFile = files[0];
   for (int i = 1; i < files.length; i++) {
   if (lastModifiedFile.lastModified() < files[i].lastModified()) {
   lastModifiedFile = files[i];
   }
   }
   return lastModifiedFile;
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜