Technical Article

Soft Masks and Transparency Flattening in Delphi

Draw a hero photo through a gradient soft mask, then draw the caption and the page footer, and the footer comes out faded too: half-transparent where the mask is grey, gone entirely where the mask is black. The mask is doing exactly what the specification says. ISO 32000-1 §8.4 makes the soft mask a graphics state parameter, in the same family as line width and fill colour, so once a content stream selects it with gs it governs every painting operator that follows until another gs replaces it or a Q restores the state saved before it

That one rule accounts for most of what goes wrong when you author masks by hand. The opposite request is just as common: a print shop, an older RIP or a PDF/X-1a workflow that wants no live transparency anywhere in the file, which means turning every fade, blend mode and mask into plain opaque pixels and then proving the file is clean enough to carry a PDF 1.3 header

Building a luminosity mask from a captured page

PDF Library for Delphi creates a form soft mask with NewSoftMaskGraphicsState, which takes a captured page as the mask content and returns a graphics state ID that you select with SetGraphicsState. The mask type is either PDF_SOFT_MASK_LUMINOSITY or PDF_SOFT_MASK_ALPHA. A luminosity mask reads the brightness of the mask content, so white is fully opaque and black fully transparent; an alpha mask reads the coverage of whatever was painted, regardless of its colour. Designers almost always hand over a greyscale gradient, which is why luminosity is the type you will reach for most often

The mask content comes from CapturePage, which turns one page of the document into a reusable form and removes that page from the page list. Two consequences follow. The document must have more than one page, or the call returns 0. And every page after the captured one moves up by one, so capture first and work out target page numbers afterwards

When the graphics state is built, the captured content is marked as an isolated transparency group in DeviceRGB (ISO 32000-1 §11.6.6), which gives the mask a known colour space to be evaluated in. The backdrop must match it: three components, each between 0 and 1, written as PDF array text such as '[0 0 0]'. A bare '0 0 0' is not an array, and NewSoftMaskGraphicsState returns 0 for it. The transfer function accepts /Identity or the text of a PDF function object, which lets you reshape the fade curve without repainting the artwork

Diagram comparing luminosity and alpha soft masks feeding NewSoftMaskGraphicsState, with a reminder that the graphics state persists until it is cleared
Luminosity masks read brightness while alpha masks read coverage, and NewSoftMaskGraphicsState wraps either one in a persistent graphics state
uses
  PDFlibrary;

var
  Lib: TPDFlib;
  MaskCapture, MaskGS, PhotoID: Integer;
begin
  Lib := TPDFlib.Create;
  try
    if Lib.LoadFromFile('brochure.pdf', '') <> 1 then
      Exit;

    // Page 4 holds only a white-to-black gradient painted as a mask;
    // CapturePage takes it out of the page list, later pages shift up
    MaskCapture := Lib.CapturePage(4);
    if MaskCapture = 0 then
      Exit;

    // Backdrop is PDF array text with three components for the RGB group
    MaskGS := Lib.NewSoftMaskGraphicsState(MaskCapture,
      PDF_SOFT_MASK_LUMINOSITY, '[0 0 0]', '/Identity');
    if MaskGS = 0 then
      Exit;

    Lib.SelectPage(1);
    PhotoID := Lib.AddImageFromFile('hero.jpg', 0);

    Lib.SaveState;                       // q
    Lib.SetGraphicsState(MaskGS);
    Lib.SelectImage(PhotoID);
    Lib.DrawImage(40, 700, 515, 260);    // fades out under the mask
    Lib.LoadState;                       // Q: the mask ends here

    Lib.SaveToFile('brochure-masked.pdf');
  finally
    Lib.Free;
  end;
end;

Identical requests are folded together. The same captured form, mask type, backdrop text and transfer text give back the same graphics state object, so a catalogue that masks two hundred product shots with one gradient writes a single ExtGState rather than two hundred

Ending the mask, and the call that wipes it early

There are two ways to stop a mask, and we prefer the bracket. SaveState and LoadState emit q and Q, and because the soft mask lives in the graphics state, Q restores whatever was in force beforehand, including no mask at all. The alternative is to select a second state built with NewSoftMaskGraphicsState(0, PDF_SOFT_MASK_NONE, '', ''), which writes /SMask /None. That works, but it adds another ExtGState carrying a transparency key, and it resets the mask even when an outer scope set one deliberately. Brackets nest; a reset does not

