// Copyright (C) 2003-2026, Foxit Software Inc..
// All Rights Reserved.
//
// http://www.foxitsoftware.com
//
// The following code is copyrighted and contains proprietary information and trade secrets of Foxit Software Inc..
// You cannot distribute any part of Foxit PDF SDK to any third party or general public,
// unless there is a separate license agreement with Foxit Software Inc. which explicitly grants you such rights.
//
// This file contains an example to demonstrate how to use Foxit PDF SDK to render all PDF layers of a PDF,
// and add layers in a PDF document.

using System;
using System.IO;

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;

namespace pdflayerCS
{
    class TestInfo
    {
        public string input_path = "../input_files/";
        public string output_path = "../output_files/pdflayer/";
    }
    class TextDoc
    {
        private FileStream mfile_stream;
        public TextDoc(string file_name, FileMode fill_mode)
        {
            //FileStream F = new FileStream(file_name, FileMode.Open, FileAccess.Read, FileShare.Read);
            mfile_stream = new FileStream(file_name, fill_mode);
        }
        ~TextDoc()
        {
            try
            {
                mfile_stream.Flush();
                mfile_stream.Close();
            }
            catch (System.ObjectDisposedException e)
            {
                string str = e.Message;
            }

        }
        public void Write(int count, string prefix, string contents)
        {
            string prefix_all = "";
            for (int i = 0; i < count; i++)
            {
                prefix_all = prefix_all + prefix;
            }
            contents = prefix_all + contents;

            byte[] byte_data = System.Text.Encoding.Default.GetBytes(contents);
            // Move file pointer to beginning of file.
            mfile_stream.Seek(0, SeekOrigin.End);
            mfile_stream.Write(byte_data, 0, byte_data.Length);
            mfile_stream.Flush();
        }
        public void Write(string contents)
        {
            byte[] byte_data = System.Text.Encoding.Default.GetBytes(contents);
            // Move file pointer to beginning of file.
            mfile_stream.Seek(0, SeekOrigin.End);
            mfile_stream.Write(byte_data, 0, byte_data.Length);
            mfile_stream.Flush();
        }
        public string Read()
        {
            int fs_Len = (int)mfile_stream.Length;
            byte[] byte_data = new byte[fs_Len];
            int r = mfile_stream.Read(byte_data, 0, byte_data.Length);
            string contents = System.Text.Encoding.UTF8.GetString(byte_data);
            return contents;
        }
    }

    class pdflayer
    {
        public static void RenderPageToImage(PDFPage page, LayerContext layer_content, string bitmap_file) 
        {
            if (!page.IsParsed())
            {
                // Parse page.
                page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.e_ParsePageNormal, null, false);
            }
            int width = (int)(page.GetWidth());
            int height = (int)(page.GetHeight());
            Matrix2D matrix = page.GetDisplayMatrix(0, 0, width, height, page.GetRotation());

            // Prepare a bitmap for rendering.
            using (foxit.common.Bitmap bitmap = new foxit.common.Bitmap(width, height, foxit.common.Bitmap.DIBFormat.e_DIBArgb, System.IntPtr.Zero, 0))
            {
                bitmap.FillRect(0xFFFFFFFF, null);
                // Render page.
                using (Renderer render = new Renderer(bitmap, false))
                {
                  if (!layer_content.IsEmpty())
                  {
                    render.SetLayerContext(layer_content);
                  }
                  render.StartRender(page, matrix, null);
                  using (foxit.common.Image image = new foxit.common.Image())
                  {
                      image.AddFrame(bitmap);
                      image.SaveAs(bitmap_file);
                  }            
                }
            }
        }

        public static string UsgaeCodeToString(LayerTree.UsageState state)
        {
            switch (state) {
                case LayerTree.UsageState.e_StateON:
                    return "ON";
                case LayerTree.UsageState.e_StateOFF:
                    return "OFF";
                case LayerTree.UsageState.e_StateUnchanged:
                    return "Unchanged";
                case LayerTree.UsageState.e_StateUndefined:
                    return "Undefined";
            }
            return "Unknown";
        }

