RemoveLayers.cs
//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Pdf.Layers;
using GrapeCity.Documents.Pdf.Annotations;
using GrapeCity.Documents.Pdf.Graphics;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Drawing;

namespace DsPdfWeb.Demos
{
    // This example shows how to remove layers and their content
    // from a PDF with multiple layers.
    // The input PDF for this sample was created by HousePlanAllLayers.
    public class RemoveLayers
    {
        public int CreatePDF(Stream stream)
        {
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "house-plan-all-layers.pdf"));
            var doc = new GcPdfDocument();
            doc.Load(fs);

            // Remove all layers except the last one with their content:
            var layers = doc.OptionalContent.Groups.Take(doc.OptionalContent.Groups.Count - 1).ToArray();
            doc.OptionalContent.RemoveLayers(true, layers);
            // Remove the single remaining layer, leaving its content in place:
            doc.OptionalContent.RemoveLayer(doc.OptionalContent.Groups[0]);

            // Save the PDF:
            doc.Save(stream);
            return doc.Pages.Count;
        }
    }
}