The trap works the other way round as well. Constant opacity in this library is also an ExtGState, and the one that SetTransparency and SetTransparencyEx select includes /SMask /None so that a fresh opacity setting always starts from a known state. Call SetTransparency after selecting a mask and the mask is gone before the next draw. The fix is ordering. The mask state carries no /ca entry, so it leaves constant opacity alone

// Mask is cleared here: the opacity state carries /SMask /None
Lib.SetGraphicsState(MaskGS);
Lib.SetTransparency(30);
Lib.DrawImage(40, 700, 515, 260);

// Both apply: 30 percent transparent, then faded by the gradient
Lib.SaveState;
Lib.SetTransparency(30);
Lib.SetGraphicsState(MaskGS);
Lib.DrawImage(40, 700, 515, 260);
Lib.LoadState;

A related default catches out people who build masks smaller than the masked object. For a luminosity mask the backdrop decides what happens outside the mask content, and a black backdrop means everything the gradient does not cover is hidden. Pass '[1 1 1]' when the area outside the gradient should stay fully visible

Image soft masks and the Matte entry

When the mask belongs to one image rather than to a region of the page, SetImageSoftMaskEx attaches a mask image directly to a target image. The two images must have the same pixel width and height, the mask is normalised to DeviceGray whatever colour space it arrived in, and the call returns the target image ID on success or 0 on refusal. It also selects the target image, so the next DrawImage paints it

The third parameter writes the optional /Matte array into the mask image (ISO 32000-1 §11.6.5.3). Matte tells a consumer that the colour samples were pre-multiplied against that colour, so it can divide the matte back out before compositing. Leave it off for pre-multiplied artwork and every soft edge picks up a dark fringe, because the consumer blends colours that were already blended once. Supply one value per component of the target image's colour space, between 1 and 4 values in the range 0 to 1, or pass an empty string to omit the entry

Diagram showing a missing Matte entry producing dark halos while a declared Matte composites cleanly, beside PDF 1.4 and PDF/A and PDF/X guardrails
A declared /Matte prevents the dark halo of pre-multiplied artwork, while PDF/A-1 and PDF/X-1 files are refused before any object changes
var
  ArtID, AlphaID: Integer;
...
  ArtID := Lib.AddImageFromFile('badge-color.png', 0);   // RGB, pre-multiplied on white
  AlphaID := Lib.AddImageFromFile('badge-alpha.png', 0); // coverage, same pixel size

  // One Matte value per RGB component of the target image
  if Lib.SetImageSoftMaskEx(ArtID, AlphaID, '[1 1 1]') = 0 then
    raise Exception.Create('Soft mask not attached: check sizes and PDF/A or PDF/X mode');

  Lib.DrawImage(72, 200, 120, 120);

Both mask calls check the conformance mode before touching any object. PDF/A-1 forbids transparency outright (ISO 19005-1 §6.4), and PDF/X-1a and PDF/X-3 do likewise, so with one of those modes active SetImageSoftMaskEx and NewSoftMaskGraphicsState return 0 and leave the document as it was. Soft masks first appeared in PDF 1.4, and a successful call raises the document version to 1.4 if it was lower. A 1.3 header on a file with soft masks would simply be untrue

What FlattenTransparency does to each page

FlattenTransparency is deliberately literal. Each page in the requested range is rendered at the DPI you choose against an opaque background colour, the page content and resources are discarded, and a single image of the rendered page takes their place. Because the renderer has already produced the final composited result, that one step covers transparency groups, blend modes, soft masks, patterns and nested forms together, with no per-construct approximation that could get one of them wrong. Pages are processed one at a time, so peak raster memory is one page at the chosen resolution

Pipeline diagram of FlattenTransparency rendering each requested page at 300 DPI on an opaque background and saving a flat press-ready PDF 1.3 file
Each requested page renders once at the chosen DPI and returns as a single opaque image saved into a truthful PDF 1.3 file

The parameters are tight on purpose. DPI must fall between 36 and 1200, an empty page range means every page, and an option bit the method does not recognise makes it return 0 without changing anything. The return value counts the pages that were actually replaced, which is the number to compare against the range you asked for

