How to use layers in PDF content stream?

Q: I need to use layers in my generated PDFs.
I have looked at the PDFLayers example (
samplecode.html#PDFLayers), but rewriting the entire application to
use XObjects is a large task to do.

I've found this post in the knowledge database but I'm not sure how to
use it.

Can you modify the layers example (
samplecode/PDFLayers.cpp), to use the BDC and EMC commands in the
content stream?

A: The code would be along the lines of PDFLayers sample except that
instead of creating forms for each layer you would write all content
directly to the main content stream. For example:

PDFDoc doc = new PDFDoc();
Group layer = CreateLayer(doc, "My Layer");
// Start a layer
int layer_id = 0;

// Write /OC /id_num BDC marked content block...
writer.WriteString(" /OC /id_");
writer.WriteString("BDC ");

Element element = builder.CreateImage(img, ...);
writer.WriteString(" EMC "); // Finish marked content block

// Start a new layer ... same as the above


// Now hook layer IDs to OCG dictionaries via Properties dictionary:

Obj res = page.GetResources();
if (res == null) res = page.GetSDFObj().PutDict("Resources");
Obj props = res.FindObj("Properties");
if (props == null) props = res.PutDict("Properties");

props.Put("id_0", layer.GetSDFObj());
... same for other layers ...