How do I flatten an annotation into the page, but also make it part of an OCG layer?

97 views
Skip to first unread message

Ryan

unread,
Jan 31, 2018, 9:20:48 PM1/31/18
to pdfne...@googlegroups.com
Question:

I want to make some of our annotations no longer selectable or editable, except as part of an OCG layer. Is this possible?

Answer:

Yes, this is possible, by taking advantage of our Annot.Flatten API call, it is easy to then mark the flattened annotation as part of an OCG layer. This will remove the annotation, but its visual representation is still on the page as an OCG layer.

The code is below, but I have also attached it as a modification of our PDFLayersTest sample code.

// A utility function used to add new Content Groups (Layers) to the document.
static Group CreateLayer(PDFDoc doc, String layer_name)
{
   
Group grp = Group.Create(doc, layer_name);
   
Config cfg = doc.GetOCGConfig();
   
if (cfg == null)
   
{
        cfg
= Config.Create(doc, true);
        cfg
.SetName("Default");
   
}


   
// Add the new OCG to the list of layers that should appear in PDF viewer GUI.
   
Obj layer_order_array = cfg.GetOrder();
   
if (layer_order_array == null)
   
{
        layer_order_array
= doc.CreateIndirectArray();
        cfg
.SetOrder(layer_order_array);
   
}
    layer_order_array
.PushBack(grp.GetSDFObj());


   
return grp;
}

Now the main code.

PageIterator itr = doc.GetPageIterator();
for (; itr.HasNext(); itr.Next())
{
   
Page page = itr.Current();
   
Obj res_dict = page.GetResourceDict();
   
if(res_dict == null) res_dict = page.GetSDFObj().PutDict("Resources");
   
Obj xobjects = res_dict.FindObj("XObject");
   
if(xobjects == null) xobjects = res_dict.PutDict("XObject");


   
// Iterate through all Form XObjects associated with this page.
   
HashSet<string> existingFormXobjects = new HashSet<string>();
   
for (DictIterator ditr = xobjects.GetDictIterator(); ditr.HasNext(); ditr.Next())
   
{
        existingFormXobjects
.Add(ditr.Key().GetName());
   
}


   
for (int i = 0; i < page.GetNumAnnots();)
   
{
       
Annot annot = page.GetAnnot(i);
       
if (annot.IsValid() == false)
       
{
            page
.AnnotRemove(i);
       
}
       
else
       
{
           
// Flatten removes the annotation from the page
           
// Creates a Form XObject of the annotation
           
// And adds the Form Xobject to the page content stream
            annot
.Flatten(page);
       
}
   
}


   
// Now we just run through all the new Xobjects, and add them to the OCG layer
   
for (DictIterator ditr = xobjects.GetDictIterator(); ditr.HasNext(); ditr.Next())
   
{
       
if (!existingFormXobjects.Contains(ditr.Key().GetName()))
       
{
           
Obj xobject = ditr.Value();
            xobject
.Put("OC", annotation_layer.GetSDFObj());
       
}
   
}
}



PDFLayersTest.cs
Reply all
Reply to author
Forward
0 new messages