1

Is it possible to retrieve font color for each character from a PDF using PDFBox As per my previous question's solution : How to extract Font color using PDFBOX java? I have proceeded till retrieving font attributes below is my code snippet

    PDDocument doc = null;
    doc = PDDocument.load("C:\\Users\\Desktop\\abc.pdf");
    PDFStreamEngine engine = new PDFStreamEngine(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PageDrawer.properties"));
    PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get(0);
    engine.processStream(page, page.findResources(), page.getContents().getStream());
    PDGraphicsState graphicState = engine.getGraphicsState();
    System.out.println(graphicState.getNonStrokingColor().getJavaColor()); 
    doc.close();

Actuall PDF contain only the following text : MessageHi where Message would contain Blue as font color and Hi would hold green , when I execute above piece of code it displays me

java.awt.Color[r=0,g=255,b=0]  ----> green 

Similarly i have tried with below piece of code to retrieve each character and their respective font attributes but , while displaying color it always displays java.awt.Color[r=0,g=0,b=0] --- black color

public class PrintTextLocations extends PDFTextStripper {

public PrintTextLocations() throws IOException {
    super.setSortByPosition(true);
}

public static void main(String[] args) throws Exception
{
    PDDocument document = null;
    document = PDDocument.load("C:\\Users\\Desktop\\abc.pdf");
    List allPages = document.getDocumentCatalog().getAllPages();
    PrintTextLocations printer = new PrintTextLocations();
        for (int i = 0; i < allPages.size(); i++) 
        {
            PDPage page = (PDPage) allPages.get(i);
            System.out.println("Processing page: " + i);
            PDStream contents = page.getContents();
            if (contents != null)
            {
                printer.processStream(page, page.findResources(), page.getContents().getStream());              
            }
        }       
        document.close();
    } 
protected void processTextPosition(TextPosition text){      
        try {
            System.out.println("String[" + text.getXDirAdj() + ","
                    + text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="
                    + text.getXScale() + " height=" + text.getHeightDir()
                    + " space=" + text.getWidthOfSpace() + " width="
                    + text.getWidthDirAdj() + "]" + text.getCharacter() + getGraphicsState().getNonStrokingColor().getJavaColor());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }                   
}
}

Can any one help me out to retrieve font color for each character pls

Thanks

Community
  • 1
  • 1
Ganeshja
  • 2,675
  • 12
  • 36
  • 57

0 Answers0