Click here to close now.

Welcome!

Java Authors: Roger Strukhoff, Harry Trott, Trevor Parsons, Elizabeth White, Ian Khan

Related Topics: Java

Java: Article

Making PDFs Portable: Integrating PDF and Java Technology

Making PDFs Portable: Integrating PDF and Java Technology

Since Adobe released the first public PDF Reference in 1993, a number of PDF utilities and libraries, supporting all kinds of languages and platforms, have been made available to users and developers alike. However, support for Adobe's technology has lagged in Java application development. And this is curious because PDF documents tend to be a popular way of storing and interchanging information when dealing with enterprise information systems - an application domain that Java technology is particularly well suited to. Yet it seems that, until recently, mature, capable PDF support wasn't readily available to Java applications developers.

PDFBox (an Open Source project released under the BSD license) is a pure Java library that lets developers read and create PDF documents. It has features such as:

  • Extracting text, including Unicode characters
  • Easy integration with text search engines like Jakarta Lucene
  • Encryption/Decryption of PDF documents
  • Importing/Exporting of form data in FDF and XFDF formats
  • Appending to existing PDF documents
  • Splitting a single PDF into multiple documents
  • Overlaying one PDF document on top of another
PDFBox API
PDFBox has been designed to represent PDF documents using familiar object-oriented paradigms. The data contained in a PDF document is a collection of basic object types: arrays, booleans, dictionaries, numbers, strings and binary streams. PDFBox captures these basic object types in the org.pdfbox.cos package (the COS Model). While it's possible to create any desired interactions with a PDF document using only these objects, it requires an intimate knowledge of the internals of PDF documents and the techniques used to represent higher-level concepts. For example, objects such as pages and fonts are represented as dictionaries with specialized attributes; deciphering all these various attributes and their types requires tedious consultation of the PDF Reference.

For this reason, the org.pdfbox.pdmodel package (the PD Model) sits on top the COS Model and provides a high-level API that accesses PDF document objects in a more familiar manner (see Figure 1). Objects such as PDPage and PDFont can be found in this package, which encapsulates their lower-level COS model counterparts.

A word of caution to developers: the PD Model offers many nice features but is still a work in progress. In some instances, use of the COS Model may be required to access a particular piece of PDF functionality. Consequently, all PD Model objects can retrieve the corresponding COS Model object that they represent, so it's always possible to start with the PD Model and drop down to the COS Model when the required piece of functionality is found to be missing.

Now that the general capabilities of PDFBox have been discussed a few examples of its use are appropriate. We will start by reading an existing PDF document:


PDDocument document =
PDDocument.load( "./test.pdf" );

This operation will cause the PDF file to be parsed and an in-memory representation of the document will be created. To facilitate the efficient handling of large documents, PDFBox only stores the document structure in memory; objects such as images, embedded fonts and page content are cached in a temporary file.

Note: When finished using a PDDocument object, care should be taken to invoke the close() method on the document object to release resources used during its creation.

Text Extraction and Lucene Integration
In an information retrieval age when applications are expected to have searching and indexing capabilities regardless of the medium, the ability to organize and catalog information into a searchable format is critical. This is simple for text and HTML documents, but PDF documents have more structure and meta-information that makes it difficult to extract the underlying text. The PDF language is similar to Postscript in that objects are drawn as vectors on the page at certain positions. For example:


/Helv 12 Tf
0 13.0847 Td
(Hello World) Tj

This set of instructions changes the font to Helvetica size 12, moves the caret to the next line and renders the string "Hello World." These command streams are usually compressed and the order in which the glyphs are displayed on the screen is not necessarily the order in which the characters appear in the file, so it isn't always possible to simply extract text strings directly from the raw PDF document. However, PDFBox has a sophisticated text-extraction algorithm that deals with this and other complexities, letting a developer get the text of the document as if reading off its rendered form.

Lucene, which is part of the Apache Jakarta project, is a popular Open Source search engine library. Lucene lets developers create an index and do complex searches on a large volume of textual content based on that index. Since Lucene has adopted text as the common denominator for content, it's the developer's responsibility to convert the data contained in other desired file formats to text to use Lucene. For example, file formats such as Microsoft Word and StarOffice documents have to be converted to text before they can be added to a Lucene index.

PDF files are no exception, but PDFBox makes it easy to include a PDF document in a Lucene index by supplying a special object that does the integration. A basic PDF document can be converted to a Lucene document with a single statement:


Document doc = LucenePDFDocument.getDocument( file );

This operation parses the PDF document, extracts the text and creates a Lucene document object that can then be added to the index. As mentioned above, PDF documents also contain metadata such as author information and keywords that are important to track when indexing PDF documents. Table 1 shows the fields that PDFBox will populate while creating the Lucene document.

