Some test text!

Search
Hamburger Icon

Go / Guides / Extract layer

Extract layers from PDF in Go

To extract PDF layers or OCG (optional content group) from a document.

doc := NewPDFDoc(filename)
page = doc.GetPage(1)

init_cfg := doc.GetOCGConfig()
ctx := NewContext(init_cfg)

pdfdraw := NewPDFDraw()
pdfdraw.SetImageSize(1000, 1000)
pdfdraw.SetOCGContext(ctx)  // Render the page using the given OCG context.

// Disable drawing of content that is not optional (i.e. is not part of any layer).
ctx.SetNonOCDrawing(false)

// Now render each layer in the input document to a separate image.
ocgs := doc.GetOCGs()    // Get the array of all OCGs in the document.
if ocgs != nil{
    sz := ocgs.Size()
    i := int64(0)
    for i < sz{
        ocg := NewGroup(ocgs.GetAt(i))
        ctx.ResetStates(false)
        ctx.SetState(ocg, true)
        fname := "pdf_layers_" + ocg.GetName() + ".png"
        fmt.Println(fname)
        pdfdraw.Export(page, outputPath + fname)
        i = i + 1
    }
}

// Now draw content that is not part of any layer...
ctx.SetNonOCDrawing(true)
ctx.SetOCDrawMode(ContextE_NoOC)
pdfdraw.Export(page, outputPath + "pdf_layers_non_oc.png")

PDF layers (OCG)
Full sample code which demonstrates how to create, extract, render PDF layers.

Get the answers you need: Chat with us