Click or drag to resize

Working With Optional Content Groups

Overview

Optional content refers to sections of content in a PDF document that can be selectively viewed or hidden by document authors or consumers. This capability is useful in items such as CAD drawings, layered artwork, maps, and multi-language documents.

The following diagram shows the SDK classes used to implement optional content:

Open in full size

OCGWrappers
Optional Content Groups and Membership

Optional Content Groups

An optional content group (PdfOCGroup) is a class representing a collection of page objects (PdfPageObject) that can be made visible or invisible dynamically by users of viewer applications. The page objects belonging to such a group can reside anywhere in the document: they need not be consecutive in drawing order, nor even belong to the same page.

In its simplest form, each group contains a Name property for presentation in a user interface. It may also have an Intent property that describes its intended use and a Usage property that describes the nature of its content.

The Name property for presentation in a user interface. It may also have an Intent property provides a way to distinguish between different intended uses of optional content. For example, many document design applications, such as CAD packages, offer layering features for collecting groups of graphics together and selectively hiding or viewing them for the convenience of the author. However, this layering may be different (at a finer granularity, for example) than would be useful to consumers of the document. Therefore, it is possible to specify different intents for optional content groups within a single document. A given application may decide to use only groups that are of a specific intent. PDF 1.5 defines two intents:OCGIntentDesign, which is intended to represent a document designer’s structural organization of artwork, and OCGIntentView, which is intended for interactive use by document consumers. More intents may be added in future PDF versions. The special value OCGIntentAll indicates the set of all intents, including those not yet defined.

Tip Tip

The PdfOCConfig class also contain an Intent property. If one or more of a group’s intents is contained in the current configuration’s set of intents, the group is used in determining visibility. If there is no match, the group has no effect on visibility.

Individual page objects in a document specify the optional content group or groups that affect their visibility. Any page object whose visibility can be affected by a given optional content group is said to belong to that group.

A group is assigned a state, which is either OCGStateOn or OCGStateOff. States are not themselves part of the PDF document but can be set programmatically or through the viewer user interface to change the visibility of page object. When a document is first opened, the groups’ states are initialized based on the document’s Default configuration.

In the typical case, page object belonging to a group is visible when the group is On and invisible when it is Off. In more complex cases, page object can belong to multiple groups, which may have conflicting states. These cases are described by the use of PdfOCMembership class.

Optional Content Membership

As mentioned above, page object typically belongs to a single optional content group and is visible when the group is On and invisible when it is Off. To express more complex visibility policies, page object should declare itself not to belong directly to an optional content group but rather to an optional content membership.

The PdfOCMembership class can express its visibility policy in two ways:

  1. The Policy property specifies a simple boolean expression indicating how the optional content groups specified by the OCGs collection determine the visibility of page object controlled by the membership.

  2. The VE entry of the membership Dictionary, which is a visibility expression that can specify an arbitrary boolean expression for computing the visibility of page object from the states of optional content groups.

Configuring Optional Content

A PDF document containing optional content can specify the default states for the optional content groups in the document and indicate which external factors should be used to alter the states. The following sections describe the SDK classes that are used to specify this information.

  1. “Optional Content Properties” describes the PdfOCProperties class that lists all the optional content groups in the document and their possible configurations.

  2. “Optional Content Configurations” describes the PdfOCConfig class that specify initial state settings and other information about the groups in the document.

  3. “Usage and Auto State” describe how the states of groups can be affected based on external factors.

Optional Content Properties

The PdfDocumentOCProperties holds the PdfOCProperties class, which contains a list of all the optional content groups in the document, as well as information about the default and alternate configurations for optional content. This property is required if the file contains any optional content; if it is missing, a PDF consumer should ignore any optional content structures in the document.

This class contains the following properties

OCGs

(Required) The PdfOCGroupCollection which contains a list of all the optional content groups in the document, in any order. Every optional content group must be included in this collection.

Default

(Required) The default viewing optional content configuration (see “Optional Content Configurations” below).

Configs

(Optional) The PdfOCConfigCollection of alternate optional content configurations (see “Optional Content Configurations” below) for PDF processing applications or features.

Optional Content Configurations

The Default and Configs properties are configurations, which represent different presentations of a document’s optional content groups for use by PDF processing applications or features. The Default configuration specifies the initial state of the optional content groups when a document is first opened. Configs list other configurations that may be used under particular circumstances. The properties of the PdfOCConfig class are shown below.

Name

