onlyforbopi
3/23/2018 - 9:55 AM

CSharp.WinForm

  1. How to add dynamic datebox + timebox
  2. How to add OpenFileDialog (Single/Multi)
  3. How to make a refresh button, use it in Form_Load
  4. How to make a quit button
  5. How to make and use class libraries for static varaibles
  6. how to make and use class libraries for methods
  7. how to reference dll library
  8. how to create dll library
  9. how to open file dialog for directories
/////////////////////////////////////////////////////////////
//
//  Opens file dialog for directory
//  Select directory
//  Assign it to variable.
//


// Handle output selector event.
        private void OutputButton_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                PathBox.Text = folderBrowserDialog1.SelectedPath;
            }
        }
dll = class library for c#

How to create:

	New Project -> Visual C# Projects -> Class Library - (Name will be given to namespace)
	
		The solution explorer will add two C# classes to the project:
			AssemblyInfo.cs will be updated or created if it did not exit
			Class1.cs (our class library)
			
	Double Click on class to edit it. Namespace will be = the name we gave it.
	That namespace will need to be referenced in the code to access this library.
	
	If its a static class it will have no constructor.
	
	Build the project often to make sure there is no problem.
	
	Adding methods:
	
		Through interface: 
			Open class view from your view menu
			It displays class1 with no methods and properties. 
			Rclick to add method or property
			
	Alternatively through code
////////////////////////////////////////////////////////
//
//  1. Download dll library
//  2. Rlick on References + Add Reference 
//  3. Add "using" at library section of main code
//
//  using iTextSharp.text.pdf;
//  using System;
//  using System.Collections.Generic;
//  using System.Linq;
//  using System.Text;
//  using System.IO;
//  using iTextSharp.text;
//  using static iTextSharp.text.Font;
//  using iTextSharp.text.pdf.parser;
//
/////////////////////////////////////////////////////////
// Class method
// 
// Design -> Rclick on Project + Add class
// Declare functions
//
// Class is in project, not a separate dll, so we dont 
// have to declare it using "using" at the top.
//
// Usage: PDFLib.classname(input parameters)
//
//



using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using static iTextSharp.text.Font;
using iTextSharp.text.pdf.parser;

namespace PDFappv1
{
    public static class PDFlib
    {


        /// <summary>
        /// Function: Watermarkpdf
        /// Description: Watermarks a pdf based on hardcoded word.
        /// Input: src = Source File, dest = Destination file (Full Paths)
        /// Output: Void
        /// Usage: WaterMarkPDF("path1", "path2")
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dest"></param>
        public static void Watermarkpdf(String src, String dest)
        {
            // Initialize a PdfReader object.
            PdfReader reader = new PdfReader(src);

            // Initialize n integer with total n. of pages.
            int n = reader.NumberOfPages;

            // Initialize a PdfStamper
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));

            // Greek test - Worked
            // Initialize a BaseFont/Font
            BaseFont GreekFont = iTextSharp.text.pdf.BaseFont.CreateFont("C:\\Windows\\Fonts\\Arial.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.EMBEDDED);
            Font f = new iTextSharp.text.Font(GreekFont, 70);

            // Old - Works for English only. No Basefont needed.
            //Font f = new Font(FontFamily.HELVETICA, 50);

            // Initialize a new phrase
            Phrase p = new Phrase(" Α Ρ Χ Ε Ι Ο   Δ Ε Η ", f);

            // Initialize a new PdGstate
            PdfGState gs1 = new PdfGState();

            // Opacity
            gs1.FillOpacity = 0.1F;
    

          

            PdfContentByte over;
            Rectangle pagesize;
            float x, y;

            // Iterate over pages of the pdf
            for (int i = 1; i<= n; i++)
            {
                pagesize = reader.GetPageSize(i);
                x = (pagesize.GetLeft(0) + pagesize.GetRight(0)) / 2;
                y = (pagesize.GetTop(0) + pagesize.GetBottom(0)) / 2;
                over = stamper.GetOverContent(i);
                over.SaveState();
                over.SetGState(gs1);
                ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER, p, x, y, 60);

                over.RestoreState();

            }
            stamper.FormFlattening = true;
            stamper.Close();
        }
        
        /// <summary>
        /// Function: ParsePDF
        /// Description: Searches a pdf for specific words, prints those pages into new pdf.
        /// Input: String (Source), String(Destination), (String) Keyword to look for
        /// Output: None.
        /// Usage: PardePDF("path1", "path2", "keyword)
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dest"></param>
        /// <param name="keyword"></param>
        public static void ParsePDF(String src, String dest, String keyword)
        {
            int pages_found = 0;           
            if (File.Exists(src))
            {
                PdfReader reader = new PdfReader(src);
                ICollection<int> pagesToKeep = new List<int>();

                for (int page = 1; page <= reader.NumberOfPages; page++)
                {

                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);

                    if (currentText.IndexOf(keyword) > 0)
                    {
                        pages_found++;
                        pagesToKeep.Add(page);
                        
                    }
                }

                Document document = new Document();
                PdfCopy copy = new PdfCopy(document, new FileStream(dest, FileMode.Create));
                document.Open();

                foreach (int page in pagesToKeep)
                {
                    PdfImportedPage importedPage = copy.GetImportedPage(reader, page);
                    copy.AddPage(importedPage);
                }

                document.Close();
                reader.Close();
            }
        }

        public static void SplitPDF(String src, String dest, int startPage, int interval)
        {
            List<int> pages = new List<int>();
            if (File.Exists(src))
            {
                PdfReader pdfReader = new PdfReader(src);
                Document document = new Document();
                PdfCopy copy = new PdfCopy(document, new FileStream(dest, FileMode.Create));
                PdfImportedPage importedPage = null;
                document.Open();

                for (int pagenumber = startPage; pagenumber < (startPage + interval); pagenumber++)
                {
                    if (pdfReader.NumberOfPages >= pagenumber)
                    {
                        importedPage = copy.GetImportedPage(pdfReader, pagenumber);
                        copy.AddPage(importedPage);
                    } else
                    {
                        break;
                    }
                }

                document.Close();
                pdfReader.Close();
            }
        }

        public static List<int> CountPDF(String src, String keyword)
        {
            List<int> pages = new List<int>();
            if (File.Exists(src))
            {
                PdfReader pdfReader = new PdfReader(src);
                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

                    string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                    if (currentPageText.Contains(keyword))
                    {
                        pages.Add(page);
                    }
                }
            }
            return pages;
        }













    }
}
/////////////////////////////////////////////////////////
// VS - Rclick on Project 
//    - Add class
//    - Add public static to HardCodedPaths
//
// Usage: HardCodedPaths.ending


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDFappv1
{
    public static class HardCodedPaths
    {
        public static string ending = ".pdf";
        public static string filedump = @"C:\Users\p.doulgeridis\Desktop\watermarks\";
        public static string script_dir = @"C:\Users\p.doulgeridis\Desktop\watermarkscript\";
    }
}


