title: save text highlighted in pdf file using C#
body: <p>I built a windows form application that opens any text file (even pdf using iTextSharp Dll) and view its contents in a rich tex box, a search field where i can search for a certain pattern, all possible matches to be highlighted in "Gold" color. I created a save button.</p>
  
  <ol>
  <li>how can i overwrite the text file (.doc) with the text highlighted
  by retaining the text format?</li>
  <li>how can i do the same step with pdf?
  (since pdf will crash after overwriting the file)</li>
  </ol>
  
  <p>The code:</p>
  
  <pre><code>private void open_Click(object sender, EventArgs e)
  {
      if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
      {
          tb.Clear();
          label1.Text = openFileDialog1.FileName;
  
          if (label1.Text.Contains(".pdf"))
          {
              // create a reader (constructor overloaded for path to local file or URL)
              string location = openFileDialog1.FileName;
              PdfReader reader = new PdfReader(location);
  
              StringBuilder text = new StringBuilder();
  
              for (int page = 1; page &lt;= reader.NumberOfPages; page++)
              {
                  ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                  string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);
  
                  currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                  text.Append(currentText);
                  reader.Close();
              }
              tb.Text = text.ToString();
          }
          else 
          {
              tb.Text = File.ReadAllText(label1.Text);
          }
  
      }
  }
  
  private void save_Click(object sender, EventArgs e)
  {
      SaveFileDialog saveFile1 = new SaveFileDialog();
  
      if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
      {
          File.WriteAllText(saveFileDialog1.FileName, tb.Text);
      }
  }
  
  private void search_Click(object sender, EventArgs e)
  {
      int index = 0;
      while (index &lt; tb.Text.LastIndexOf(sb.Text))
      {
          tb.Find(sb.Text,index,tb.TextLength,RichTextBoxFinds.None);
          tb.SelectionBackColor = Color.Gold;
          index = tb.Text.IndexOf(sb.Text, index) + 1;
      }
  }
  </code></pre>
  
  <p>Thanks in advance!</p>