A name for the configuration, suitable for presentation in a user interface.

Creator

Name of the application or feature that created this configuration dictionary.

BaseState

Used to initialize the states of all the optional content groups in a document when this configuration is applied. The value of this entry must be one of the following:

  • On: The states of all groups are turned on.

  • Off: The states of all groups are turned off.

  • Unchanged: The states of all groups are left unchanged.

After this initialization, the contents of the On and Off collections are processed, overriding the state of the groups included in the collections.

Default value: On

Important note Important

In the Default configuration, its value must be On.

On

The PdfOCGroupCollection of optional content groups whose state should be set to On when this configuration is applied.

Tip Tip

If the BaseState entry is On, this entry is redundant.

Off

The PdfOCGroupCollection of optional content groups whose state should be set to Off when this configuration is applied.

Tip Tip

If the BaseState entry is Off, this entry is redundant.

Intent

A set of flags specifying which optional content groups’ states to consider and ignore in calculating the visibility of content (see the Intent decription in the "Optional Content Groups" section above).

PDF 1.5 defines two flags, View and Design. Future versions may define others. In addition, the flag All indicates the set of all intents, including those not yet defined. Default value: View.

Important note Important

In the Default configuration, its value must be View.

AutoState

The PdfOCAutoStateCollection of PdfOCAutoState classes specifying which PdfOCUsage categories should be consulted by viewer applications to automatically set the states of optional content groups based on external factors, such as the current system language or viewing magnification, and when they should be applied

Order

The specifying the recommended order for presentation of optional content groups in a user interface. The collection may include the objects that implement the IOrderNode interface:

  • PdfOCGroup, whose Name entry is to be displayed in the user interface.

  • PdfOCOrderCollection to allow nesting as in a tree or outline structure.

  • PdfOCLabel. Each nested collection may optionally have as its first element a text string to be used as a non-selectable label in the user interface.

Tip Tip

PdfOCLabel in nested collection should be used to present collections of related optional content groups, and not to communicate actual nesting of content inside multiple layers of groups. To reflect actual nesting of groups in the content, such as for layers with sublayers, nested collections without the PdfOCLabel should be used.

An empty collection explicitly specifies that no groups should be presented.

In the Default configuration, the default value is an empty collection; in other configurations, the default is the Order value from the default configuration.

Important note Important

Any groups not listed in this collection should not be presented in any user interface that uses the configuration.

ListMode

A value specifying which optional content groups in the Order collection should be displayed to the user.

  • AllPages: Display all groups in the Order collection.

  • VisiblePages: Display only those groups in the Order collection that are referenced by one or more visible pages.

Default value: AllPages.

RBGroups

The PdfOCRadioButtonCollection consisting of one or more PdfOCGroupCollection, each of which represents a collection of optional content groups whose states are intended to follow a radio button paradigm. That is, the state of at most one optional content group in each array should be On at a time. If one group is turned On, all others must be turned Off. However, turning a group from On to Off does not force any other group to be turned On.

An empty collection explicitly indicates that no such collections exist.

In the Default configuration, the default value is an empty collection; in other configurations, the default is the RBGroups value from the default configuration.

Locked

The PdfOCGroupCollection of optional content groups that should be locked when this configuration is applied. The state of a locked group cannot be changed through the user interface of a viewer application. Producers can use this entry to prevent the visibility of content that depends on these groups from being changed by users.

Default value: an empty collection

Note Note

This property does not prevent the states of optional content groups from being changed by means other than the user interface, such as JavaScript or items in the AutoState collection.

The AutoState property specify how viewer applications should automatically set the state of optional content groups based on external factors, as discussed in the following section.

Usage and Auto State

Optional content groups are typically constructed to control the visibility of page objects that are related in some way. Objects can be related in several ways; for example, a group may contain content in a particular language or content suitable for viewing at a particular magnification.

The PdfOCUsage contains information describing the nature of the content controlled by the group. This clas can contain any combination of the entries shown in the below table.

PdfCreatorInfo

A class used by the creating application to store application-specific data associated with the optional content group. It contains two required properties:

  • Creator: A text string specifying the application that created the group.

  • Subtype: A name defining the type of content controlled by the group. Suggested values include but are not limited to Artwork, for graphic-design or publishing applications, and Technical, for technical designs such as building plans or schematics.

Additional entries may be included into the Dictionary to present information relevant to the creating application or related applications.

Note Note

Groups whose Intent property contains Design typically include a CreatorInfo.

PdfLanguage