/////////////////////////////////////////
// HOW TO ADD QUIT BUTTON





/// <summary>
        /// QUIT BUTTON CLICK
        /// Function: Quit
        /// Work: Exits the application.
        /// Notes: Can be used in any windows app.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QuitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
/////////////////////////////////////////////////////////
//
// In this example: We use a refresh function, and call it
// from form load event, that is good for scenarios when we 
// want out refresh to be the same as the initial form load.
//
// If we want a more targettted refresh we need to create 
// something separate for the refresh function
//
// Design Side: Nothing, just note names of textboxes
// BackEnd Side: Nothing, see code below.
//






       /// <summary>
        /// Function: Refresh Form
        /// Input: None
        /// Output: None
        /// Work : Performs checks and initially sets fields
        /// 
        /// </summary>
        private void refreshForm()
        {

            // Check if target directory exists and update MainBox
            if (Directory.Exists(HardCodedPaths.filedump))
            {
                MainBox.Text = "Initial Checks: Dump directory - succesful\n";
            }
            else
            {
                MainBox.Text = "Initial Checks unsuccesful: Dump directory missing.\n";
            }

            // Check if script directory exists and update MainBox
            if (Directory.Exists(HardCodedPaths.script_dir))
            {
                MainBox.AppendText("Initial Checks succesful: Script Directory located\n");
                MainBox.AppendText("Ready to process....Select action.");
            }
            else
            {
                MainBox.AppendText("Initial Checks unsuccesful: Script Directory missing\n");
                MainBox.AppendText("Quit and restart application");
            }


            // This works but we dont need it here
            //FileMethods new_file = new FileMethods(@"C:\Users\p.doulgeridis\Desktop\abapabao40.txt");

            //MainBox.AppendText(new_file.File_Path);
            //MainBox.AppendText("Size is: " + new_file.get_file_size().ToString());


        }
        
        
private void Form1_Load(object sender, EventArgs e)
        {
            // Initial Form Load : refreshForm()
            // Refreshform is used on initial form load, 
            // and everytime we want to refresh it.
            // Notes: This is the best way to initially load the form
            // because it combines the functio with the refresh button.
            // 
            refreshForm();
        }
/////////////////////////////////////////////////////////////////
//
//  Design side: ToolBox -> OpenFileDialog1
//               We do not need to change properties/events of OpenFileDialog1
//
//  BackEnd:
//
//  //Set FileDialog parameters
//  this.openFileDialog1.Filter = "PDF FILES (*.txt) |*.pdf";
//  this.openFileDialog1.InitialDirectory = @"C:\Users\p.doulgeridis\Desktop\";
//  this.openFileDialog1.Multiselect = true;
//  this.openFileDialog1.Title = "Select Files for processing";
//  this.openFileDialog1.CheckFileExists = true;
//  this.openFileDialog1.CheckPathExists = true;
//
//
//  //Open File Dialog 
    // Assign selection to result (list)
//    DialogResult result = openFileDialog1.ShowDialog();
//
//// Check if result from Dialog box selection is valid
//            if (result == System.Windows.Forms.DialogResult.OK)
//            {
//                // iterate over pdfs
//                foreach (String file in openFileDialog1.FileNames)
//                {
//
//                    // Initiate a new FileMethod object with the selected pdf
//                    FileMethods new_file = new FileMethods(file);
//
//                    // Construct output filename
//                    //String out_file = Path.Combine(HardCodedPaths.filedump, "Fixed." + new_file.get_file_basename());
//                    String out_file = Path.Combine(PathBox.Text.ToString(), "Fixed." + new_file.get_file_basename());
//                    //MainBox.AppendText(out_file + "\n");
//                    //Console.Write(out_file + "\n");
//
//                    PDFlib.Watermarkpdf(file, out_file);

//                    // Count n.of pdfs processed
//                    counter = counter + 1;
//                    //MainBox.AppendText(file);
//                    //MainBox.AppendText("\n");


//                    // Update Main Box
//                    MainBox.AppendText("Processed: " + new_file.get_file_basename().ToString() + "\n");
//                }
//                //MainBox.AppendText(counter.ToString());
//                CounterBox.Text = (counter.ToString());
               
//            }

//        }



        /// <summary>
        /// WATERMARKING
        /// Function: Watermarking pdf
        /// Input: None, Button click
        /// Output: Void
        /// Work: Opens File Dialog
        ///       Adds watermark to selected files
        ///       Stores output files to directory
        /// Notes: Modify initial directory so it works on all pcs.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            // Update Textboxes
            Opbox.Text = "Watermarking";
            MainBox.Text = "Processing files: .... \n";

            // Set FileDialog parameters
            this.openFileDialog1.Filter = "PDF FILES (*.txt) |*.pdf";
            this.openFileDialog1.InitialDirectory = @"C:\Users\p.doulgeridis\Desktop\";
            this.openFileDialog1.Multiselect = true;
            this.openFileDialog1.Title = "Select Files for processing";
            this.openFileDialog1.CheckFileExists = true;
            this.openFileDialog1.CheckPathExists = true;

            // Initiate File Counter
            Int32 counter = 0;

            // Open File Dialog 
            // Assign selection to result (list)
            DialogResult result = openFileDialog1.ShowDialog();

            // Check if result from Dialog box selection is valid
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // iterate over pdfs
                foreach (String file in openFileDialog1.FileNames)
                {

                    // Initiate a new FileMethod object with the selected pdf
                    FileMethods new_file = new FileMethods(file);

                    // Construct output filename
                    //String out_file = Path.Combine(HardCodedPaths.filedump, "Fixed." + new_file.get_file_basename());
                    String out_file = Path.Combine(PathBox.Text.ToString(), "Fixed." + new_file.get_file_basename());
                    //MainBox.AppendText(out_file + "\n");
                    //Console.Write(out_file + "\n");

                    PDFlib.Watermarkpdf(file, out_file);

                    // Count n.of pdfs processed
                    counter = counter + 1;
                    //MainBox.AppendText(file);
                    //MainBox.AppendText("\n");


                    // Update Main Box
                    MainBox.AppendText("Processed: " + new_file.get_file_basename().ToString() + "\n");
                }
                //MainBox.AppendText(counter.ToString());
                CounterBox.Text = (counter.ToString());
               
            }

        }
/////////////////////////////////////////////////////////////
//
//  Design Side: ToolBox -> Timer
//               Click on Timer - _Tick event + add code
//    
//  BackEnd Side: Add code in Timer_Tick event
//                Add code in form1() for Timer_Tick
//





        public Form1()
        {
            // Default Command that Initializes form
            InitializeComponent();

            // Initialize Timer Tick
            timer1.Enabled = true;
            timer1.Tick += timer1_Tick;

            // Initialize DateBox
            DateBox.Text = DateTime.Now.ToString("dd-MM-yyyy");


            // Initialize OpBox
            Opbox.Text = "Select Operation..";

            // Initialize Instruction Label Test
            InstructionLabel.Text = Instructions.instruction.ToString();

            // Initialize PathBox
            PathBox.Text = "Click to select output path";
        }
        
        
        
        
        /// <summary>
        /// TIMER TICK 
        /// NECESSARY FOR TIMER.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            //label1.Text = DateTime.Now.ToString("HH:mm:ss");
            ////label1.Text = "aaaaa";
            TimeBox.Text = DateTime.Now.ToString("HH:mm:ss");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Button button;
            button = new Button();
            button.Location = new Point(300, 300);
            button.Text = "MyButton";
            button.Size = new Size(70, 70);
            button.UseVisualStyleBackColor = true;

            // We are already in form code, desiggner and form1 coextst
            // we can call on controls
            Controls.Add(button);
            
            // See how its instantiated in .designer
            // 'Controls' is visible from form1
            

        }