using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using ExpertPdf;

namespace pdftotext_winforms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelectPDF_Click(object sender, EventArgs e)
        {
            OpenFileDialog openPdfDialog = new OpenFileDialog();
            openPdfDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
            openPdfDialog.Multiselect = false;

            if (openPdfDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxPdfDoc.Text = openPdfDialog.FileName;
            }

            openPdfDialog.Dispose();
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            if (textBoxPdfDoc.Text.Trim().Equals(String.Empty))
            {
                MessageBox.Show("Please select a PDF file to convert", "Select PDF file", MessageBoxButtons.OK);
                return;
            }

            // the pdf file to converter 
            string pdfFileName = textBoxPdfDoc.Text.Trim();

            // get PDF pages range to be extracted. 0 for end page number
            // means to extract all the pages from start page to the end
            // of the document    
            int startPageNumber = int.Parse(textBoxStartPage.Text.Trim());
            int endPageNumber = int.Parse(textBoxEndPage.Text.Trim());

            // the output text layout
            TextLayout textLayout =  radioButtonReadingLayout.Checked?TextLayout.ReadingLayout:TextLayout.OriginalLayout;

            // the html output options
            bool htmlEnabled = cbHtmlEnabled.Checked;
            string htmlCharset = textBoxHtmlCharset.Text.Trim();

            // the output text encoding
            System.Text.Encoding textEncoding = System.Text.Encoding.UTF8;
            if (radioButtonLatin.Checked)
                textEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
            else if (radioButtonAscii.Checked)
                textEncoding = System.Text.Encoding.ASCII;

            // page breaks
            bool markPageBreaks = cbMarkPageBreaks.Checked;

            //optional user password to open the PDF document
            string password = textBoxPassword.Text.Trim().Equals(String.Empty)?null:textBoxPassword.Text.Trim();

            // get the license key
            // in demo mode only the first 2 pages of the PDF document will be converted
            string licenseKey = (textBoxLicenseKey.Text.Trim().Equals(String.Empty) || textBoxLicenseKey.Text.Trim().ToLower().Equals("demo")) ?
                null : textBoxLicenseKey.Text.Trim();

            string outputPath = Application.StartupPath;
            string outputFileName = System.IO.Path.Combine(outputPath, 
                System.IO.Path.GetFileNameWithoutExtension(pdfFileName) + (htmlEnabled?".html":".txt"));

            // create the converter object and set the user options

            PdfToTextConverter pdfToTextConverter = new PdfToTextConverter();

            if (licenseKey != null)
                pdfToTextConverter.LicenseKey = licenseKey;

            pdfToTextConverter.Layout = textLayout;
            pdfToTextConverter.StartPageNumber = startPageNumber;
            pdfToTextConverter.EndPageNumber = endPageNumber;
            if (htmlEnabled)
            {
                pdfToTextConverter.AddHtmlMetaTags = true;
                pdfToTextConverter.HtmlCharset = htmlCharset;
            }
            pdfToTextConverter.MarkPageBreaks = markPageBreaks;
            if (password != null)
                pdfToTextConverter.UserPassword = password;

            try
            {
                // extract text from PDF
                string extractedText = pdfToTextConverter.ConvertToText(pdfFileName);
                // write the resulted string into an output file 
                // in the application directory using the selected encoding
                System.IO.File.WriteAllText(outputFileName, extractedText, textEncoding);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            DialogResult dr = MessageBox.Show( String.Format("Open the file in the default external viewer?", outputFileName), 
                                        "Open Output File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outputFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }

        private void autoSetHtmlCharset()
        {
            if (radioButtonUTF8.Checked)
                textBoxHtmlCharset.Text = "utf-8";
            else if (radioButtonLatin.Checked)
                textBoxHtmlCharset.Text = "iso-8859-1";
            else if (radioButtonAscii.Checked)
                textBoxHtmlCharset.Text = "us-ascii";
        }

        private void radioButtonUTF8_CheckedChanged(object sender, EventArgs e)
        {
            autoSetHtmlCharset();
        }

        private void radioButtonLatin_CheckedChanged(object sender, EventArgs e)
        {
            autoSetHtmlCharset();
        }

        private void radioButtonAscii_CheckedChanged(object sender, EventArgs e)
        {
            autoSetHtmlCharset();
        }
    }
}