A class specifying the language of the content controlled by the optional content group. It has two properties:

  • Language (required): A text string that specifies a language and possibly a locale. For example, es-MX represents Mexican Spanish.

  • Preferred (optional): A state whose values may be On or Off. Default value: Off. It is used by viewer applications when there is a partial match but no exact match between the system language and the language strings in all usage classes.

PdfExport

A class containing one entry, ExportState whose value may be On or Off. This value indicates the recommended state for content in the group when the document (or part of it) is saved by a viewer application to a format that does not support optional content (for example, an earlier version of PDF or a raster image format).

PdfZoom

A class specifying a range of magnifications at which the content in the optional content group is best viewed. It contain the following properties:

  • Min: The minimum recommended magnification factor at which the group should be On. Default value: 0.

  • Max: The magnification factor below which the group should be On. Default value: infinity.

PdfPrint

A class specifying that the content in the group is intended for use in printing. It contains the following properties:

  • Subtype: A name object specifying the kind of content controlled by the group; for example, Trapping, PrintersMarks and Watermark.

  • PrintState: wose value may be On or Off, indicating that the group should be set to that state when the document is printed from a viewer application.

PdfView

A class that has a single property, ViewState that may have a value of On or Off, indicating that the group should be set to that state when the document is opened in a viewer application.

PdfUser

A class specifying one or more users for whom the optional content group is primarily intended. The class has two properties:

PdfPageElement

A class declaring that the group contains a pagination artifact. It contains one property, Subtype, whose value is a name that can be HeaderFooter, Foreground image or graphic, Background image or graphic, or Logo.

While the data in the PdfOCUsage class can be viewed as information for a document user to examine, it can also be used by viewer applications to automatically manipulate the state of optional content groups based on external factors such as current system language settings or zoom level. Document authors can use PdfOCAutoState class to specify which properties in the PdfOCUsage should be consulted to automatically set the state of optional content groups based on such factors. Auto State is specified in the PdfOCConfigAutoState property. If AutoState property is null, states are not automatically adjusted based on usage information.

A PdfOCAutoState class specifies the rules for which PdfOCUsage properties should be used by viewer applications to automatically manipulate the state of optional content groups, which groups should be affected, and under which circumstances. The below table shows the properties in a usage application dictionary.

Event

A name defining the situation in which this usage application dictionary should be used. May be View, Print, or Export.

OCGs

The PdfOCGroupCollection listing the optional content groups that should have their states automatically managed based on information in their Usage. Default value: an empty collection, indicating that no groups are affected.

Category

A set of flags, each of which corresponds to a property of the PdfOCUsage class. When managing the states of the optional content groups in the OCGs collection, each of the corresponding categories in the group’s Usage should be considered.

The Event property specifies whether the usage settings should be applied during viewing, printing, or exporting the document. The OCGs property specifies the set of optional content groups to which usage settings should be applied. For each of the groups in OCGs, the properties in its Usage specified by Category are examined to yield a recommended state for the group. If all the properties yield a recommended state of On, the group’s state is set to On; otherwise, its state is set to Off.

The Category is used as follows:

  • View: The recommended state is the value of the ViewState property. This property allows a document to contain content that is relevant only when the document is viewed interactively, such as instructions for how to interact with the document.

  • Print: The recommended state is the value of the PrintState property. If PrintState is Unspecified the state of the optional content group is left unchanged.

  • Export: The recommended state is the value of the ExportState property.

  • Zoom: If the current magnification level of the document is greater than or equal to Min and less thanMax, an On state is recommended; otherwise, Off is recommended.

  • User: The Name property specifies a name or names to match with the user’s identification. The UserType property determines how the Name property is interpreted (name, title, or organization). If there is an exact match, an On state is recommended; otherwise Off is recommended.

  • Language: This category allows the selection of content based on the language and locale of the application. If an exact match to the language and locale is found among the Language properties of the optional content groups in the PdfOCAutoState list, all groups that have exact matches receive an On recommendation. If no exact match is found, but a partial match is found (that is, the language matches but not the locale), all partially matching groups that have Preferred properties with a value of On receive an On recommendation. All other groups receive an Off recommendation.

Determining the State of Optional Content Groups

