Click or drag to resize

Working With Color Spaces

Overview

Pdfium.Net SDK includes facilities for getting and specifying the colors of page objects to be painted on the current page. A color value consists of one or more color components, which are usually numbers. For example, a gray level can be specified by a single number ranging from 0.0 (black) to 1.0 (white). Full color values can be specified in any of several ways; a common method uses three numeric values to specify red, green, and blue components.

Color values are interpreted according to the color space. The color space and fill and stroke color components can be retrieved from any page object using the following methods: GetFillColor, SetFillColorGetStrokeColorSetStrokeColor

Color spaces are classified into color space families and are grouped into the following class hierarchy:

Open in full size

Color Spaces
  • Device color spaces directly specify colors or shades of gray that the output device is to produce. They provide a variety of color specification methods, including grayscale, RGB (red-green-blue), and CMYK (cyan-magenta-yellowblack), corresponding to the color space classes CsDeviceGray, CsDeviceRGB, and CsDeviceCMYK.

  • CIE-based color spaces are based on an international standard for color specification created by the Commission Internationale de l’Éclairage (International Commission on Illumination). These spaces specify colors in a way that is independent of the characteristics of any particular output device. Color space classes in this category include CsCalGray, CsCalRGB, CsLab, and CsICCBased.

  • Special color spaces add features or properties to an underlying color space. They include facilities for patterns, color mapping, separations, and highfidelity and multitone color. The corresponding color space classes are CsPattern, CsIndexed, CsSeparation, and CsDeviceN.

Device Color Spaces

The device color spaces enable a page description to specify color values that are directly related to their representation on an output device. Color values in these spaces map directly (or by simple conversions) to the application of device colorants, such as quantities of ink or intensities of display phosphors. This enables a PDF document to control colors precisely for a particular device, but the results may not be consistent from one device to another.

Output devices form colors either by adding light sources together or by subtracting light from an illuminating source. Computer displays typically add colors; printing inks typically subtract them. These two ways of forming colors give rise to two complementary methods of color specification, called additive and subtractive color. The most widely used forms of these two types of color specification are known as RGB and CMYK, respectively, for the names of the primary colors on which they are based. They correspond to the following device color spaces:

  • CsDeviceGray controls the intensity of achromatic light, on a scale from black to white.

  • CsDeviceRGB controls the intensities of red, green, and blue light, the three additive primary colors used in displays.

  • CsDeviceCMYK controls the concentrations of cyan, magenta, yellow, and black inks, the four subtractive process colors used in printing.

DeviceGray Color Space

Black, white, and intermediate shades of gray are special cases of full color. A grayscale value is represented by a single number in the range 0.0 to 1.0, where 0.0 corresponds to black, 1.0 to white, and intermediate values to different gray levels.

The below example shows alternative ways to select the CsDeviceGray color space and a specific gray level within that space for stroking operations.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float[] color = { 0.5f };
    pageObject.SetStrokeColor(PdfColorSpace.DeviceGray(), color);
}

DeviceRGB Color Space

Colors in the CsDeviceRGB color space are specified according to the additive RGB (red-green-blue) color model, in which color values are defined by three components representing the intensities of the additive primary colorants red, green, and blue. Each component is specified by a number in the range 0.0 to 1.0, where 0.0 denotes the complete absence of a primary component and 1.0 denotes maximum intensity. If all three components have equal intensity, the perceived result theoretically is a pure gray on the scale from black to white. If the intensities are not all equal, the result is some color other than a pure gray.

Example shows alternative ways to select the CsDeviceRGB color space and a specific color within that space for filling operations.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    int R = 127;
    int G = 255;
    int B = 15;
    float[] color = { (float)R / 255, (float)G / 255, (float)B / 255 };
    pageObject.SetFillColor(PdfColorSpace.DeviceRGB(), color);
}

DeviceCMYK Color Space

The CsDeviceCMYK color space allows colors to be specified according to the subtractive CMYK (cyan-magenta-yellow-black) model typical of printers and other paper-based output devices. In theory, each of the three standard process colorants used in printing (cyan, magenta, and yellow) absorbs one of the additive primary colors (red, green, and blue, respectively). Black, a fourth standard process colorant, absorbs all of the additive primaries in equal amounts. The four components in a CsDeviceCMYK color value represent the concentrations of these process colorants. Each component is specified by a number in the range 0.0 to 1.0, where 0.0 denotes the complete absence of a process colorant (that is, absorbs none of the corresponding additive primary) and 1.0 denotes maximum concentration (absorbs as much as possible of the additive primary). Note that the sense of these numbers is opposite to that of RGB color components.

The below example shows alternative ways to select the CsDeviceCMYK color space and a specific color within that space for stroking operations.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float C = 0.7f;
    float M = 0;
    float Y = 0.5f;
    float K = 1;
    float[] color = { C, M ,Y, K };
    pageObject.SetStrokeColor(PdfColorSpace.DeviceCMYK(), color);
}
CIE-Based Color Spaces

Calibrated color in PDF is defined in terms of an international standard used in the graphic arts, television, and printing industries. CIE-based color spaces enable a page description to specify color values in a way that is related to human visual perception. The goal is for the same color specification to produce consistent results on different output devices, within the limitations of each device. Patagames PDF SDK supports four CIE based color space families, named CsCalGray, CsCalRGB, CsLab, and CsICCBased.

The CsCalRGB and CsLab color spaces are special cases of three-component CIE-based color spaces, known as CIE-based ABC color spaces. Color values in a CIE-based ABC color space have three components, arbitrarily named A, B, and C.

CalGray Color Space

A CsCalGray color space is a special case of a single component CIEbased color space, known as a CIE-based A color space. This type of space is the one dimensional analog of CIE-based ABC spaces. Color values in a CIE-based A space have a single component, arbitrarily named A and represents the gray component of a calibrated gray space. This component must be in the range 0.0 to 1.0.

A CsCalGray color space is a color space with only one transformation stage instead of two. The decoding function is a gamma function whose coefficient is specified by the Gamma property. The transformation matrix is derived from the WhitePoint property.

Gamma must be positive and is generally greater than or equal to 1. Default value: 1.

WhitePoint.X and WhitePoint.Z must be positive, and WhitePoint.Y must be equal to 1.0.

The following example establishes a space consisting of the Y dimension of the CIE 1931 XYZ space with the CCIR XA/11 recommended D65 white point.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float A = 1;
    float[] color = { A };
    float gamma = 2.22f;
    CIEPoint whitePoint = new CIEPoint(0.9505f, 1, 1.0890f);
    var colorSpace = new CsCalGray(doc, gamma, whitePoint);

    pageObject.SetFillColor(colorSpace, color);
}

CalRGB Color Space

A CsCalRGB color space is a CIE-based ABC color space with only one transformation stage instead of two. In this type of space, A, B, and C represent calibrated red, green, and blue color values. These three color components must be in the range 0.0 to 1.0; component values falling outside that range are adjusted to the nearest valid value without error indication. The decoding functions are gamma functions whose coefficients are specified by the Gamma property. The transformation matrix is defined by the Matrix property.

The WhitePoint and BlackPoint control the overall effect of the CIE-based gamut mapping function. Typically, the colors specified by WhitePoint and BlackPoint are mapped to the nearly lightest and nearly darkest achromatic colors that the output device is capable of rendering in a way that preserves color appearance and visual contrast.

WhitePoint is assumed to represent the diffuse achromatic highlight, not a specular highlight. Specular highlights, achromatic or otherwise, are often reproduced lighter than the diffuse highlight. X and Z must be positive, and Y must be equal to 1.0.

BlackPoint is assumed to represent the diffuse achromatic shadow; its value is typically limited by the dynamic range of the input device. All three of black point numbers (X, Y, and Z) must be non-negative.

Gamma specifying the gamma for the red, green, and blue (A, B, and C) components of the color space.

The following example shows an example of a CsCalRGB color space for the CCIR XA/11– recommended D65 white point with 1.8 gammas and Sony Trinitron phosphor chromaticities.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float A = 1;
    float B = 0.5f;
    float C = 0;
    float[] color = { A, B, C };
    CIEPoint whitePoint = new CIEPoint(0.9505f, 1, 1.0890f);
    CIEGamma gamma = new CIEGamma(1.8f, 1.8f, 1.8f);
    CIEMatrix matrix = new CIEMatrix(0.4497f, 0.2446f, 0.0252f, 0.3163f, 0.6720f, 0.1412f, 0.1845f, 0.0833f, 0.9227f);
    var colorSpace = new CsCalRGB(doc, gamma, matrix, whitePoint);

    pageObject.SetFillColor(colorSpace, color);
}

Lab Color Space

The CsLab color space is a CIE-based ABC color space with two transformation stages. In this type of space, A, B, and C represent the L*, a*, and b* components of a CIE 1976 L*a*b* space. The range of the first (L*) component is always 0 to 100; the ranges of the second and third (a* and b*) components are defined by the aMin, aMax, bMin, and bMax properties.

The below example example defines the CIE 1976 L*a*b* space with the CCIR XA/11–recommended D65 white point. The a* and b* components, although theoretically unbounded, are defined to lie in the useful range −128 to +127.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float L = 50;
    float a = -20;
    float b = 40;
    float[] color = { L, a, b };
    CIEPoint whitePoint = new CIEPoint(0.9505f, 1, 1.0890f);
    float aMin = -128;
    float aMax = 127;
    float bMin = -128;
    float bMax = 127;
    var colorSpace = new CsLab(doc, aMin, aMax, bMin, bMax, whitePoint);

    pageObject.SetFillColor(colorSpace, color);
}

ICCBased Color Space

CsICCBased color space is based on a cross-platform color profile as defined by the International Color Consortium (ICC). Unlike the CsCalGray, CsCalRGB, and CsLab color spaces, which are characterized by WhitePoint, BlackPoint, Gamma, etc , the CsICCBased color space is characterized by a sequence of bytes in a standard format. Details of the profile format can be found in the ICC specification.

Teh following example shows an CsICCBased color space for a typical three-component RGB space.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    int R = 127;
    int G = 255;
    int B = 15;
    float[] color = { (float)R / 255, (float)G / 255, (float)B / 255 };
    int nComponents = 3;
    var alternateCs = new CsDeviceRGB();
    byte[] iccProfile = { };
    var colorSpace = new CsICCBased(doc, nComponents, iccProfile, alternateCs);

    pageObject.SetFillColor(colorSpace, color);
}

An alternate color space is used in case the one specified in the iccProfile is not supported. The alternate space may be any valid color space (except a CsPattern color space) that has the number of components specified by nComponents. If this entry is omitted and the application does not understand the ICC profile data, the color space used is CsDeviceGray, CsDeviceRGB, or CsDeviceCMYK, depending on whether the value of nComponents is 1, 3, or 4, respectively.

Note Note

There is no conversion of source color values, such as a tint transformation, when using the alternate color space. Color values within the range of the CsICCBased color space might not be within the range of the alternate color space. In this case, the nearest values within the range of the alternate space are substituted.

Special Color Spaces

Special color spaces add features or properties to an underlying color space. There are four special color space families: CsIndexed, CsSeparation, CsDeviceN, and CsPattern.

Indexed Color Spaces

An CsIndexed color space allows a PDF content stream to use small integers as indices into a color map or color table of arbitrary colors in some other space. A PDF consumer application treats each sample value as an index into the color table and uses the color value it finds there. This technique can considerably reduce the amount of data required to represent a sampled image—for example, by using 8-bit index values as samples instead of 24-bit RGB color values.

This example illustrates the specification of an CsIndexed color space that maps 8-bit index values to three-component color values (Red, White, and Blue) in the CsDeviceRGB color space and set the specific color index(2) within that space for stroking operations.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float[] color = { 2 };
    var baseCs = new CsDeviceRGB();
    byte[] colorTable = { 255, 0, 0, 255, 255, 255, 0, 0, 255 };
    var colorSpace = new CsIndexed(doc, baseCs, colorTable);

    pageObject.SetStrokeColor(colorSpace, color);
}

baseCs identifies the base color space in which the values in the color table are to be interpreted. It can be any device or CIE-based color space or CsSeparation or CsDeviceN space, but not a CsPattern space or another CsIndexed space. For example, if the base color space is CsDeviceRGB, the values in the colorTable are to be interpreted as red, green, and blue components; if the base color space is a CIE-based ABC space such as a CsCalRGB or CsLab space, the values are to be interpreted as A, B, and C components.

The HiVal property is an integer that specifies the maximum valid index value. In other words, the color table is to be indexed by integers in the range 0 to HiVal. hival can be no greater than 255, which is the integer required to index a table with 8-bit index values.

The colorTable data must be m × (HiVal + 1) bytes long, where m is the number of color components in the baseCs. Each byte is an unsigned integer in the range 0 to 255 that is scaled to the range of the corresponding color component in the base color space; that is, 0 corresponds to the minimum value in the range for that component, and 255 corresponds to the maximum.

The color components for each entry in the colorTable appear consecutively. For example, if the base color space is CsDeviceRGB and the indexed color space contains three colors, the order of bytes in the string or stream is R0, G0, B0, R1, G1, B1, R2, G2, B2 where letters denote the color component and numeric subscripts denote the table entry.

Separation Color Space

Color output devices produce full color by combining primary or process colorants in varying amounts. On an additive color device such as a display, the primary colorants consist of red, green, and blue phosphors; on a subtractive device such as a printer, they typically consist of cyan, magenta, yellow, and sometimes black inks. In addition, some devices can apply special colorants, often called spot colorants, to produce effects that cannot be achieved with the standard process colorants alone. Examples include metallic and fluorescent colors and special textures.

