private void btnFindText_Click(object sender, EventArgs e)
{
if (pdfFileTextBox.Text.Trim().Equals(String.Empty))
{
MessageBox.Show("Please choose a PDF file to search", "Choose PDF file", MessageBoxButtons.OK);
return;
}
if (textToFindTextBox.Text.Trim().Equals(String.Empty))
{
MessageBox.Show("Please enter the text to find", "Text to Find", MessageBoxButtons.OK);
return;
}
// the pdf file to search
string pdfFileName = pdfFileTextBox.Text.Trim();
// start page number
int startPageNumber = int.Parse(textBoxStartPage.Text.Trim());
// end page number
// when it is 0 the extraction will continue up to the end of document
int endPageNumber = 0;
if (textBoxEndPage.Text.Trim() != String.Empty)
endPageNumber = int.Parse(textBoxEndPage.Text.Trim());
Cursor = Cursors.WaitCursor;
string outputFileName = System.IO.Path.Combine(Application.StartupPath, @"DemoFiles\Output",
System.IO.Path.GetFileNameWithoutExtension(pdfFileName) + "_Highlighted.pdf");
Document pdfDocument = null;
try
{
// create the PDF to Text converter
PdfToTextConverter pdfToTextConverter = new PdfToTextConverter();
pdfToTextConverter.LicenseKey = "C4WUhJaRhJSEkoqUhJeVipWWip2dnZ2ElA==";
// search text in PDF
FindTextLocation[] findTextLocations = pdfToTextConverter.FindText(pdfFileName, textToFindTextBox.Text,
startPageNumber, endPageNumber, cbCaseSensitive.Checked, cbWholeWord.Checked);
// open the PDF to search in PDF library
pdfDocument = new Document(pdfFileName);
// highlight the found text in PDF
foreach (FindTextLocation findTextLocation in findTextLocations)
{
RectangleElement highlightRectangle = new RectangleElement(findTextLocation.X, findTextLocation.Y,
findTextLocation.Width, findTextLocation.Height);
highlightRectangle.BackColor = Color.Yellow;
highlightRectangle.Opacity = 50;
pdfDocument.Pages[findTextLocation.PageNumber - 1].AddElement(highlightRectangle);
}
// Save the modified PDF document in a memory buffer
byte[] outPdfBuffer = pdfDocument.Save();
// Write the memory buffer in a PDF file
System.IO.File.WriteAllBytes(outputFileName, outPdfBuffer);
}
catch (Exception ex)
{
// The search failed
MessageBox.Show(String.Format("An error occurred. {0}", ex.Message), "Error");
return;
}
finally
{
// Close the PDF document
if (pdfDocument != null)
pdfDocument.Close();
Cursor = Cursors.Arrow;
}
// Open the modified PDF document in default PDF viewer
try
{
System.Diagnostics.Process.Start(outputFileName);
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Cannot open highlighted PDF file '{0}'. {1}", outputFileName, ex.Message));
}
}