        public static void GetAllLayerNodesInformation(LayerNode layer_node, int depth, ref TextDoc text_doc)
        {
            if (depth >= 0)
            {
                string node_name = layer_node.GetName();
                text_doc.Write(depth, "\t", node_name);
                if (layer_node.HasLayer()) 
                {
                    LayerTree.UsageState state = layer_node.GetViewUsage();
                    text_doc.Write(string.Format(" {0}\r\n", (state == LayerTree.UsageState.e_StateON) ? "[*]" : "[ ]"));
                    text_doc.Write(depth, "\t", string.Format("View usage state:\t{0}\r\n", UsgaeCodeToString(state)));
                    text_doc.Write(depth, "\t", string.Format("Export usage state:\t{0}\r\n", UsgaeCodeToString(layer_node.GetExportUsage())));

                    LayerPrintData print_data = layer_node.GetPrintUsage();
                    text_doc.Write(depth, "\t", string.Format("Print usage state:\t{0}, subtype: {1}\r\n", UsgaeCodeToString(print_data.print_state),print_data.subtype));

                    LayerZoomData zoom_data = layer_node.GetZoomUsage();
                    text_doc.Write(depth, "\t", string.Format("Zoom usage:\tmin_factor = {0:F4} max_factor = {1:F4}\r\n\r\n", zoom_data.min_factor,zoom_data.max_factor));
                } else {
                    text_doc.Write("\r\n");
                }
            }
            
            depth++;
            int count = layer_node.GetChildrenCount();
            for (int i = 0; i < count; i++) 
            {
                using (LayerNode child = layer_node.GetChild(i))
                {
                    GetAllLayerNodesInformation(child, depth, ref text_doc);
                }
            }
        }

        public static void SetAllLayerNodesInformation(LayerNode layer_node) 
        {
            if (layer_node.HasLayer()) 
            {
                layer_node.SetDefaultVisible(true);
                layer_node.SetExportUsage(LayerTree.UsageState.e_StateUndefined);
                layer_node.SetViewUsage(LayerTree.UsageState.e_StateOFF);
                LayerPrintData print_data = new LayerPrintData("subtype_print", LayerTree.UsageState.e_StateON);
                layer_node.SetPrintUsage(print_data);
                LayerZoomData zoom_data = new LayerZoomData(1, 10);
                layer_node.SetZoomUsage(zoom_data);
                string new_name = "[View_OFF_Print_ON_Export_Undefined]" + layer_node.GetName();
                layer_node.SetName(new_name);
            }
            int count = layer_node.GetChildrenCount();
            for (int i = 0; i < count; i++) 
            {
                using (LayerNode child = layer_node.GetChild(i))
                {
                    SetAllLayerNodesInformation(child);
                }
            }
        }

        public static void SetAllLayerNodesVisible(LayerContext context, LayerNode layer_node, bool visible)
        {
            if (layer_node.HasLayer())
            {
                context.SetVisible(layer_node, false);
            }
            int count = layer_node.GetChildrenCount();
            for (int i = 0; i < count; i++)
            {
                using(LayerNode child = layer_node.GetChild(i))
                {
                    SetAllLayerNodesVisible(context, child, visible);
                }
            }
        }

        public static void RenderAllLayerNodes(PDFDoc doc, LayerContext context, LayerNode layer_node, string pdf_name,string output_path) 
        {
            if (layer_node.HasLayer()) 
            {
                context.SetVisible(layer_node, true);
                int nCount = doc.GetPageCount();
                for (int i=0; i<nCount; i++) 
                {
                    using (PDFPage page = doc.GetPage(i))
                    {
                        string layer_name = layer_node.GetName();
                        layer_name = layer_name.Replace(":", string.Empty);
                        layer_name = layer_name.Replace(">", string.Empty);
                        layer_name = layer_name.Replace("<", string.Empty);
                        layer_name = layer_name.Replace("=", string.Empty);
                        string file_name = output_path + "page_" + i.ToString() + "_layer_node_" + layer_name + ".bmp";
                        RenderPageToImage(page, context, file_name);
                    }
                }
            }

            int count = layer_node.GetChildrenCount();
            for (int i = 0; i < count; i++) 
            {
                using (LayerNode child = layer_node.GetChild(i))
                {
                    RenderAllLayerNodes(doc, context, child, pdf_name,output_path);
                }
            }
            if (layer_node.HasLayer()) 
            {
                // The visibility of parent layer will affect the children layers,
                // so reset the visibility of parent layer after children have been rendered.
                context.SetVisible(layer_node, false);
            }
        }