When printing a page, most devices produce a single composite page on which all process colorants (and spot colorants, if any) are combined. However, some devices, such as imagesetters, produce a separate, monochromatic rendition of the page, called a separation, for each colorant. When the separations are later combined—on a printing press, for example—and the proper inks or other colorants are applied to them, the result is a full-color page.

A CsSeparation color space provides a means for specifying the use of additional colorants or for isolating the control of individual color components of a device color space for a subtractive device. When such a space is used, the color is a single-component value, called a tint, that controls the application of the given colorant or color components only.

As mentioned above, a color value in a CsSeparation color space consists of a single tint component in the range 0.0 to 1.0. The value 0.0 represents the minimum amount of colorant that can be applied; 1.0 represents the maximum. Tints are always treated as subtractive colors, even if the device produces output for the designated component by an additive method. Thus, a tint value of 0.0 denotes the lightest color that can be achieved with the given colorant, and 1.0 is the darkest.

The Colorant property specify the name of the colorant that this CsSeparation color space is intended to represent (or one of the special names All or None). Such colorant names are arbitrary, and there can be any number of them, subject to implementation limits.

The special colorant name All refers collectively to all colorants available on an output device, including those for the standard process colorants. When a CsSeparation space with this colorant name is the current color space, painting operators apply tint values to all available colorants at once. This is useful for purposes such as painting registration targets in the same place on every separation. Such marks are typically painted as the last step in composing a page to ensure that they are not overwritten by subsequent painting operations.

The special colorant name None never produces any visible output. Painting operations in a CsSeparation space with this colorant name have no effect on the current page.

All devices support CsSeparation color spaces with the colorant names All and None, even if they do not support any others. Separation spaces with either of these colorant names ignore the AlternateCS and TintTransform properties, although valid values must still be provided.

If the colorant name associated with a CsSeparation color space does not correspond to a colorant available on the device, the application arranges for subsequent painting operations to be performed in an alternate color space. The intended colors can be approximated by colors in a device or CIE-based color space, which are then rendered with the usual primary or process colorants:

  • AlternateCS identifies the alternate color space, which can be any device or CIE-based color space but not another special color space (CsPattern, CsIndexed, CsSeparation, or CsDeviceN).

  • During subsequent painting operations, an application calls the function to transform a tint value into color component values in the alternate color space. The TintFunction is called with the tint value and must return the corresponding color component values. That is, the number of components and the interpretation of their values depend on the alternate color space.

The following example illustrates the specification of a CsSeparation color space that is intended to produce a color named LogoGreen. If the output device has no colorant corresponding to this color, CsDeviceCMYK is used as the alternate color space, and the tint transformation function maps tint values linearly into shades of a CMYK color value approximating the LogoGreen color.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float[] color = { 0.5f };
    var alternateCs = new CsDeviceCMYK();
    var domain = new float[] { 0, 1 };
    var range = new float[] { 0, 1, 0, 1, 0, 1, 0, 1 };
    int numOfInputs = 1;
    int numOfOutputs = 4;
    string postScriptProgram = @"
    {
        dup 0.84 mul
        exch 0.00 exch dup 0.44 mul 
        exch 0.21 mul 
    }";
    var function = new PdfFuncPostScript(numOfInputs, numOfOutputs, domain, range, postScriptProgram);
    var colorSpace = new CsSeparation(doc, "LogoGreen", alternateCs, function);

    pageObject.SetStrokeColor(colorSpace, color);
}

DeviceN Color Space

CsDeviceN color spaces can contain an arbitrary number of color components. They provide greater flexibility than is possible with standard device color spaces such as CsDeviceCMYK or with individual CsSeparation color spaces. For example, it is possible to create a CsDeviceN color space consisting of only the cyan, magenta, and yellow color components, with the black component excluded.

CsDeviceN color spaces are used in applications such as these:

  • High-fidelity color is the use of more than the standard CMYK process colorants to produce an extended gamut, or range of colors. A popular example is the PANTONE Hexachrome system, which uses six colorants: the usual cyan, magenta, yellow, and black, plus orange and green.

  • Multitone color systems use a single-component image to specify multiple color components. In a duotone, for example, a single-component image can be used to specify both the black component and a spot color component. The tone reproduction is generally different for the different components. For example, the black component might be painted with the exact sample data from the single-component image; the spot color component might be generated as a nonlinear function of the image data in a manner that emphasizes the shadows.

