Difference between revisions of "Transparency in PDF"

From
Jump to: navigation, search
(Created page with "==Blend modes== Blend mode is a setting one may use for the graphics state object that defines how the final color will be calculated...")
 
Line 65: Line 65:
  
 
[[File:apitron_pdf_kit_transparency_alpha_exclusion.png|none|frame|Transparent object drawn using '''Exclusion''' blend mode]]
 
[[File:apitron_pdf_kit_transparency_alpha_exclusion.png|none|frame|Transparent object drawn using '''Exclusion''' blend mode]]
 +
 +
==Transparency group XObjects==
 +
A Transparency group [[Form XObject|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 [[Form XObject|XObject]] is a [[Form XObject|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 [[Transparency in PDF#Soft mask|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
 +
 +
<nowiki>
 +
// 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};
 +
        fixedDocument.ResourceManager.RegisterResource(graphicsState);                           
 +
 +
        // create transparency group and draw several rects inside it
 +
        TransparencyGroup transparencyGroup = new TransparencyGroup("myGroup", new Boundary(0,0,150,150));               
 +
        fixedDocument.ResourceManager.RegisterResource(transparencyGroup);               
 +
               
 +
        // 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);
 +
            content.SetDeviceNonStrokingColor(color);
 +
            content.FillAndStrokePath(path);
 +
        };
 +
               
 +
        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)
 +
        pageContent.SaveGraphicsState();
 +
        // draw bg image
 +
        pageContent.Translate(10, 680);
 +
        pageContent.AppendImage("logo",0,0,150,150);
 +
        // set state and draw transparency group
 +
        pageContent.SetGraphicsState("semiTransparent");               
 +
        pageContent.AppendXObject("myGroup");
 +
        pageContent.RestoreGraphicsState();
 +
 +
        // draw rects over an image (2)
 +
        pageContent.SaveGraphicsState();
 +
        // draw bg image
 +
        pageContent.Translate(170, 680);
 +
        pageContent.AppendImage("logo", 0, 0, 150, 150);
 +
 +
        // set state  and draw colored rects directly on page
 +
        pageContent.SetGraphicsState("semiTransparent");
 +
        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 });
 +
        pageContent.RestoreGraphicsState();
 +
        // save document
 +
        fixedDocument.Save(outputStream);
 +
    }
 +
}
 +
</nowiki>
 +
 +
This code produces the following results:
 +
 +
[[File:apitron_pdf_kit_transparency_group_form_xobject.png|none|frame|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.

Revision as of 22:36, 21 February 2018

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.

Alpha

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
        document.ResourceManager.RegisterResource(gs);

        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();
        rect.AppendRectangle(0,0,100,100);

        content.Translate(10,730);
        // fill and stroke this path, it creates an opaque rect
        content.FillAndStrokePath(rect);

        // transparency will be set using the graphics state resource
        content.SetGraphicsState("gs01");
        // 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);
        content.FillAndStrokePath(rect);
    
        // save document
        document.Save(outputStream);
    }
}
 

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};
        fixedDocument.ResourceManager.RegisterResource(graphicsState);                            

        // create transparency group and draw several rects inside it
        TransparencyGroup transparencyGroup = new TransparencyGroup("myGroup", new Boundary(0,0,150,150));                
        fixedDocument.ResourceManager.RegisterResource(transparencyGroup);                
                
        // 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);
            content.SetDeviceNonStrokingColor(color);
            content.FillAndStrokePath(path); 
        };
                
        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)
        pageContent.SaveGraphicsState();
        // draw bg image
        pageContent.Translate(10, 680);
        pageContent.AppendImage("logo",0,0,150,150);
        // set state and draw transparency group
        pageContent.SetGraphicsState("semiTransparent");                
        pageContent.AppendXObject("myGroup");
        pageContent.RestoreGraphicsState();

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

        // set state  and draw colored rects directly on page
        pageContent.SetGraphicsState("semiTransparent");
        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 });
        pageContent.RestoreGraphicsState();
        // save document
        fixedDocument.Save(outputStream);
    }
}
 

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.