PDFsharp & MigraDoc Foundation
http://forum.pdfsharp.com/

Does PDFsharp preserve Optional Content Groups (i.e. layers)
http://forum.pdfsharp.com/viewtopic.php?f=2&t=3983
Page 1 of 1

Author:  SSteve [ Sat Jun 08, 2019 1:20 am ]
Post subject:  Does PDFsharp preserve Optional Content Groups (i.e. layers)

If I load a PDF containing graphics objects on three layers (which are called Optional Content Groups in the PDF reference), does PDFsharp preserve those layers? Or do they all get merged into the page's Contents property?

In the debugger I can see the /OCProperties key in document._trailer.Root.Elements.Keys. The associated value is a dictionary. One of the keys in that dictionary is /OCGs whose value is an array with three references corresponding to the three layers in the document. But I'm not sure how to get at those references.

I tried to attach the PDF I'm testing with, but it's 429kb so it's too large.

Thanks.

Author:  SSteve [ Fri Jun 14, 2019 6:55 pm ]
Post subject:  Re: Does PDFsharp preserve Optional Content Groups (i.e. lay

Upon further study I see that the three layers in the page's content stream are delineated by marked-content operators BDC and EMC with a marked-content tag of /OC. Now I just need to figure out how to get to the layer names.

Author:  SSteve [ Tue Jun 18, 2019 12:16 am ]
Post subject:  Re: Does PDFsharp preserve Optional Content Groups (i.e. lay

I think I've got it figured out. I came up with this code to display the layer names and content stream of the first page of a document.

Code:
         var doc = PdfReader.Open(fileName);
         var page = doc.Pages[0];
         var resources = page.Elements.GetDictionary("/Resources");
         var properties = resources?.Elements.GetDictionary("/Properties");
         if (!(properties is null))
         {
            foreach (var property in properties)
            {
               if (property.Value is PdfReference propertyValue &&
                   propertyValue.Value is PdfDictionary propertyDict)
               {
                  // Write the key and name of the layer
                  var layerName = propertyDict.Elements.GetString("/Name");
                  Debug.WriteLine($"Key: {property.Key} Value: {layerName}");
               }
            }
         }   
         var contents = page.Contents;
         var elements = contents.Elements;
         foreach (var element in elements)
         {
            if (element is PdfReference reference && reference.Value is PdfContent content)
            {
               // Write the entire content stream
               Debug.WriteLine(content.Stream);
            }
         }

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/