Click here to close now.


Java IoT Authors: Liz McMillan, Elizabeth White, Pat Romanski, Betty Zakheim, Deep Bhattacharjee

Related Topics: Java IoT

Java IoT: 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 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
Microservices are a very exciting architectural approach that many organizations are looking to as a way to accelerate innovation. Microservices promise to allow teams to move away from monolithic "ball of mud" systems, but the reality is that, in the vast majority of organizations, different projects and technologies will continue to be developed at different speeds. How to handle the dependencies between these disparate systems with different iteration cycles? Consider the "canoncial problem" in this scenario: microservice A (releases daily) depends on a couple of additions to backend B (re...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound effect on the world, and what should we expect to see over the next couple of years.
Container technology is shaping the future of DevOps and it’s also changing the way organizations think about application development. With the rise of mobile applications in the enterprise, businesses are abandoning year-long development cycles and embracing technologies that enable rapid development and continuous deployment of apps. In his session at DevOps Summit, Kurt Collins, Developer Evangelist at, examined how Docker has evolved into a highly effective tool for application delivery by allowing increasingly popular Mobile Backend-as-a-Service (mBaaS) platforms to quickly crea...
Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Day 2 Keynote at 17th Cloud Expo, Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, wil...
PubNub has announced the release of BLOCKS, a set of customizable microservices that give developers a simple way to add code and deploy features for realtime apps.PubNub BLOCKS executes business logic directly on the data streaming through PubNub’s network without splitting it off to an intermediary server controlled by the customer. This revolutionary approach streamlines app development, reduces endpoint-to-endpoint latency, and allows apps to better leverage the enormous scalability of PubNub’s Data Stream Network.
Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Ben Perlmutter, a Sales Engineer with IBM Cloudant, demonstrated techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user experience, both offline and online. The focus of this talk was on IBM Cloudant, Apache CouchDB, and ...
I recently attended and was a speaker at the 4th International Internet of @ThingsExpo at the Santa Clara Convention Center. I also had the opportunity to attend this event last year and I wrote a blog from that show talking about how the “Enterprise Impact of IoT” was a key theme of last year’s show. I was curious to see if the same theme would still resonate 365 days later and what, if any, changes I would see in the content presented.
Cloud computing delivers on-demand resources that provide businesses with flexibility and cost-savings. The challenge in moving workloads to the cloud has been the cost and complexity of ensuring the initial and ongoing security and regulatory (PCI, HIPAA, FFIEC) compliance across private and public clouds. Manual security compliance is slow, prone to human error, and represents over 50% of the cost of managing cloud applications. Determining how to automate cloud security compliance is critical to maintaining positive ROI. Raxak Protect is an automated security compliance SaaS platform and ma...
The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
Just over a week ago I received a long and loud sustained applause for a presentation I delivered at this year’s Cloud Expo in Santa Clara. I was extremely pleased with the turnout and had some very good conversations with many of the attendees. Over the next few days I had many more meaningful conversations and was not only happy with the results but also learned a few new things. Here is everything I learned in those three days distilled into three short points.
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York and Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound cha...
DevOps is about increasing efficiency, but nothing is more inefficient than building the same application twice. However, this is a routine occurrence with enterprise applications that need both a rich desktop web interface and strong mobile support. With recent technological advances from Isomorphic Software and others, rich desktop and tuned mobile experiences can now be created with a single codebase – without compromising functionality, performance or usability. In his session at DevOps Summit, Charles Kendrick, CTO and Chief Architect at Isomorphic Software, demonstrated examples of com...
As organizations realize the scope of the Internet of Things, gaining key insights from Big Data, through the use of advanced analytics, becomes crucial. However, IoT also creates the need for petabyte scale storage of data from millions of devices. A new type of Storage is required which seamlessly integrates robust data analytics with massive scale. These storage systems will act as “smart systems” provide in-place analytics that speed discovery and enable businesses to quickly derive meaningful and actionable insights. In his session at @ThingsExpo, Paul Turner, Chief Marketing Officer at...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
In his General Session at 17th Cloud Expo, Bruce Swann, Senior Product Marketing Manager for Adobe Campaign, explored the key ingredients of cross-channel marketing in a digital world. Learn how the Adobe Marketing Cloud can help marketers embrace opportunities for personalized, relevant and real-time customer engagement across offline (direct mail, point of sale, call center) and digital (email, website, SMS, mobile apps, social networks, connected objects).
We all know that data growth is exploding and storage budgets are shrinking. Instead of showing you charts on about how much data there is, in his General Session at 17th Cloud Expo, Scott Cleland, Senior Director of Product Marketing at HGST, showed how to capture all of your data in one place. After you have your data under control, you can then analyze it in one place, saving time and resources.
The Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, exploreed the current state of IoT connectivity and review key trends and technology requirements that will drive the Internet of Things from hype to reality.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessions, I wanted to share some of my observations on emerging trends. As cyber security serves as a fou...
With all the incredible momentum behind the Internet of Things (IoT) industry, it is easy to forget that not a single CEO wakes up and wonders if “my IoT is broken.” What they wonder is if they are making the right decisions to do all they can to increase revenue, decrease costs, and improve customer experience – effectively the same challenges they have always had in growing their business. The exciting thing about the IoT industry is now these decisions can be better, faster, and smarter. Now all corporate assets – people, objects, and spaces – can share information about themselves and thei...
Continuous processes around the development and deployment of applications are both impacted by -- and a benefit to -- the Internet of Things trend. To help better understand the relationship between DevOps and a plethora of new end-devices and data please welcome Gary Gruver, consultant, author and a former IT executive who has led many large-scale IT transformation projects, and John Jeremiah, Technology Evangelist at Hewlett Packard Enterprise (HPE), on Twitter at @j_jeremiah. The discussion is moderated by me, Dana Gardner, Principal Analyst at Interarbor Solutions.