        static void Main(string[] args)
        {
            string input_path ="../input_files/";
            string output_path = "../output_files/pdflayer/";
            System.IO.Directory.CreateDirectory(output_path);

            string sn = "Rew1vB0TqoMIxX444UcpScARWdhgJpsJfzmyMLR32a0+EgrCjp2NaQ==";
            string key = "8f3g1sFttW8NAgfSNv+BvaJWy4Pp8flcm7ncNDkdvCCO4JwUFbGLyZdujReMaiplbYJwwxam3lr7uHtQaEf0xTSu8j2ZBdrZ8FS4OQkEUjOI9UEGb3Ic0GqmlP9T9OnSItOYqoZZA/OnYg5EaVP+c/ha32nUquOk+5riEdhYgINAZDdgJkPc+YSWsrfixOIROf6t34j3eRcyFnOY0MS7tSXi1AEPE0VZdyu+5bfmBSGvLI+WR5lQ+oOQR5hRGwqf990WEdBelNO7dxhZELVhEZ+/L60PpDf5y9A8qmrY6PiEU8nhqIyLpks0BxeIsYyZ3Cr82jjfbItPGyEARsIVzluBSgVMD4oGjojz8T6wGDEXUbmZH/pra94XAs8wZ28mzbmIEppWnhBqX0c6Ov8iXCfFfUZr4KNuPxMEgk4VOYTMOd70GEjGnylivw18hbn7ZpkWh2Zql+uU2HejvOgn+WHvT0HF9NhK0Xb5vH8aFkgBP92PJx8obIbxBVeeExczxvsqWufuPdXS2sPNIgMYZ2TtvqVVsiUToeGB2FQo09fzZOSH5Vi18u/siyvC3FmjeMf4+OYWPuDPNCcrb21NgcHam7XI8AAoGLTGtLLWR+fxynbBBcg2d2ZPcZ5CMFIfOBHRWCkcA0sDT3cl9nsBppHNJze/jVxHy+lREeQEA/etSIgohTGAWW3ZlpibRXqMxlmVWEPifCubbWTzQ6U54mRMpW2UghH3gvCNFNgdday3Av7EtlIJOdUuiMq3zmmd5J4Jt4C82CKnVewA0DtZ4EEtwRG9IYuLrfpuZlnjBAtoeXRV1lqUZ6BcCe0E3m9jO28sGkALuIeJQ74XG7X8lMC7lMWWQYiYD7D6G9QT6X3qV4vXJwNKRKpYc/rI+amEawTSnDYAMEaYPwtZ0rb/7BL+atsZZaI+ncebdfVfjDJZbCZAc+JnkuNlUn2xrNRuObw8h/G0lm2pNOEJ10S8R4+yplo5B1QmC2dCDhaTaW67QJPqnJPKbVmjw7i6KGBi+CDP3JnAKlOX/YUu8uk56JfeQUuGcQg/KaBMGctnchH2n1i3+oGbibhurQj22+OO66Q6mijKoCRP/QJm5WTGcO4c0iVX0B8dIlai/uv/pGU8Wps9MxysH5ViVIj56LWKuNfy1FNO9+wx4iHYnUxfW0Iccq3YJYAlOBkMv8VZIJl9aTEEFJ626LJEw/UbEBdR9CdlwnylPf4RuNW/lcGYMgq3xNVpp/bzYKwZivvQOFgMdX1tv8D33SHvAm3zrRCU+v94BJXnBi9k25fnKsc705IMwv+I6bueXA+mDnagj1oTqsWXZ0WnPAYI3WUO7sBf7XUH230wfYXnTSVhujJxiEP/2oWqi2813gtQkKwz9N2p6yT8Vsh3+BaAwwDvtOZMJKUFcabTBSL6NoouzmzwItJ4mIboT6KXaef66rs8jCU=";
            // Initialize library
            ErrorCode error_code = Library.Initialize(sn, key);
            if (error_code != ErrorCode.e_ErrSuccess)
            {
                Console.WriteLine("Library Initialize Error: {0}\n", error_code);
                return;
            }

            try 
            {
                string input_file = input_path + "OCTest_src.pdf";
                using (PDFDoc doc = new PDFDoc(input_file))
                {
                    error_code = doc.Load(null);
                    if (error_code != ErrorCode.e_ErrSuccess)
                    {
                        Console.WriteLine("The PDFDoc [{0}] Error: {1}\n", input_file, error_code);
                        Library.Release();
                        return;
                    }

                    using (LayerTree layertree = new LayerTree(doc))
                    {
                        using (LayerNode root = layertree.GetRootNode())
                        {
                            if (root.IsEmpty())
                            {
                                Console.WriteLine("No layer information!\r\n");
                                Library.Release();
                                return;
                            }

                            // Get original information of all layer nodes.
                            string file_info = output_path + "original_layer_informations.txt";
                            TextDoc original_doc = new TextDoc(file_info, FileMode.Create);
                            GetAllLayerNodesInformation(root, -1, ref original_doc);
                            // Set new information.
                            SetAllLayerNodesInformation(root);
                            // Get new information.
                            file_info = output_path + "new_layer_informations.txt";
                            TextDoc new_info = new TextDoc(file_info, FileMode.Create);
                            GetAllLayerNodesInformation(root, -1, ref new_info);

                            string output_file = output_path + "new_layers.pdf";
                            doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);
                            // Render layer node.
                            using (LayerContext context = new LayerContext(doc, LayerContext.UsageType.e_UsageView))
                            {
                                SetAllLayerNodesVisible(context, root, false);
                                RenderAllLayerNodes(doc, context, root, output_file, output_path);
                            }
                        }
                    }
                }

                // edit layer tree
                using (PDFDoc doc = new PDFDoc(input_file))
                {
                    error_code = doc.Load(null);
                    if (error_code != ErrorCode.e_ErrSuccess)
                    {
                        Console.WriteLine("The PDFDoc [{0}] Error: {1}\n", input_file, error_code);
                        Library.Release();
                        return;
                    }

                    using (LayerTree layertree = new LayerTree(doc))
                    {
                        using (LayerNode root = layertree.GetRootNode())
                        {
                            if (root.IsEmpty())
                            {
                                Console.WriteLine("No layer information!\r\n");
                                Library.Release();
                                return;
                            }
                            int children_count = root.GetChildrenCount();
                            root.RemoveChild(children_count - 1);

                            using (LayerNode child = root.GetChild(children_count - 2))
                            {
                                using (LayerNode child0 = root.GetChild(0))
                                {
                                    child.MoveTo(child0, 0);
                                    using (child.AddChild(0, "AddedLayerNode", true))
                                    using (child.AddChild(0, "AddedNode", false)) { }
                                    string file_info = output_path + "edit_layer_informations.txt";
                                    TextDoc new_info = new TextDoc(file_info, FileMode.Create);
                                    GetAllLayerNodesInformation(root, -1, ref new_info);

                                    string output_file = output_path + "edit_layer_tree.pdf";
                                    doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);
                                }
                            }
                        }
                    }
                }

              // create layer tree
                using (PDFDoc doc = new PDFDoc(input_path + "AboutFoxit.pdf"))
                {
                    error_code = doc.Load(null);
                    if (error_code != ErrorCode.e_ErrSuccess)
                    {
                        Console.WriteLine("The PDFDoc [{0}] Error: {1}\n", input_file, error_code);
                        Library.Release();
                        return;
                    }

                    bool has_layer = doc.HasLayer();
                    using (LayerTree layertree = new LayerTree(doc))
                    {
                        has_layer = doc.HasLayer();
                        using (LayerNode root = layertree.GetRootNode())
                        {
                            if (root.IsEmpty())
                            {
                                Console.WriteLine("No layer information!\r\n");
                                Library.Release();
                                return;
                            }
                            int children_count = root.GetChildrenCount();

                            using (LayerNode child = root.AddChild(0, "AddedLayerNode", true))
                            {
                                using (root.AddChild(0, "AddedNode", false)) { }
                                string file_info = output_path + "create_layer_informations.txt";
                                TextDoc new_info = new TextDoc(file_info, FileMode.Create);
                                GetAllLayerNodesInformation(root, -1, ref new_info);

                                string output_file = output_path + "create_layer_tree.pdf";
                                doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);
                            }
                        }
                    }
                }
                //Copy graphics objects from A PDF to B PDF
                using (PDFDoc doc = new PDFDoc(input_file))
                {
                    error_code = doc.Load(null);
                    if(error_code != ErrorCode.e_ErrSuccess)
                    {
                        Console.WriteLine("The PDFDoc [{0}] Error: {1}\n", input_file, error_code);
                        Library.Release();
                        return;
                    }
                    using (PDFPage page = doc.GetPage(0))
                    {
                        page.StartParse((int)PDFPage.ParseFlags.e_ParsePageNormal, null, false);
                        using (PDFDoc newdoc = new PDFDoc(input_path + "SamplePDF.pdf"))
                        {
                            error_code = newdoc.Load(null);
                            if (error_code != ErrorCode.e_ErrSuccess)
                            {
                              Console.WriteLine("The PDFDoc [{0}] Error: {1}\n", input_file, error_code);
                              Library.Release();
                              return;
                            }
                            using (PDFPage newpage = newdoc.GetPage(0))
                            {
                                newpage.StartParse((int)PDFPage.ParseFlags.e_ParsePageNormal, null, false);
                                bool has_layer = newdoc.HasLayer();
                                using (LayerTree layertree = new LayerTree(newdoc))
                                {
                                    has_layer = newdoc.HasLayer();
                                    using (LayerNode root = layertree.GetRootNode())
                                    {
                                        using (LayerNode child = root.AddChild(0, "AddedLayerNode", true))
                                        {
                                            for (int i = 0; i < 5; i++)
                                            {
                                              foxit.pdf.graphics.GraphicsObject graphics_object = page.GetGraphicsObject(i);
                                              foxit.pdf.graphics.GraphicsObject ngraphics_object = graphics_object.Clone();
                                              newpage.InsertGraphicsObject(0, ngraphics_object);
                                              child.AddGraphicsObject(newpage, ngraphics_object);
                                            }
                                            newpage.GenerateContent();

                                            string output_file = output_path + "copy_graphics_objects.pdf";
                                            newdoc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
                                        }
                                    }
                                }
                            }
                
                        }
                    }

                }

                Console.WriteLine("PDFLayer test.");
            }
            catch (foxit.PDFException e) 
            {
                Console.WriteLine( e.Message);
            }

            Library.Release();
        }
    }
}
