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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Building and Deploying Microservices With Spring Boot and Docker
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • Reactive Programming

Trending

  • Building and Deploying Microservices With Spring Boot and Docker
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • Reactive Programming
  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?

Gowthamraj Palani user avatar by
Gowthamraj Palani
·
Updated Oct. 01, 19 · Tutorial
Like (13)
Save
Tweet
Share
82.23K 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.

Trending

  • Building and Deploying Microservices With Spring Boot and Docker
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • Reactive Programming

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: