HousePlanAllLayers.cs
//
// This code is part of GrapeCity Documents for PDF samples.
// Copyright (c) GrapeCity, 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 GcPdfWeb.Samples
{
    // This sample creates a multi-layer PDF document from a set of PDFs
    // each of which shows a certain part of an electrical plan of a house.
    // Each PDF is added as a separate layer. The resulting PDF provides
    // optional content that allows the user to selectively see parts of
    // the electrical wiring of a house (e.g. just the HVAC setup, or
    // just the outlets, etc.).
    // Note that this example is similar to HousePlanLayers, but unlike
    // that sample, here ALL content is added as layers (in HousePlanLayers,
    // the full electrical plan content does not belong to any layer).
    public class HousePlanAllLayers
    {
        public void CreatePDF(Stream stream)
        {
            // The list of PDF names' parts identifying their semantics:
            List<string> fnames = new List<string>()
            {
                "full_electrical_plan.pdf",
                "all_outlets.pdf",
                "data_plan_and_detectors.pdf",
                "HVAC_with_wiring.pdf",
                "lighting_plan.pdf",
                "lighting_plan_with_wiring.pdf",
                "security_system_plan.pdf",
            };
            // The common base name:
            var fbase = "how_to_read_electrical_plans_";
            // The directory containing the PDFs:
            var dir = Path.Combine("Resources", "PDFs");

            var doc = new GcPdfDocument();
            var page = doc.Pages.Add();
            var g = page.Graphics;
            var disposables = new List<IDisposable>();
            // Combine all PDFs into a single document as layers on the first page:
            for (int i = 0; i < fnames.Count; ++i)
            {
                var iname = fnames[i];
                var idoc = new GcPdfDocument();
                var ifs = File.OpenRead(Path.Combine(dir, fbase + iname));
                idoc.Load(ifs);
                disposables.Add(ifs);
                doc.OptionalContent.AddLayer(iname);
                doc.OptionalContent.SetLayerDefaultState(iname, false);
                g.BeginLayer(iname);
                g.DrawPdfPage(idoc.Pages[0], page.Bounds);
                g.EndLayer();
            }
            // Make the last layer visible by default:
            doc.OptionalContent.SetLayerDefaultState(fnames.Last(), true);

            // Save the PDF:
            doc.Save(stream);

            // Dispose file streams:
            disposables.ForEach(d_ => d_.Dispose());
        }
    }
}