Amerousful
Amerousful

Reputation: 2545

IText 7, get transparency of text (reference to ExtGState)

I have PDF with two simple texts. One of which contains transparency. The text object contains a reference to ExtGState which has transparency value. How I can get this value?

There is picture from debug tool (pdf apache pdfbox): enter image description here

I found how to get transparency value from the resource, but I don't know how to match it with certain text.

double value = document.getFirstPage()
        .getResources()
        .getPdfObject()
        .getAsDictionary(PdfName.ExtGState)
        .getAsDictionary(new PdfName("GS1"))
        .getAsNumber(PdfName.ca)
        .getValue();

I also have a class which implement IEventListener and get many different information about text in PDF.

class TextRenderListener implements IEventListener {

 @Override
    public void eventOccurred(IEventData data, EventType type) {
        if (type.equals(EventType.RENDER_TEXT)) {
            TextRenderInfo textRenderInfo = (TextRenderInfo) data;
            CanvasGraphicsState canvasGraphicsState = textRenderInfo.getGraphicsState();

    ...
   }
 ...
}

But fillAlpha and strokeAlpha always == 1.0 and I cannot find any reference to Resource ExtGstate

Parser:

new PdfDocumentContentParser(document).processContent(pageNumber, new TextRenderListener);

Pdf: https://filebin.net/34vm4sxl715oxy6z

Upvotes: 1

Views: 692

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12312

You mention that fillAlpha and strokeAlpha are always equal to 1 and that indeed was the case previously, but this was fixed recently and the fix is available in current 7.1.11-SNAPSHOT version of iText. Here is the example code:

class TextRenderListener implements IEventListener {

    @Override
    public void eventOccurred(IEventData data, EventType type) {
        if (type.equals(EventType.RENDER_TEXT)) {
            TextRenderInfo textRenderInfo = (TextRenderInfo) data;
            float transparency = textRenderInfo.getGraphicsState().getFillOpacity();
            System.out.println(transparency);
        }
    }

    @Override
    public Set<EventType> getSupportedEvents() {
        return new HashSet<>(Collections.singletonList(EventType.RENDER_TEXT));
    }
}

For your document it prints the following contents into the console (so the first piece of text is not transparent and the second one is transparent):

1.0
0.34902

To use the SNAPSHOT version you need to add the following Maven repository to your project:

<repositories>
  <repository>
    <id>itext-snapshot</id>
    <name>iText Repository - snapshots</name>
    <url>https://repo.itextsupport.com/snapshot</url>
  </repository>
</repositories>

Upvotes: 2

Related Questions