This section summarizes the rules by which applications make use of the configuration and usage application dictionaries to set the state of optional content groups. For purposes of this discussion, it is useful to distinguish the following types of applications:

  1. Viewer applications, which allow users to interact with the document in various ways.

  2. Design applications, which offer layering features for collecting groups of graphics (page objects) together and selectively hiding or viewing them.

    Note Note

    The following rules are not meant to apply to design applications; they may manage their states in an entirely different manner if they choose.

  3. Aggregating applications, which import PDF files as graphics.

  4. Printing applications, which print PDF files.

When a document is first opened, its optional content groups are assigned a state based on the PdfOCPropertiesDefault configuration in thePdfDocumentOCProperties:

  1. The value of BaseState is applied to all the groups.

  2. The groups listed in either the On or Off collection (depending on which one is opposite to BaseState) have their states adjusted.

This state is the recommended state for printing and aggregating applications, which should not apply the changes based on AutoState described below. However, for more advanced functionality, they may provide user control for manipulating the individual states of optional content groups.

Note Note

Viewer applications should also provide users with an option to view documents in this state (that is, to disable the automatic adjustments discussed below). This option permits an accurate preview of the content as it will appear when placed into an aggregating application or sent to a stand-alone printing system.

The remaining discussion in this section applies only to viewer applications. Such applications should examine the AutoState collection for auto states that have an Event of type OCGEventView. For each one found, the groups listed in its PdfOCAutoStateOCGs collection should be adjusted as described in “Usage and Auto State” section.

Subsequently, the document is ready for interactive viewing by a user.

When a document is printed by a viewer application, AutoState with an event type OCGEventPrint are applied over the current states of optional content groups. These changes persist only for the duration of the print operation; then all groups revert to their prior states.

Similarly, when a document is exported to an earlier version of PDF or other format that does not support optional content, AutoState with an event type OCGEventExport are applied over the current states of optional content groups. Changes persist only for the duration of the export operation; then all groups revert to their prior states.

To make it easier to determine the states of groups, SDK provides a method that implements the above rules: PdfOCPropertiesCheckVisibility

This method takes two parameters: an optional content group or index into the OCGs collection, and an event type.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    if (doc.OCProperties != null && doc.OCProperties.OCGs!= null)
    {
        foreach (var group in doc.OCProperties.OCGs)
        {
            if(doc.OCProperties.CheckVisibility(group, OCGEvent.View))
            {
                // the group state is OCGState.On
            }
            else
            {
                // the group state is OCGState.Off
            }
        }
    }
}
Making Graphical Content Optional

Graphical content in a PDF file can be made optional by specifying an optional content group or membership in the PdfOptionalContent class. Since this class is inherited from PdfMarkedContent, its instances can be added to the PdfPageObjectMarkedContent collection. Thus, a claim is made that the given page object belongs to this group or membership.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    // Get some page, page object and group.
    var page = doc.Pages[0];
    var group = doc.OCProperties.OCGs[0];
    var pageObject = page.PageObjects[0];

    // Create an optional content and assign it as a marked content to the page object.
    var optionalContent = new PdfOptionalContent(group);
    pageObject.MarkedContent.Add(optionalContent);

    // Generate page content to avoid losing changes when the page is disposed.
    page.GenerateContent();
}

And it's the same with membership.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    // Get some page, page object and group.
    var page = doc.Pages[0];
    var group1 = doc.OCProperties.OCGs[0];
    var group2 = doc.OCProperties.OCGs[0];
    var pageObject = page.PageObjects[0];

    //Create a membership
    var membership = new PdfOCMembership(doc);
    membership.OCGs.Add(group1);
    membership.OCGs.Add(group2);
    membership.Policy = OCGPolicy.AllOn;

    // Create an optional content and assign it as a marked content to the page object.
    var optionalContent = new PdfOptionalContent(membership);
    pageObject.MarkedContent.Add(optionalContent);

    // Generate page content to avoid losing changes when the page is disposed.
    page.GenerateContent();
}
Creating optional content groups
C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    // Create optional content groups named Group 1, Group2, and Group 3.
    doc.OCProperties = new PdfOCProperties(doc);
    doc.OCProperties.OCGs.Add(new PdfOCGroup("Group 1"));
    doc.OCProperties.OCGs.Add(new PdfOCGroup("Group 2"));
    doc.OCProperties.OCGs.Add(new PdfOCGroup("Group 3"));

    // Specify the order: Group 3, Group 2 and Group 1.
    doc.OCProperties.Default.Order = new PdfOCOrderCollection(doc)
    {
        doc.OCProperties.OCGs[2],
        doc.OCProperties.OCGs[1],
        doc.OCProperties.OCGs[0]
    };
}
See Also