Java Program to Extract Content from a PDF
Java class< file using the Apache Tika< library is used. For document type detection and content extraction from various file formats, it uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing different file formats. All these parser libraries are encapsulated in a single interface called the Parser interface.
Java supports multiple in-built classes and packages to extract and access the content from a PDF document. The following classes are used in the extraction of the content :
BodyContentHandler is an in-built class that creates a handler for the text, which writes these XHTML body character events and stores them in an internal string buffer. It is inherited from the parent class ContentHandlerDecorator in Java. The specified text can be retrieved using the method ContentHandlerDecorator.toString() provided by the parent class.
PDFParser Java provides an in-built package that provides a class PDFParser, which parses the contents of PDF documents. It extracts the contents of a PDF Document stored within paragraphs, strings, and tables (without invoking tabular boundaries). It can be used to parse encrypted documents too if the password is specified as an argument.
ParseContext: This class is a component of the Java package org.apache.tika.parser, which is used to parse context and pass it on to the Tika parsers.
- Create a content handler.
- Create a PDF file at the local directory in the system.
- Now, create a FileInputStream having the same path as that of the above PDF file created.
- Create a content parser using a metadata type object for the PDF document.
- PDF document is now parsed using the PDF parser class.
- Print the content of the PDF document as created above to illustrate the extraction of content in the above PDF.
Implementation: The following Java program is used to illustrate the extraction of content from the PDF document.
Output: The following are the contents of the file at the local directory made is as follows: