// 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 do PDF page organization,
// such as inserting, removing, and so on.

using System;
using System.IO;

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

namespace page_organizationCS
{
    class page_organization
    {
        const string input_path = "../input_files/";
        const string output_path = "../output_files/page_organization/";

        const string sn = "Rew1vB0TqoMIxX444UcpScARWdhgJpsJfzmyMLR32a0+EgrCjp2NaQ==";
        const 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=";

        private static void CreateResultFolder(string output_path)
        {
            if (!Directory.Exists(output_path))
            {
                Directory.CreateDirectory(output_path);
            }
        }

        static void AddTextObjects(PDFPage page, string content)
        {
            long position = page.GetLastGraphicsObjectPosition(GraphicsObject.Type.e_TypeText);
            using (var text_object = TextObject.Create())
            {

                text_object.SetFillColor(0xFFAAAAAA);
                text_object.SetStrokeColor(0xFFF68C21);

                // Prepare text state
                using (var state = new TextState())
                {
                    using (var font = new Font(Font.StandardID.e_StdIDTimes))
                    {
                        state.font_size = 64.0f;
                        state.font = font;
                        state.textmode = TextState.Mode.e_ModeFillStrokeClip;
                    }

                    text_object.SetTextState(page, state, false, 750);

                    // Set content
                    text_object.SetText(content);
                    page.InsertGraphicsObject(position, text_object);

                    // Transform to center
                    var rect = text_object.GetRect();
                    float offset_x = (page.GetWidth() - (rect.right - rect.left)) / 2;
                    float offset_y = (page.GetHeight() - (rect.top - rect.bottom)) / 2;
                    text_object.Transform(new Matrix2D(1, 0, 0, 1, offset_x, offset_y), false);

                    // Generator content
                    page.GenerateContent();
                }
            }
        }

        static void InsertPage()
        {
            string input_file = input_path + "page_organization_123.pdf";
            using (var doc = new PDFDoc(input_file))
            {
                ErrorCode code = doc.Load(null);
                if (code != ErrorCode.e_ErrSuccess)
                {
                    Console.WriteLine("The PDFDoc {0} Error: {1}", input_file, code);
                    return;
                }

                using (var page = doc.InsertPage(-1, PDFPage.Size.e_SizeLetter))
                {
                    AddTextObjects(page, "insert in first");
                }
                using (var page = doc.InsertPage(2, PDFPage.Size.e_SizeLetter))
                {
                    AddTextObjects(page, "insert in 2 (based 0)");
                }
                using (var page = doc.InsertPage(doc.GetPageCount(), PDFPage.Size.e_SizeLetter))
                {
                    AddTextObjects(page, "insert in last");
                }
                string output_file = output_path + "insert_page.pdf";
                doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
            }
            Console.WriteLine("Insert pages.");
        }

        static void RemovePage()
        {
            string input_file = input_path + "page_organization_123.pdf";
            using (var doc = new PDFDoc(input_file))
            {
                ErrorCode code = doc.Load(null);
                if (code != ErrorCode.e_ErrSuccess)
                {
                    Console.WriteLine("The PDFDoc {0} Error: {1}", input_file, code);
                    return;
                }

                while (doc.GetPageCount() > 1)
                {
                    doc.RemovePage(0);
                }
                string output_file = output_path + "remove_all_pages_exceptt_the_last_page.pdf";
                doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
            }
            Console.WriteLine("Remove pages.");
        }

        // You can implement the functionality of exporting pages by creating an empty document
        // and importing part of the source document into the empty document.
        // You can also import the target document as a source document
        // to implement the copy page functionality.
        static void ImportPage()
        {
            string file_dest = input_path + "page_organization_123.pdf";
            string file_src = input_path + "page_organization_abc.pdf";
            using (var doc_src = new PDFDoc(file_src))
            {
                ErrorCode code = doc_src.Load(null);
                if (code != ErrorCode.e_ErrSuccess)
                {
                    Console.WriteLine("The PDFDoc {0} Error: {1}", file_src, code);
                    return;
                }
                Range import_ranges = new Range(0);
                import_ranges.AddSingle(doc_src.GetPageCount() - 1);
                using (var doc_dest = new PDFDoc(file_dest))
                {
                    code = doc_dest.Load(null);
                    if (code != ErrorCode.e_ErrSuccess)
                    {
                        Console.WriteLine("The PDFDoc {0} Error: {1}", file_dest, code);
                        return;
                    }
                    // Import page from PDFDoc object.
                    using (var progressive =
                            doc_dest.StartImportPages(-1, doc_src, (int)PDFDoc.ImportPageFlags.e_ImportFlagNormal,
                            "abc", import_ranges, null))
                    {
                        while (progressive.Continue() != Progressive.State.e_Finished)
                        {
                        }
                    }
                    string output_file = output_path + "page_organization_abc_to_123_import_pages.pdf";
                    doc_dest.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
                }
                using (var doc_dest = new PDFDoc(file_dest))
                {
                    code = doc_dest.Load(null);
                    if (code != ErrorCode.e_ErrSuccess)
                    {
                        Console.WriteLine("The PDFDoc {0} Error: {1}", file_dest, code);
                        return;
                    }
                    // Import pages from file path.
                    using (var progressive = doc_dest.StartImportPagesFromFilePath(
                        -1, file_src, null, (int)PDFDoc.ImportPageFlags.e_ImportFlagNormal, "abc",
                        import_ranges, null))
                    {
                        while (progressive.Continue() != Progressive.State.e_Finished)
                        {
                        }
                    }
                    string output_file = output_path + "abc_to_123_import_pages_form_filepath.pdf";
                    doc_dest.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
                }
            }
            Console.WriteLine("Import pages.");

        }

        // This example shows how to use the use the functions StartExtractPages and InsertDocument together,
        // instead of the StartImportPagesFromFilePath function. The execution efficiency of importing pages has
        // been optimized in these new functions.
        public static void ImportPageOptimized()
        {
            string file_dest = input_path + "page_organization_123.pdf";
            string file_src = input_path + "page_organization_abc.pdf";
            string file_temp = output_path + "page_organization_import_extracted_pages.pdf";

            ErrorCode code;
            using (var doc_src = new PDFDoc(file_src))
            {
                code = doc_src.Load(null);
                if (code != ErrorCode.e_ErrSuccess)
                {
                    Console.WriteLine("The PDFDoc {0} Error: {1}", file_src, code);
                    return;
                }
                // Extract pages to temporary document
                Range import_ranges = new Range(0);
                import_ranges.AddSingle(doc_src.GetPageCount() - 1);
                using (var progressive = doc_src.StartExtractPages(file_temp, (int)PDFDoc.ExtractPagesOptions.e_ExtractPagesOptionAnnotation, import_ranges, null))
                {
                    while (progressive.Continue() != Progressive.State.e_Finished)
                    {
                    }
                }
            }

            using (var doc_temp = new PDFDoc(file_temp))
            {
                code = doc_temp.Load(null);
                if (code != ErrorCode.e_ErrSuccess)
                {
                    Console.WriteLine("The PDFDoc {0} Error: {1}", file_temp, code);
                    return;
                }

                using (var doc_dest = new PDFDoc(file_dest))
                {
                    code = doc_dest.Load(null);
                    if (code != ErrorCode.e_ErrSuccess)
                    {
                        Console.WriteLine("The PDFDoc {0} Error: {1}", file_dest, code);
                        return;
                    }
                    // Insert temporary document into destination
                    doc_dest.InsertDocument(-1, doc_temp, (int)PDFDoc.InsertDocOptions.e_InsertDocOptionAttachments);
                    string output_file = output_path + "abc_to_123_insert_document.pdf";
                    doc_dest.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
                }
            }
            Console.WriteLine("Import pages optimized.");
        }

        static void MovePages()
        {
            string input_file = input_path + "page_organization_123.pdf";
            string input_file1 = input_path + "page_organization_abc.pdf";
            Range page_set = new Range();
            // Move page
            using (var doc = new PDFDoc(input_file))
            {
                ErrorCode code = doc.Load(null);
                if (code != ErrorCode.e_ErrSuccess)
                {
                    Console.WriteLine("The PDFDoc {0} Error: {1}", input_file, code);
                    return;
                }
                int count = doc.GetPageCount();
                using (var page = doc.GetPage(0))
                {
                    doc.MovePageTo(page, doc.GetPageCount() - 1);
                }
                string output_file1 = output_path + "move_first_page_to_last.pdf";
                doc.SaveAs(output_file1, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
                for (int i = 0; i < count / 2; i++)
                {
                    page_set.AddSingle(2 * i);
                }
            }
            using (var doc = new PDFDoc(input_file1))
            {
                ErrorCode code = doc.Load(null);
                if (code != ErrorCode.e_ErrSuccess)
                {
                    return;
                }
                doc.MovePagesTo(page_set, doc.GetPageCount() - 1);
                string output_file = output_path + "move_pages.pdf";
                doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
            }
            Console.WriteLine("Move pages.");
        }
        static void Main(string[] args)
        {
            CreateResultFolder(output_path);
            // 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
            {
                InsertPage();
                RemovePage();
                ImportPage();
                ImportPageOptimized();
                MovePages();
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Library.Release();
        }
    }
}
