using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using PDFlibDLL;

namespace csharp_dll_sample
{
    public partial class Form1 : Form
    {
        // losLab PDF Library DLL Edition setup
        PDFlibrary PDF;

        public Form1()
        {
            InitializeComponent();

            // Different filename for 32-bit and 64-bit DLL
            string dllName;

            // Check to see if IntPtr size is 4.
            // If 4 then it's 32-bit, if 8 then it is 64-bit.
            if (IntPtr.Size == 4)
            {
                dllName = "PDFlibDLL32.dll"; // 32 bits 
            }
            else
            {
                dllName = "PDFlibDLL64.dll"; // 64 bits 
            }

            // Load the library
            if (!(File.Exists(dllName) || File.Exists(Environment.SystemDirectory + @"\" + dllName)))
                dllName = @"..\..\..\..\DLL\" + dllName;

            PDF = new PDFlibrary(dllName);

            if (PDF.LibraryLoaded()) ;
            else
                MessageBox.Show("Could not locate the PDF Library DLL!");
        }

        private void btnDrawText_Click(object sender, EventArgs e)
        {
            // This function draws text onto a document
            
            // Setup the parameters
            string fileName = @".\drawText.pdf";

            // Set origin co-ordinates to top left of page
            PDF.SetOrigin(1);

            // Call the DrawText function
            PDF.DrawText(80, 100, "Hello world from C# and losLab PDF Library");

            // Save the changes to the document on the local disk (in the debug folder)
            PDF.SaveToFile(fileName);

            // Open PDF automatically
            System.Diagnostics.Process.Start(fileName);         
 
        }

        private void btnDrawHTMLText_Click(object sender, EventArgs e)
        {
            // This function draws text using HTML tags onto a document

            // Setup the parameters
            string fileName = @".\drawHTMLText.pdf";

            // Create a new document in memory with one blank page
            int docID = PDF.NewDocument();


            // Call the DrawHTMLText function and specify the necessary settings.
            PDF.DrawHTMLText(40, 760, 200, "Here is some <b>bold</b>, <i>italic</i> and <u>underlined</u> text");
            PDF.DrawHTMLText(40, 730, 200, "<ul><li>This</li><li>is</li><li>a</li><li>bullet</li><li>list</li></ul>");
                
            // Save the changes to the document on the local disk (in the debug folder)
            PDF.SaveToFile(fileName);
                
            // Remove document from memory
            PDF.RemoveDocument(docID);

            // Open PDF automatically
            System.Diagnostics.Process.Start(fileName);

        }

        private void btnGetPageText_Click(object sender, EventArgs e)
        {
            // This function extracts text from a page in a document

            // Setup the parameters
            string fileName = @"..\..\..\Sample1.pdf";

            // Create a new document in memory with one blank page
            int docID = PDF.NewDocument();


            // Load the document that you want to extract text from into memory
            PDF.LoadFromFile(fileName, "");

            // Select the page that you want to extract text from (first page in 
            // a document is always 1)

            PDF.SelectPage(1);

            // Specify the variable that the text should be added to and call
            // the GetPageText function (with the appropriate option selected)
            string pageText = PDF.GetPageText(1);

            // Display the extracted text in a message box
            MessageBox.Show(pageText);

            // Remove document from memory
            PDF.RemoveDocument(docID);

        }

        private void btnExtractPages_Click(object sender, EventArgs e)
        {
            // This function extracts pages from a document

            // Setup the parameters
            string fileName = @"..\..\..\Sample1.pdf";
            int StartPage = 1;
            int PageCount = 1;
            string OutputFile = @".\Sample1Extracted.pdf";

            // Load the document that you want to extract text from into memory
            int docID = PDF.LoadFromFile(fileName, "");
            // The ExtractPages requires two paramters. The first paramter
            // tells the library where to start extracting pages from and
            // the second paramter tells the library how many pages from the
            // starting point should be extracted.
            int extractPageSuccess = PDF.ExtractPages(StartPage, PageCount);
            // You can find out if the extraction process was successfull by 
            // checking the returned value of the ExtractPages function. If 
            // it returns 0 then it means the page(s) could not be extracted, 
            // other wise it will return a new document ID.
            if (extractPageSuccess == 0)
            {
               MessageBox.Show("Page(s) could not be extracted.");
            }
            else
            {
               MessageBox.Show("Page(s) successfully extracted.");
                // First check to see if the extraction process worked
                // and if it did, then save the results to a new file.
                PDF.SaveToFile(OutputFile);

                System.Diagnostics.Process.Start(OutputFile);

            }

            // Remove document from memory
            PDF.RemoveDocument(docID);
        }

        private void btnPrintDocument_Click(object sender, EventArgs e)
        {
            // This function prints a document

            // Setup general parameters
            string fileName = @"..\..\..\Sample1.pdf";

            {
                // Load the document that you want to print into memory
                int docID = PDF.LoadFromFile(fileName, "");

                // Set the paramters for the PrintDocument function
                string PrinterName = PDF.GetDefaultPrinterName();
                int StartPage = 1; // Set first page number
                int EndPage = PDF.PageCount(); // Set last page number

                // Set the paramters for the PrintOptions function
                int PageScaling = 0;
                int AutoRotateCenter = 0;
                string Title = fileName;

                // Assign the options for printing to an int variable
                int Options = PDF.PrintOptions(PageScaling, AutoRotateCenter, Title);

                // Print the document with the required paramters and options specified
                PDF.PrintDocument(PrinterName, StartPage, EndPage, Options);

                // Remove document from memory
                PDF.RemoveDocument(docID);
            }

        }

        private void btnGetPrinterNames_Click(object sender, EventArgs e)
        {
            // This function retrieves a list of all the local printers
            // Setup general parameters

            {
                // Assign all  of the printers to a string variable
                string printers = PDF.GetPrinterNames();
                // Display the printer names in a message box
                MessageBox.Show(printers);
            }

        }

        private void btnDARenderPageToString_Click(object sender, EventArgs e)
        {
            // This function renders a page in a PDF to a variant which can be used
            // to display the PDF in a window

            // Setup general parameters
            string fileName = @"..\..\..\Sample1.pdf";
            string password = "";
            int pageNumber = 1;

            {
                // Open the file, get a file handle
                int fileHandle = PDF.DAOpenFile(fileName, password);

                // Get a reference to the first page
                int pageReference = PDF.DAFindPage(fileHandle, pageNumber);

                // Height and width in points (1/72 inch)
                double pageHeight = PDF.DAGetPageHeight(fileHandle, pageReference);
                double pageWidth = PDF.DAGetPageWidth(fileHandle, pageReference);

                // Work out the smallest DPI needed to fit the entire
                // page into the PictureBox
                int horizontalDPI = Convert.ToInt32((pictureBox1.Width / pageWidth) * 72);
                int verticalDPI = Convert.ToInt32((pictureBox1.Height / pageHeight) * 72);
                int smallestDPI;
                if (horizontalDPI < verticalDPI)
                {
                    smallestDPI = horizontalDPI;
                }
                else
                {
                    smallestDPI = verticalDPI;
                }

                // Render the page to BMP format into the byte array
                byte[] bitmapData = (byte[])PDF.DARenderPageToString(fileHandle,
                    pageReference, 0, smallestDPI);

                // Put the byte array into a stream
                MemoryStream stream = new MemoryStream(bitmapData);

                // Create a new Image from the stream
                pictureBox1.Image = Image.FromStream(stream);

                // Close the file
                PDF.DACloseFile(fileHandle);
            }

        }

        private void btnNewOptionalContentGroup_Click(object sender, EventArgs e)
        {
            // This function creates a new Optional Content Group (known as a Layer in Acrobat)

            // Setup general parameters
            string OutputfileName = @".\OptionalContentGroup.pdf";

            {
                // Load the document that you want to print into memory
                int docID = PDF.NewDocument();

                // Create the new Optional Content Group and assign it a name
                int OCG1 = PDF.NewOptionalContentGroup("OCG 1");

                int ContentStream = PDF.NewContentStream();
                PDF.SelectContentStream(ContentStream);
                PDF.DrawText(100, 750, "This text belongs to OCG 1");
                PDF.SetContentStreamOptional(OCG1);
                PDF.SetOptionalContentGroupVisible(OCG1, 1);

                int OCG2 = PDF.NewOptionalContentGroup("OCG 2");
                PDF.SelectContentStream(ContentStream);
                PDF.DrawText(100, 730, "This text belongs to OCG 2.");
                PDF.SetContentStreamOptional(OCG2);
                PDF.SetOptionalContentGroupVisible(OCG2, 1);

                // Save the new OCG to the specified file on the local disk
                PDF.SaveToFile(OutputfileName);

                // Remove document from memory
                PDF.RemoveDocument(docID);

                System.Diagnostics.Process.Start(OutputfileName);
            }
 
        }

        private void btnOptionalContentGroupCount_Click(object sender, EventArgs e)
        {
            // This function counts the number of Optional Content Groups (aka Layers) in a document

            // Setup general parameters
            string fileName = @".\OptionalContentGroup.pdf";

            {
                // Load the document that you want to print into memory
                // and assign the Document ID to an int variable
                int docID = PDF.LoadFromFile(fileName, "");

                // Select the document using the Document ID
                PDF.SelectDocument(docID);

                // Initiate the OptionalContentGroupCount function
                // and assign the returned value to an int variable
                int OCGs = PDF.OptionalContentGroupCount();

                // Convert the int value to a string
                string CountOCGs = Convert.ToString(OCGs);

                // Display the number of OCGs from the file in the message box
                MessageBox.Show(CountOCGs);

                // Remove document from memory
                PDF.RemoveDocument(docID);
            }
 
        }

        private void btnNewOutline_Click(object sender, EventArgs e)
        {
            // This function creates a new outline (aka bookmark) in a document

            // Setup general parameters
            string InputfileName = @"..\..\..\Sample1.pdf";
            string OutputfileName = @".\NewOutline.pdf";

            {
                // Load the document into memory
                int docID = PDF.LoadFromFile(InputfileName, "");

                // Get the page height value for the position paramter in the NewOutline function
                double pageHeight = PDF.PageHeight();

                // Initiate the NewOutline function and set paramters
                int nOutline1 = PDF.NewOutline(0, "Bookmark 1", 1, pageHeight / 2);
                int nOutline2 = PDF.NewOutline(0, "Bookmark 2", 1, pageHeight);

                // Check the value returned from the NewOutline function to see
                // if it was successful.
                if (nOutline1 == 0 || nOutline2 == 0)
                {
                    MessageBox.Show("Sorry, the bookmark could not be added.");
                }
                else
                {  
                    // Save the new outline to the document.
                    PDF.SaveToFile(OutputfileName);
                    System.Diagnostics.Process.Start(OutputfileName);
                }

                // Remove document from memory
                PDF.RemoveDocument(docID);
            }

        }

        private void btnOutlineCount_Click(object sender, EventArgs e)
        {
            // This function counts the number of outlines (aka bookmarks) in a document

            // Setup general parameters
            string fileName = @".\NewOutline.pdf";

            {
                // Load the document into memory
                int docID = PDF.LoadFromFile(fileName, "");
                PDF.SelectDocument(docID);
                int numberOfOutlines = PDF.OutlineCount();
                string Outlines = Convert.ToString(numberOfOutlines);
                MessageBox.Show(Outlines);

                // Remove document from memory
                PDF.RemoveDocument(docID);
            }
  
        }

        private void btnMergeDocument_Click(object sender, EventArgs e)
        {
            // This function merges two documents together

            // Setup general parameters
            string firstDoc = @"..\..\..\Sample1.pdf";
            string secondDoc = @"..\..\..\Sample2.pdf";
            string DestfileName = @".\MergedSamples.pdf";

            {
                // Load the document into memory
                PDF.LoadFromFile(firstDoc, "");
                int MainDoc = PDF.SelectedDocument();
                PDF.LoadFromFile(secondDoc, "");
                int Append = PDF.SelectedDocument();

                PDF.SelectDocument(MainDoc);
                PDF.MergeDocument(Append);

                PDF.SaveToFile(DestfileName);
                System.Diagnostics.Process.Start(DestfileName);

                // Remove document from memory
                PDF.RemoveDocument(MainDoc);

            }
  
        }

        private void btnMergeFileList_Click(object sender, EventArgs e)
        {
            // This function merges a list of documents together

            // Setup general parameters
            string ListName = @"Sample";
            string firstFile = @"..\..\..\Sample1.pdf";
            string secondFile = @"..\..\..\Sample2.pdf";
            string OutputFile = @".\MergeFileListSample.pdf";

            {
                // Add the first file to the file list
                PDF.AddToFileList(ListName, firstFile);
                // Add the second file to the file list
                PDF.AddToFileList(ListName, secondFile);
                // Merge all files in the file list and output a new file
                PDF.MergeFileList(ListName, OutputFile);

                System.Diagnostics.Process.Start(OutputFile);

            }
         }

        private void btnGetInformation_Click(object sender, EventArgs e)
        {
            // This function retrieves document information

            // Setup general parameters
            string fileName = @"..\..\..\Sample1.pdf";

            {
                int DocumentID = PDF.LoadFromFile(fileName, "");
                PDF.SelectDocument(DocumentID);
                string PDFversion = PDF.GetInformation(0);
                string Author = PDF.GetInformation(1);
                string Title = PDF.GetInformation(2);

                string[] infoArray = {PDFversion, Author, Title};
                foreach (string info in infoArray)
                {
                    MessageBox.Show(info);
                }
            }

        }

        private void btnFindImages_Click(object sender, EventArgs e)
        {
            // This function counts the number of images in a document

            // Setup general parameters
            string fileName = @"..\..\..\Images.pdf";

            {
                int DocumentID = PDF.LoadFromFile(fileName, "");
                PDF.SelectDocument(DocumentID);
                int images = PDF.FindImages();

                string numberOfImages = Convert.ToString(images);

                MessageBox.Show(numberOfImages);

                // Remove the document from memory
                PDF.RemoveDocument(DocumentID);
            }

        }
    }
}