Skip to main content
Skip table of contents

How to change the order of Optional Content Groups?

I have a PDF file with a hierarchy of layers. How do I modify this data in order to copy it into a new file?

I have a PDF file with a hierarchy of layers (aka OCG). Using the following code snippet

C#
var ocProps = reader.Catalog.GetAsDict(PdfName.OCPROPERTIES);
var occd = ocProps.GetAsDict(PdfName.D);
var order = occd.GetAsArray(PdfName.ORDER);

I can query the current order from the source file. But I have no idea how to modify this data in order to copy it into a new file with the following snippet.

C#
var reader = new PdfReader(input);
var document = new Document(reader.GetPageSizeWithRotation(1));
var pdfCopyProvider = new PdfCopy(document,
    new System.IO.FileStream(output, System.IO.FileMode.Create));
document.Open();
// TBD do OCG modification ...
var importedPage = pdfCopyProvider.GetImportedPage(reader, 1);
pdfCopyProvider.AddPage(importedPage);
document.Close();

Nonetheless, the OCG information is copied to the new PDF file by default.

Any hint on this is welcome.

Posted on StackOverflow on Apr 24, 2014 by Holger

You're already very close to the solution. See the ChangeOCGOrder example (Java/.NET) to find out how to change ocg.pdf into ocg_reordered.pdf.

In iText 7 your code will look like this:

JAVA
public void manipulatePdf(String src, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    PdfCatalog catalog = pdfDoc.getCatalog();
    PdfDictionary ocProps = (PdfDictionary) catalog.getPdfObject().get(PdfName.OCProperties);
    PdfDictionary occd = (PdfDictionary) ocProps.get(PdfName.D);
    PdfArray order = occd.getAsArray(PdfName.Order);
    PdfObject nestedLayers = order.get(0);
    PdfObject nestedLayerArray = order.get(1);
    PdfObject groupedLayers = order.get(2);
    PdfObject radioGroup = order.get(3);
    order.set(0, radioGroup);
    order.set(1, nestedLayers);
    order.set(2, nestedLayerArray);
    order.set(3, groupedLayers);
    pdfDoc.close();
}

In my example, the order array contains 4 elements. I get these four elements, and I change the order of the entries in the original array.

Click How to change the order of Optional Content Groups? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.