kabeersvohra
kabeersvohra

Reputation: 1059

How to extract fonts from PDDocument in PDFBox 2.0.2

I have seen how to do this in previous versions like below:

How to extract font styles of text contents using pdfbox?

But I think the getFonts() method has been removed now. I want to retrieve a map of texts to fonts (Map<String, PDFont>) in the new version of PDFBox but I have no idea how.

Thanks

Kabeer

Upvotes: 5

Views: 10719

Answers (4)

Tilman Hausherr
Tilman Hausherr

Reputation: 18851

Do this:

PDDocument doc = PDDocument.load("C:/mydoc3.pdf");
for (int i = 0; i < doc.getNumberOfPages(); ++i)
{
    PDPage page = doc.getPage(i);
    PDResources res = page.getResources();
    for (COSName fontName : res.getFontNames())
    {
        PDFont font = res.getFont(fontName);
        // do stuff with the font
    }
}

Note that this is a very simple solution of the problem, it only works on the top level. There could be more fonts in xobject forms, patterns, softmasks, and possibly more.

Upvotes: 10

balram singh
balram singh

Reputation: 31

 PDFMetaData pdfMeta = new PDFMetaData();
 PDDocument document = PDDocument.load(new File("/Users/ban.pdf"));
 PDPage page = document.getPage(0);
 PDResources res = page.getResources();
 for (COSName fontName : res.getFontNames())
{
  PDFont font = res.getFont(fontName);
  pdfMeta.setFontName(font);                    
}

Upvotes: 3

Sunil K Chaudhary
Sunil K Chaudhary

Reputation: 21

This one is to Extract font of the Pdf file using pdfbox 2.0.6.

import java.io.File;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
public class PDFFontExtractor {
    public static void main(String args[])
    {
        try
        {  
            PDDocument pddDocument = PDDocument.load(new File("C:\\Users\\Desktop\\sample1.pdf"));
            for (int i = 0; i < pddDocument.getNumberOfPages(); ++i)
            {
                PDPage page = pddDocument.getPage(i);
                PDResources res = page.getResources();
                for (COSName fontName : res.getFontNames())
                {
                    PDFont font = res.getFont(fontName);
                    System.out.println("FONT :: "+ font);
                }
            } 
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

Upvotes: -2

Maruan Sahyoun
Maruan Sahyoun

Reputation: 589

For PDFBox 2.x the revised code for the answer you are linking to is

PDDocument  doc = PDDocument.load("C:/mydoc3.pdf");
for(PDPage page : doc.getPages()){
    // get the names of the fonts in the resources dictionary
    Iterable<COSName> iterable = page.getResources().getFontNames();
    // to get the font for each item call
    // page.getResources().getFont(COSName name);
}

Upvotes: 1

Related Questions