简体   繁体   中英

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

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
    }
}
 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);                    
}

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);
}

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM