/*
// losLab PDF Library (Convert Images to PDF Sample)
//
*/

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

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

        public frmMain()
        {
            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 frmMain_Load(object sender, EventArgs e)
        {
        // Set the output folder to the desktop as default
            textBoxSaveFiles.Text = Environment.CurrentDirectory;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
        // Exit the application
            Close();
        }

        private void btnConvertImages_Click(object sender, EventArgs e)
        {
            // Check to see that user actually has any items in the list
            if (listBoxImages.Items.Count == 0)
            {
                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Error]: Please add one or more images to the list and try again.");
                return;
            }

            // Iterate through each image filename in the listbox
            bool bFail = false;
            foreach (string sImageFileName in listBoxImages.Items)
            {
                // Create a blank document
                PDF.NewDocument();

                // Load next image into memory
                int imageID;
                if (sImageFileName.Substring(sImageFileName.Length - 3).ToLower() == @"png")
                    imageID = PDF.AddImageFromFile(sImageFileName, 5);
                else
                    imageID = PDF.AddImageFromFile(sImageFileName, 0);

                // Check to see if image loaded successfully
                if (imageID == 0)
                {
                    txtBoxLog.AppendText(Environment.NewLine);
                    txtBoxLog.AppendText("> [Error]: Unable to load the file (" + sImageFileName + ").");

                    bFail = true;
                    continue;
                }
                
                // Select the load image, technically selected by default
                // after loading but selecting again to be safe
                PDF.SelectImage(imageID);

                // Get horizontal and vertical image resolution
                int dpix = PDF.ImageHorizontalResolution();
                int dpiy = PDF.ImageVerticalResolution();

                if (dpix == 0) dpix = 72;
                if (dpiy == 0) dpiy = 72;

                // Get width, height of image in points

                double ImageWidthInPoints = (double)PDF.ImageWidth() / dpix * 72.0; // assumming dpi units
                double ImageHeightInPoints = (double)PDF.ImageHeight() / dpiy * 72.0;

                // Set origin for drawing functions to top
                // left of page 0, 0
                PDF.SetOrigin(1);

                if(PDF.SetPageDimensions(ImageWidthInPoints, ImageHeightInPoints) ==0)
                {
                    txtBoxLog.AppendText(Environment.NewLine);
                    txtBoxLog.AppendText("> [Error]: Unable to process the page dimensions for the file (" + sImageFileName + ").");
                    bFail = true;
                    continue;
                }

                // Draw the image onto the document using the specified width/height
                if(PDF.DrawImage(0, 0, ImageWidthInPoints, ImageHeightInPoints) ==0)
                {
                    txtBoxLog.AppendText(Environment.NewLine);
                    txtBoxLog.AppendText("> [Error]: Unable to draw the image (" + sImageFileName + ") to the PDF file.");

                    bFail = true;
                    continue;
                }

                // Then do so using a .PDF extension instead of the image filename
                // in the output folder...
                string sPDFFileName = textBoxSaveFiles.Text + "\\" + Path.GetFileNameWithoutExtension(sImageFileName) + ".pdf";
                if (PDF.SaveToFile(sPDFFileName) == 0)
                {
                    txtBoxLog.AppendText(Environment.NewLine);
                    txtBoxLog.AppendText("> [Error]: The image " + Path.GetFileName(sImageFileName) + " could not be saved as a PDF file.");

                    bFail = true;
                    continue;
                }

                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Success]: The file (" + Path.GetFileName(sImageFileName) + ") was converted to PDF.");
            }

        // Let the user know that we're all finished and done
            if (bFail != true)
            {
                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Success]: Finished. The image(s) have been converted to PDF.");
            }
            else
            {
                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Error]: There was an issue converting some images.");
            }
        }
   
        
        private void btnLoadImage_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.RestoreDirectory = false;
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "Image Files (JPEG,GIF,BMP,PNG,WMF,EMF,TIFF)|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*.tiff;*.wmf;*.emf";
            openFileDialog1.FilterIndex = 8;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
            // Add the selected item to the listbox
                string[] sFileNames = openFileDialog1.FileNames;

                foreach (var item in sFileNames)
                {
                    listBoxImages.Items.Add(item);
                }
            }
        }

        private void btnRemoveImage_Click(object sender, EventArgs e)
        {
            listBoxImages.Items.Remove(listBoxImages.SelectedItem);
        }

        private void btnOutputFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFolderDialog = new FolderBrowserDialog();
            openFolderDialog.Description = "Select the output folder";

            if (openFolderDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxSaveFiles.Text = openFolderDialog.SelectedPath;
            }
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            // Check to see that user actually has any items in the list
            if (listBoxImages.Items.Count < 2) // you need at least 2 images in order to merge files
            {
                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Error]: You need at least 2 images in order to convert and merge.");

                return;
            }

            int iDocID = PDF.SelectedDocument(); // Get the ID of the first document

            // Iterate through each image filename in the listbox
            bool bFail = false;
            foreach (string sImageFileName in listBoxImages.Items)
            {
                // Create a blank document
                int iNewDocID = PDF.NewDocument();

                // Load the image into memory
                int imageID;
                if (sImageFileName.Substring(sImageFileName.Length - 3).ToLower() == @"png")
                    imageID = PDF.AddImageFromFile(sImageFileName, 5);
                else
                    imageID = PDF.AddImageFromFile(sImageFileName, 0);

                // Check to see if image loaded successfully into memory
                if (imageID == 0)
                {
                    txtBoxLog.AppendText(Environment.NewLine);
                    txtBoxLog.AppendText("> [Error]: Unable to load the file (" + sImageFileName + ").");

                    bFail = true;
                    continue;
                }

                // Select loaded image
                PDF.SelectImage(imageID);

                // Get horizontal and vertical resolution of image
                int dpix = PDF.ImageHorizontalResolution();
                int dpiy = PDF.ImageVerticalResolution();

                if (dpix == 0) dpix = 72;
                if (dpiy == 0) dpiy = 72;

                // Get page size and page width in points
                double ImageWidthInPoints = (double)PDF.ImageWidth() / dpix * 72.0; // assumming dpi units
                double ImageHeightInPoints = (double)PDF.ImageHeight() / dpiy * 72.0;

                // Set page origin (0,0) to top left of page
                PDF.SetOrigin(1);
                
                // Select page dimensions based on width/height of image in points
                if (PDF.SetPageDimensions(ImageWidthInPoints, ImageHeightInPoints) == 0)
                {
                    txtBoxLog.AppendText(Environment.NewLine);
                    txtBoxLog.AppendText("> [Error]: Unable to process the page dimensions for the file (" + sImageFileName + ").");

                    bFail = true;
                    continue;
                }

                // Draw the image onto the document using the specified width/height
                if (PDF.DrawImage(0, 0, ImageWidthInPoints, ImageHeightInPoints) == 0)
                {
                    txtBoxLog.AppendText(Environment.NewLine);
                    txtBoxLog.AppendText("> [Error]: Unable to draw the image (" + sImageFileName + ") onto the PDF file.");

                    bFail = true;
                    continue;
                }

                // Append the new document to the primary 
                PDF.SelectDocument(iDocID);
                PDF.MergeDocument(iNewDocID); // Note: the merge function also deletes the new document
            }

            // Delete the first page (blank) of the merged document as this was created by the first
            PDF.DeletePages(1, 1); // instance of losLab PDF Library

            // Now all documents have been merged 
            // with the primary document
            // So time to save it...
            if (PDF.SaveToFile(textBoxSaveFiles.Text + "\\merged_file.pdf") == 0) // Use the same folder, and a hard-coded filename
            {
                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Error]: Could not save the combined images as a PDF file.");

                bFail = true;
                return; // if that didn't work then forgetaboutit
            }

            // Let the user know that we're all finished and done
            if (bFail != true)
            {
                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Success]: The image(s) have been converted to PDF and merged into one PDF.");
            }
            else
            {
                txtBoxLog.AppendText(Environment.NewLine);
                txtBoxLog.AppendText("> [Error]: There was an issue during the converting, merging or saving process.");
            }
        }

        private void VisitLink()
        {
            // Change the color of the link text by setting LinkVisited 
            // to true.
            linkLabel1.LinkVisited = true;
            //Call the Process.Start method to open the default browser 
            //with a URL:
            System.Diagnostics.Process.Start("https://www.loslab.com/pdf-library/delphi-pdf-library");
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                VisitLink();
            }
            catch (Exception)
            {
                MessageBox.Show("Unable to open link that was clicked.");
            }
        }
    }
}