// *****************************************************************************
// This C# project is designed to give you a good idea of how to use
// the many functions from the ActiveX edition of losLab PDF Library 
//
// *****************************************************************************

using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace csharp_activex_sample
{
    public partial class Form1 : Form
    {
        // Initialize PDF Library
        PDFlibAX.PDFlibrary qp = new PDFlibAX.PDFlibrary();

        public Form1()
        {
            InitializeComponent();
        }

        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
            qp.SetOrigin(1);

            // Call the DrawText function
            qp.DrawText(100, 100, "Hello world from C# and the ActiveX edition of PDF Library");

            // Save the changes to the document on the local disk (in the debug folder)
            qp.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 = qp.NewDocument();

            // Call the DrawHTMLText function and specify the necessary settings.
            qp.DrawHTMLText(40, 760, 200, "Here is some <b>bold</b>, <i>italic</i> and <u>underlined</u> text");
            qp.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)
            qp.SaveToFile(fileName);
            
            // Remove document from memory
            qp.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 = qp.NewDocument();

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

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

            qp.SelectPage(1);

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

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

            // Remove document from memory
            qp.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 = @"sample1_extracted.pdf";

            // Load the document that you want to extract text from into memory
            int docID = qp.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 = qp.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.
                qp.SaveToFile(OutputFile);
                System.Diagnostics.Process.Start(OutputFile);
            }

            // Remove document from memory
            qp.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 = qp.LoadFromFile(fileName, "");

            // Set the paramters for the PrintDocument function
            string PrinterName = qp.GetDefaultPrinterName();
            int StartPage = 1; // Set first page number
            int EndPage = qp.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 = qp.PrintOptions(PageScaling, AutoRotateCenter, Title);

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

            // Remove document from memory
            qp.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 = qp.GetPrinterNames();
            // Display the printer names in a message box
            MessageBox.Show(printers);
        }

        private void btnDARenderPageToVariant_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 = qp.DAOpenFile(fileName, password);

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

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

            // Work out the smallest DPI needed to fit the entire
            // page into the PictureBox
            int horizontalDPI = Convert.ToInt32((pictureBox1.Width / pageHeight) * 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[])qp.DARenderPageToVariant(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
            qp.DACloseFile(fileHandle);
        }

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

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

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

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

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

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

            // Remove document from memory
            qp.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 = @"ocgs.pdf";

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

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

            // Initiate the OptionalContentGroupCount function
            // and assign the returned value to an int variable
            int OCGs = qp.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
            qp.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 = qp.LoadFromFile(InputfileName, "");

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

            // Initiate the NewOutline function and set paramters
            int nOutline = qp.NewOutline(0, "New Bookmark", 1, pageHeight);

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

            // Remove document from memory
            qp.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 = @"sample2.pdf";

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

            // Remove document from memory
            qp.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 = @"merged_samples.pdf";

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

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

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

            // Remove document from memory
            qp.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
            qp.AddToFileList(ListName, firstFile);
            // Add the second file to the file list
            qp.AddToFileList(ListName, secondFile);
            // Merge all files in the file list and output a new file
            qp.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 = qp.LoadFromFile(fileName, "");
            qp.SelectDocument(DocumentID);
            string PDFversion = qp.GetInformation(0);
            string Author = qp.GetInformation(1);
            string Title = qp.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 = @"sample3.pdf";

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

            string numberOfImages = Convert.ToString(images);

            MessageBox.Show(numberOfImages);

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