This integration makes it easy for developers to support simple searching and indexing of PDF documents with Lucene. Of course, some applications require more sophisticated text-extraction methods. In that case, the PDFTextStripper class can be used directly, or extended to handle these complex requirements.

By extending this class and overriding the showCharacter() method, many aspects of text extraction can be controlled. For instance, an implementation of this method can use the x, y positioning information to limit the inclusion of certain blocks of text in the extraction. One use might exclude all of the text above a certain y-coordinate value effectively excluding an unwanted document header.

Another example: Oftentimes a group of PDF documents may have been created from forms and the source data are no longer available. In other words, the documents all have some interesting text at similar locations on the page, but the form data used to fill the document out are no longer available. For example, a collection of cover letters that have the name and address at the same location in the document. In this case, an extension of the PDFTextStripper class can be used as a sort of screen-scraping device to extract the desired fields.

More Stories By Ben Litchfield

Ben Litchfield is a business systems consultant within the development & integration practice at LPA Systems. He has been the lead developer of PDFBox for the past two years. Ben holds a BS in Software Engineering from the Rochester Institute of Technology. He has been providing solutions for enterprise applications for the past five years.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Lucious 03/23/05 02:27:55 PM EST

I can't believe I found this!! I was searching for tools to update pdf files in my java programs. All I could find was commercial tools that would charge for single/multiple CPU and development liscenses and then charge MORE for deployment!! I actually gave up and downloaded the pdf specs (over 1200 pages) to develop tools of my own. I can't wait to start using these tools!

Maulik 03/23/05 08:09:43 AM EST

Great easy-to-follow article for someone who knows next to nothing about integrating Java and PDF. Good job.

Richard Bouchard 03/12/05 09:15:57 PM EST

Excellent article and has great utility.