Rotated pages get the treatment a naive flattener skips. For a page with /Rotate 90 or 270, the rendered image is already upright, so the method writes the visual width and height back as the new page size and removes /Rotate; leaving it in place would make a viewer turn the finished image a second time. /UserUnit (PDF 1.6) is folded into the effective DPI and the new page dimensions, then removed. BleedBox, TrimBox, ArtBox and BoxColorInfo are removed as well, and we think that is the right call: a TrimBox describing the old geometry on a page whose size has changed is worse than no TrimBox at all

Annotations and form fields are flattened into the page image by default, and the interactive objects are deleted, which is what a print deliverable wants. Pass PDF_FLATTEN_TRANSPARENCY_KEEP_ANNOTATIONS to keep them live instead. In that mode the renderer skips annotation appearances whilst drawing the page, so a stamp or a filled field is not painted once into the image and then again by the viewer on top of it

The trade-off is equally literal. The output is an image, so text is no longer selectable or searchable and vector edges are resampled at the chosen resolution. Keep the transparent original and flatten a copy; 300 DPI is the usual starting point for offset print, and fine type on a coated stock may justify more

Why does the PDF 1.3 save still fail after flattening?

Flattening replaces page content, but the 1.3 check does not look at pages. The save-time version gate walks every indirect object in the file, reachable or not, and any ExtGState with /SMask, /CA, /ca or /BM, any transparency group and any image /SMask counts as a PDF 1.4 feature. That is stricter than it looks, and rightly so. An orphaned soft mask left over from an earlier edit is still in the file, and a preflight tool that walks objects rather than pages will find it

That is why PDF_FLATTEN_TRANSPARENCY_DEFAULT includes PDF_FLATTEN_TRANSPARENCY_GARBAGE_COLLECT. Once the pages are replaced, a mark-and-sweep pass releases every object that is no longer reachable, including the masks, groups and graphics states the old content used. Passing 0 as the options skips the sweep, and the leftover objects will then block the 1.3 save. The price of the sweep is that image, capture and graphics state IDs you obtained before flattening may now point at released objects. Re-acquire anything you still need, such as the IDs from AddImageFromFile or CapturePage, before editing any further

Flattening does not lower the header by itself. Pin the target with LockSaveVersion('1.3'), which also stops later calls from raising the version behind your back, and then check the save. A refused save returns 0 with LastErrorCode set to PDFLIB_ERROR_VERSION_COMPLIANCE (602), and GetInformation(311) and GetInformation(312) report the version required and the feature that requires it

var
  Flattened: Integer;
...
  if Lib.LoadFromFile('brochure-masked.pdf', '') <> 1 then
    Exit;

  Flattened := Lib.FlattenTransparency('', 300, $FFFFFF,
    PDF_FLATTEN_TRANSPARENCY_DEFAULT);
  if Flattened <> Lib.PageCount then
    Exit;  // at least one page was not replaced and still has live content

  // IDs obtained before this point may be stale after the sweep
  Lib.LockSaveVersion('1.3');
  if Lib.SaveToFile('press-ready.pdf') <> 1 then
    if Lib.LastErrorCode = PDFLIB_ERROR_VERSION_COMPLIANCE then
      Writeln('Needs PDF ', Lib.GetInformation(311),
        ' for ', Lib.GetInformation(312));

The feature name is worth reading even when you are sure the transparency has gone. A source file can carry other post-1.3 constructs, such as AES encryption or object streams, and the gate reports whichever one it meets first. If 312 names a crypt filter, the fix lies in the encryption settings, and no amount of re-flattening will change the answer

Two related articles cover the cases where rasterising is the wrong tool. When an effect can be expressed as a gradient rather than a mask, vector graphics, shaders and gradients keeps it as vector artwork. When the real requirement is colour rather than transparency, recolouring a document to another colour space keeps text live where flattening would not, and the PDF/X side of a print job is covered in PDF/X-1a, X-3 and X-4 print conformance

Mask authoring, flattening and the renderer that produces the flattened pages all belong to a single Delphi, C++Builder and Free Pascal library; downloads and the full API list are on the PDF Library for Delphi product page