DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API in Java
  • How To Convert Common Documents to PNG Image Arrays in Java

Trending

  • Next-Gen IoT Performance Depends on Advanced Power Management ICs
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Introduction to Retrieval Augmented Generation (RAG)
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  1. DZone
  2. Coding
  3. Java
  4. PDFBox: Extract Content From a PDF Using Java

PDFBox: Extract Content From a PDF Using Java

Want to learn how you can extract content from a PDF?

By 
Gowthamraj Palani user avatar
Gowthamraj Palani
·
Updated Oct. 01, 19 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
89.1K Views

Join the DZone community and get the full member experience.

Join For Free

How easy would our lives be if there was a way to automate PDF content validation? Ever heard of a Java tool that makes our work easier by extracting the content of a PDF? If you are looking for such a tool, then theApache PDFBox is what you have been searching for.

What Is PDFBox?

The Apache PDFBox library is an open-source Java tool for working with PDF documents. It allows us to create new PDF documents, update existing documents like adding styles, hyperlinks, etc., and extract content from documents. 

Let's get into the details on how to do that!

Read Content From a PDF

Half of the problem is solved when you extract the text from the PDF. The following code does that for you. 

Class PDFTextStripper takes a PDF document and strips out all of the text in a document. This ignores all formatting in the document.

tStripper = new PDFTextStripper();
tStripper.setStartPage(1);
tStripper.setEndPage(3);

PDDocument document = PDDocument.load(new File("name.pdf"));
document.getClass();
            if (!document.isEncrypted()) {
                pdfFileInText = tStripper.getText(document);
                lines = pdfFileInText.split("\\r\\n\\r\\n");
                for (String line : lines) {
                    System.out.println(line);
                    content += line;
                }
            }
System.out.println(content.trim());


Obtain All Hyperlinks From a Page in a PDF

The second important thing is to validate the PDF by checking the hyperlinks. The following code provides you with the hyperlinks in the document.

The getAnnotations() method of PDPage class gives you the list of annotations used in the document. Secondly, fetch the items that are part of the type PDActionURI. This provides a list of URLs used in the document or in a page.

PDDocument document = PDDocument.load(new File("name.pdf"));
document.getClass();
PDPage pdfpage = document.getPage(1);
            annotations = pdfpage.getAnnotations();
            for (int j = 0; j < annotations.size(); j++) {
                PDAnnotation annot = annotations.get(j);
                if (annot instanceof PDAnnotationLink) {
                    PDAnnotationLink link = (PDAnnotationLink) annot;
                    PDAction action = link.getAction();
                    if (action instanceof PDActionURI) {
                        PDActionURI uri = (PDActionURI) action;
                        urls += uri.getURI();
                        System.out.println(uri.getURI());
                    }
                }
            }
        }


Extract All Images From a PDF

In addition to text and hyperlinks, PDFBox provides the provision to extract images from a document. 

 getResources() method of PDPage class gives you the list of all resource objects (like images).

PDDocument document = PDDocument.load(new File("name.pdf"));
PDPage pdfpage = document.getPage(1);

        int i = 1;
        PDResources pdResources = pdfpage.getResources();
        for (COSName c : pdResources.getXObjectNames()) {
            PDXObject o = pdResources.getXObject(c);
            if (o instanceof org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) {
                File file = new File(i + ".png");
                i++;
                ImageIO.write(((org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) o).getImage(), "png", file);
            }
        }


Get Words That Are Hyperlinked in a PDF

Getting text, hyperlinks, and images from a PDF are fairly straightforward tasks. 

Next, we go a little further to see how to extract hyperlinked words.

As we see in the second section, for all 'link' annotations, and for every link, crop the text area by using PDRectangle class. The below code gives you the list of words that are hyperlinked in a document.

PDDocument document = PDDocument.load(new File("name.pdf"));
        int pageNum=0;

        for( PDPage page : doc.getPages() )
        {
            pageNum++;
            PDFTextStripperByArea stripper = new PDFTextStripperByArea();
            List<PDAnnotation> annotations = page.getAnnotations();
            //first setup text extraction regions
            for( int j=0; j<annotations.size(); j++ )
            {
                PDAnnotation annot = annotations.get(j);
                if( annot instanceof PDAnnotationLink )
                {
                    PDAnnotationLink link = (PDAnnotationLink)annot;
                    PDRectangle rect = link.getRectangle();
                    //need to reposition link rectangle to match text space
                    float x = rect.getLowerLeftX();
                    float y = rect.getUpperRightY();
                    float width = rect.getWidth();
                    float height = rect.getHeight();
                    int rotation = page.getRotation();
                    if( rotation == 0 )
                    {
                        PDRectangle pageSize = page.getMediaBox();
                        y = pageSize.getHeight()-y;
                    }
                    else if( rotation == 90 )
                    {}
                    Rectangle2D.Float awtRect = new Rectangle2D.Float( x,y,width,height );
                    stripper.addRegion( "" + j, awtRect );
                }
            }

            stripper.extractRegions( page );

            for( int j=0; j<annotations.size(); j++ )
            {
                PDAnnotation annot = annotations.get(j);
                if( annot instanceof PDAnnotationLink )
                {
                    PDAnnotationLink link = (PDAnnotationLink)annot;
                    PDAction action = link.getAction();
                    String urlText = stripper.getTextForRegion( "" + j );
                    if( action instanceof PDActionURI )
                    {
                        PDActionURI uri = (PDActionURI)action;
                        System.out.println( "Page " + pageNum +":'" + urlText.trim() + "'=" + uri.getURI() );
                    }
                }
            }
        }


That's all for now! 

PDF Extract Java (programming language) Document

Opinions expressed by DZone contributors are their own.

Related

  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API in Java
  • How To Convert Common Documents to PNG Image Arrays in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!