@ThingsExpo Stories
The Workspace-as-a-Service (WaaS) market will grow to $6.4B by 2018. In his session at 16th Cloud Expo, Seth Bostock, CEO of IndependenceIT, will begin by walking the audience through the evolution of Workspace as-a-Service, where it is now vs. where it going. To look beyond the desktop we must understand exactly what WaaS is, who the users are, and where it is going in the future. IT departments, ISVs and service providers must look to workflow and automation capabilities to adapt to growing demand and the rapidly changing workspace model.
Cloud data governance was previously an avoided function when cloud deployments were relatively small. With the rapid adoption in public cloud – both rogue and sanctioned, it’s not uncommon to find regulated data dumped into public cloud and unprotected. This is why enterprises and cloud providers alike need to embrace a cloud data governance function and map policies, processes and technology controls accordingly. In her session at 15th Cloud Expo, Evelyn de Souza, Data Privacy and Compliance Strategy Leader at Cisco Systems, will focus on how to set up a cloud data governance program and s...
As organizations shift toward IT-as-a-service models, the need for managing and protecting data residing across physical, virtual, and now cloud environments grows with it. CommVault can ensure protection &E-Discovery of your data – whether in a private cloud, a Service Provider delivered public cloud, or a hybrid cloud environment – across the heterogeneous enterprise. In his session at 16th Cloud Expo, Randy De Meno, Chief Technologist - Windows Products and Microsoft Partnerships, will discuss how to cut costs, scale easily, and unleash insight with CommVault Simpana software, the only si...
Hadoop as a Service (as offered by handful of niche vendors now) is a cloud computing solution that makes medium and large-scale data processing accessible, easy, fast and inexpensive. In his session at Big Data Expo, Kumar Ramamurthy, Vice President and Chief Technologist, EIM & Big Data, at Virtusa, will discuss how this is achieved by eliminating the operational challenges of running Hadoop, so one can focus on business growth. The fragmented Hadoop distribution world and various PaaS solutions that provide a Hadoop flavor either make choices for customers very flexible in the name of opti...
Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 16th Cloud Expo at the Javits Center in New York June 9-11 will find fresh new content in a new track called PaaS | Containers & Microservices Containers are not being considered for the first time by the cloud community, but a current era of re-consideration has pushed them to the top of the cloud agenda. With the launch of Docker's initial release in March of 2013, interest was revved up several notches. Then late last...
Roberto Medrano, Executive Vice President at SOA Software, had reached 30,000 page views on his home page - http://RobertoMedrano.SYS-CON.com/ - on the SYS-CON family of online magazines, which includes Cloud Computing Journal, Internet of Things Journal, Big Data Journal, and SOA World Magazine. He is a recognized executive in the information technology fields of SOA, internet security, governance, and compliance. He has extensive experience with both start-ups and large companies, having been involved at the beginning of four IT industries: EDA, Open Systems, Computer Security and now SOA.
HP and Aruba Networks on Monday announced a definitive agreement for HP to acquire Aruba, a provider of next-generation network access solutions for the mobile enterprise, for $24.67 per share in cash. The equity value of the transaction is approximately $3.0 billion, and net of cash and debt approximately $2.7 billion. Both companies' boards of directors have approved the deal. "Enterprises are facing a mobile-first world and are looking for solutions that help them transition legacy investments to the new style of IT," said Meg Whitman, Chairman, President and Chief Executive Officer of HP...
The industrial software market has treated data with the mentality of “collect everything now, worry about how to use it later.” We now find ourselves buried in data, with the pervasive connectivity of the (Industrial) Internet of Things only piling on more numbers. There’s too much data and not enough information. In his session at @ThingsExpo, Bob Gates, Global Marketing Director, GE’s Intelligent Platforms business, to discuss how realizing the power of IoT, software developers are now focused on understanding how industrial data can create intelligence for industrial operations. Imagine ...
Operational Hadoop and the Lambda Architecture for Streaming Data Apache Hadoop is emerging as a distributed platform for handling large and fast incoming streams of data. Predictive maintenance, supply chain optimization, and Internet-of-Things analysis are examples where Hadoop provides the scalable storage, processing, and analytics platform to gain meaningful insights from granular data that is typically only valuable from a large-scale, aggregate view. One architecture useful for capturing and analyzing streaming data is the Lambda Architecture, representing a model of how to analyze rea...
SYS-CON Events announced today that Vitria Technology, Inc. will exhibit at SYS-CON’s @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Vitria will showcase the company’s new IoT Analytics Platform through live demonstrations at booth #330. Vitria’s IoT Analytics Platform, fully integrated and powered by an operational intelligence engine, enables customers to rapidly build and operationalize advanced analytics to deliver timely business outcomes for use cases across the industrial, enterprise, and consumer segments.
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
SYS-CON Events announced today that Open Data Centers (ODC), a carrier-neutral colocation provider, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. Open Data Centers is a carrier-neutral data center operator in New Jersey and New York City offering alternative connectivity options for carriers, service providers and enterprise customers.
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
PubNub on Monday has announced that it is partnering with IBM to bring its sophisticated real-time data streaming and messaging capabilities to Bluemix, IBM’s cloud development platform. “Today’s app and connected devices require an always-on connection, but building a secure, scalable solution from the ground up is time consuming, resource intensive, and error-prone,” said Todd Greene, CEO of PubNub. “PubNub enables web, mobile and IoT developers building apps on IBM Bluemix to quickly add scalable realtime functionality with minimal effort and cost.”
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
In the consumer IoT, everything is new, and the IT world of bits and bytes holds sway. But industrial and commercial realms encompass operational technology (OT) that has been around for 25 or 50 years. This grittier, pre-IP, more hands-on world has much to gain from Industrial IoT (IIoT) applications and principles. But adding sensors and wireless connectivity won’t work in environments that demand unwavering reliability and performance. In his session at @ThingsExpo, Ron Sege, CEO of Echelon, will discuss how as enterprise IT embraces other IoT-related technology trends, enterprises with i...
When it comes to the Internet of Things, hooking up will get you only so far. If you want customers to commit, you need to go beyond simply connecting products. You need to use the devices themselves to transform how you engage with every customer and how you manage the entire product lifecycle. In his session at @ThingsExpo, Sean Lorenz, Technical Product Manager for Xively at LogMeIn, will show how “product relationship management” can help you leverage your connected devices and the data they generate about customer usage and product performance to deliver extremely compelling and reliabl...
The Internet of Things (IoT) is causing data centers to become radically decentralized and atomized within a new paradigm known as “fog computing.” To support IoT applications, such as connected cars and smart grids, data centers' core functions will be decentralized out to the network's edges and endpoints (aka “fogs”). As this trend takes hold, Big Data analytics platforms will focus on high-volume log analysis (aka “logs”) and rely heavily on cognitive-computing algorithms (aka “cogs”) to make sense of it all.
With several hundred implementations of IoT-enabled solutions in the past 12 months alone, this session will focus on experience over the art of the possible. Many can only imagine the most advanced telematics platform ever deployed, supporting millions of customers, producing tens of thousands events or GBs per trip, and hundreds of TBs per month. With the ability to support a billion sensor events per second, over 30PB of warm data for analytics, and hundreds of PBs for an data analytics archive, in his session at @ThingsExpo, Jim Kaskade, Vice President and General Manager, Big Data & Ana...
One of the biggest impacts of the Internet of Things is and will continue to be on data; specifically data volume, management and usage. Companies are scrambling to adapt to this new and unpredictable data reality with legacy infrastructure that cannot handle the speed and volume of data. In his session at @ThingsExpo, Don DeLoach, CEO and president of Infobright, will discuss how companies need to rethink their data infrastructure to participate in the IoT, including: Data storage: Understanding the kinds of data: structured, unstructured, big/small? Analytics: What kinds and how responsiv...