CsDeviceN was designed to represent color spaces containing multiple components that correspond to colorants of some target device. As with CsSeparation color spaces, PDF consumer applications must be able to approximate the colorants if they are not available on the current output device, such as a display. To accomplish this, the color space definition provides a tint transformation function that can be used to convert all the components to an alternate color space.

CsDeviceN color spaces are defined in a similar way to CsSeparation color spaces—in fact, a CsSeparation color space can be defined as a CsDeviceN color space with only one component.

The Colorants property is an array of names specifying the individual color components. The length of the array determines the number of components in the CsDeviceN color space. The component names must all be different from one another, except for the name None. The special name All, used by CsSeparation color spaces, is not allowed.

The color component name None, indicates that the corresponding color component is never painted on the page, as in a CsSeparation color space for the None colorant. However, when the CsDeviceN color space reverts to its alternate color space, those components are passed to the tint transformation function, which can use them as desired.

Color values are tint components in the range 0.0 to 1.0. 0.0 always represents the minimum amount of colorant; 1.0 represents the maximum. Tints are always treated as subtractive colors, even if the device produces output for the designated component by an additive method. Thus, a tint value of 0.0 denotes the lightest color that can be achieved with the given colorant, and 1.0 the darkest. (This convention is the same one as for CsDeviceCMYK color components but opposite to the one for CsDeviceGray and CsDeviceRGB.)

The AlternateCS can be any device or CIE-based color space but not another special color space (CsPattern, CsIndexed, CsSeparation, or CsDeviceN). If any of the component names in the color space do not correspond to a colorant available on the device, the PDF consumer application can perform subsequent painting operations in the alternate color space specified by this parameter.

The TintTransform specifies a function that is used to transform the tint values into the alternate color space. It is called with n tint values and returns m color component values, where n is the number of components needed to specify a color in the DeviceN color space and m is the number required by the alternate color space.

The following example illustrate interesting and useful special case of the use of CsIndexed and CsDeviceN color spaces in combination to produce multitone colors. an CsIndexed color space maps index values in the range 0 to 255 to a duotone CsDeviceN space in cyan and black. In effect, the index values are treated as if they were tints of the duotone space, which are then mapped into tints of the two underlying colorants. Only the beginning of the lookup table string for the Indexed color space is shown; the full table would contain 256 twobyte entries, each specifying a tint value for cyan and black, for a total of 512 bytes. If the alternate color space of the DeviceN space is selected, the tint transformation function (object 15 in the example) maps the two tint components for cyan and black to the four components for a DeviceCMYK color space by supplying zero values for the other two components.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    var pageObject = page.PageObjects[0];

    float[] color = { 1 };

    int numOfInputs = 2;
    int numOfOutputs = 4;
    float[] domain = { 0, 1 };
    float[] range = { 0, 1, 0, 1, 0, 1, 0, 1 };
    var tintTransform = new PdfFuncPostScript(numOfInputs, numOfOutputs, domain, range, "{0 0 3 −1 roll}");
    string[] colorants = { "Cayan", "Black" };
    var deviceN = new CsDeviceN(doc, colorants, PdfColorSpace.DeviceCMYK(), tintTransform);
    byte[] colorTable = { 102, 5, 17, 15, 107, 255 };
    var indexed = new CsIndexed(doc, deviceN, colorTable);

    pageObject.SetStrokeColor(indexed, color);
}

Pattern Color Space

A CsPattern color space enables a PDF content stream to paint an area with a pattern rather than a single color. The pattern may be either a tiling pattern or a shading pattern. Section, Patterns discusses patterns in detail.

How to get the color space of a particular page object.
C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    var page = doc.Pages[0];
    foreach (var obj in page.PageObjects)
    {
        obj.GetFillColor(out PdfColorSpace cs,  out _, out float[] color);

        if (cs is CsDeviceGray)
        {
            int nComponents = cs.CountComponents; // 1
            float[] defColor = cs.DefaultColor; // An array of componentns [ 0 ]
        }
        else if (cs is CsDeviceRGB)
        {
            int nComponents = cs.CountComponents; // 3
            float[] defColor = cs.DefaultColor; // An array of componentns [ 0 0 0]
        }
        else if (cs is CsDeviceCMYK)
        {
            int nComponents = cs.CountComponents; // 4
            float[] defColor = cs.DefaultColor; // An array of componentns [ 0 0 0 1]
        }
        else if (cs is CsCalRGB)
        {
            CIEGamma gamma = (cs as CsCalRGB).Gamma;
            CIEPoint white = (cs as CsCalRGB).WhitePoint;
            CIEPoint black = (cs as CsCalRGB).BlackPoint;
        }

    }
}
See Also