Transparency in PDF

Revision as of 23:01, 21 February 2018 by Adminko (talk | contribs)
Jump to: navigation, search

Blend modes

Blend mode is a setting one may use for the graphics state object that defines how the final color will be calculated based on the predefined formulas. A Normal blend mode is the typical setting and all of them can be found in section 11.3.4 Blend Mode of the PDF specification. It's implemented in the Fixed layout API as theGraphicsState.BlendMode property.


Transparent objects can be drawn using the current alpha setting stored in the graphics state object. There are two values of type double ranging from 0.0 to 1.0 and indicating the degree of transparency that should be applied to the filled or stroked content.

The code below illustrates this concept:

using (FileStream outputStream = new FileStream("outfile.pdf", FileMode.Create, FileAccess.Write))
    // create new PDF document
    using(FixedDocument document = new FixedDocument())
        document.Pages.Add(new Page());
        // register graphics state resource
        GraphicsState gs = new GraphicsState("gs01") {CurrentStrokingAlpha = 0.3, CurrentNonStrokingAlpha = 0.3};                
        // register graphics state resource

        Content content = document.Pages[0].Content;

        // select current colors
        content.SetDeviceStrokingColor (new double[]{1,0,0});
        content.SetDeviceNonStrokingColor(new double[] { 0, 1, 0 });

        // create rect path
        Path rect = new Path();

        // fill and stroke this path, it creates an opaque rect

        // transparency will be set using the graphics state resource
        // select current colors
        content.SetDeviceStrokingColor(new double[] { 0, 1, 0 });
        content.SetDeviceNonStrokingColor(new double[] { 1, 0, 0 });
        // draw a transparent rect
        content.Translate(80, -20);
        // save document

It produces the following results, see the image below:

Transparent object drawn using Normal blend mode

Transparency in PDF is outlined in section 11 “Transparency” of the specification and describes many other things to consider except the basic alpha settings. As an example, current alpha could be combined with any blending mode described in section 11.3.5 “Blend Mode” to achieve various visual effects. There are also transparency groups and soft mask objects which are explained the the next sections of the current article.

If we would change the blending mode in code sample produced the image above from Normal to Exclusion using the code below:

    // register graphics state resource
    GraphicsState gs = new GraphicsState("gs01") {CurrentStrokingAlpha = 0.3, CurrentNonStrokingAlpha = 0.3, BlendMode = BlendMode.Exclusion};

Then results would be as follows:

Transparent object drawn using Exclusion blend mode

Transparency Group XObjects

A Transparency group XObject is a special type of Group Form XObject (see the section 8.10.3 “Group XObjects” in PDF specification) that can be used to group graphical elements together and have extended support for transparency-related operations. Transparency groups and their properties are described in section 11.6.6 “Transparency Group XObjects” of the PDF specification. Any group XObject is a form XObject with an additional attribute describing its type. Since there is only one type of Group XObjects defined in PDF specification so far, it only makes sense to discuss transparency groups.

Apitron PDF Kit supports the creation of transparency groups which can be used for various reasons. As an example you may check an article below describing soft masks and use them to create advanced masking effects. Transparency groups can be created using TransparencyGroup class provided by Fixed layout API and their properties can be changed via Attributes property.

The most important properties of a transparency group define whether the group should be treated as “isolated” or “knockout” or both. These terms describe an interaction between group as a whole with its background or/and other elements on page and also the interaction between the objects(drawings) added into this group. These topics are quite complicated and are explained in details in sections 11.2 “Overview of Transparency”, 11.4.5 “Isolated Groups”, 11.4.6 “Knockout Groups” of the PDF specification. See also figures L.16 and L.17 on page 741 of PDF specification.

Draw objects using Transparency Group

The code sample below demonstrates how to use transparency group for drawing several objects at once and its differences from the “normal” drawing when transparency becomes involved. It draws two identical sets of objects over the same image and sets the current alpha state, so that we'll have:

  • a transparency group containing colored rectangles, on the left
  • a set of ungrouped colored rectangles, on the right
// create output file
using (Stream outputStream = File.Create("transparency_group.pdf"))
    // create document and add one page to it
    using(FixedDocument fixedDocument = new FixedDocument())
        fixedDocument.Pages.Add(new Page());

        fixedDocument.ResourceManager.RegisterResource(new Apitron.PDF.Kit.FixedLayout.Resources.XObjects.Image("logo", "apitron.png"));
        // create graphics state, it will be used to define group transparency
        GraphicsState graphicsState = new GraphicsState("semiTransparent"){CurrentNonStrokingAlpha = 0.7};

        // create transparency group and draw several rects inside it
        TransparencyGroup transparencyGroup = new TransparencyGroup("myGroup", new Boundary(0,0,150,150));                
        // draw colored rects inside the transparency group
        Path path = new Path();
        path.AppendRectangle(20, 20, 50, 50);

        Action<ClippedContent,double, double, double[]> drawRect = (content,tx, ty, color) =>
            content.Translate(tx, ty);
        drawRect(transparencyGroup.Content,0, 0, new double[] {1, 0, 0});
        drawRect(transparencyGroup.Content,30, 30, new double[] { 0, 1, 0 });
        drawRect(transparencyGroup.Content,30, 30, new double[] { 0, 0, 1 });

        ClippedContent pageContent = fixedDocument.Pages[0].Content;
        // draw group over an image (1)
        // draw bg image
        pageContent.Translate(10, 680);
        // set state and draw transparency group

        // draw rects over an image (2)
        // draw bg image
        pageContent.Translate(170, 680);
        pageContent.AppendImage("logo", 0, 0, 150, 150);

        // set state  and draw colored rects directly on page
        drawRect(pageContent, 0, 0, new double[] { 1, 0, 0 });
        drawRect(pageContent, 30, 30, new double[] { 0, 1, 0 });
        drawRect(pageContent, 30, 30, new double[] { 0, 0, 1 });
        // save document

This code produces the following results:

Draw objects using Transparency Group

Note that rectangles on the left, which were included into the transparency group, were treated as a whole transparent thing, while rectangles on the right were treated as separate transparent objects. This sample demonstrates one of the possible applications of transparency groups.

Soft mask

Using images it's possible to create a stencil mask using raster data as a source for mask values and draw through it with current non-stroking color or apply an explicit mask to achieve the same effect but for the image itself. But stencil masks are quite limited in terms of defining transparency. You can only indicate whether the particular location within the mask is fully transparent or not, making it impossible to define a mask containing semi-transparent areas.

Soft masks, discussed here, are designed for complex masking effects which are impossible to achieve with any other type of masking. The word "soft" emphasizes that the mask value at a given point is not limited to just 0.0 or 1.0 but can be represented by intermediate fractional values as well. Such a mask is typically the only means of providing position-dependent opacity values, since elementary objects do not have the any intrinsic properties specifying opacity. It is fully described in section 11.5 “Soft Masks” of the PDF specification.

A special class in Fixed layout API was designed to work with these masks and it’s called not surprisingly SoftMask, it’s a resource object that in its turn uses TransparencyGroup instance as a source for soft mask values. TransparencyGroup is special kind of a form XObject which is being discussed above (Transparency Group XObjects) and, among other things, can provide soft mask values derived either from its alpha or luminosity calculated for any given point. It implements ClippedContent and therefore can contain the same drawing commands as other descendants like Page for example.

To apply a SoftMask while drawing, one have to create a GraphicsState object and apply it by calling the SetGraphicsState() function on the desired ClippedContent instance before any further drawing occurs.