PDFBox: Extract Content From a PDF Using Java
Want to learn how you can extract content from a PDF?
Join the DZone community and get the full member experience.
Join For FreeHow 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!
Opinions expressed by DZone contributors are their own.
Comments