woensdag 20 januari 2010

Drag & Drop

Basic drag & drop is pretty easy to accomplish in WPF. For starters you should add a MouseMove handler to the object you want to drag around. When you detect the left mouse button is pressed you initiate the drag and pass the source and data to the drag & drop method.

     private void border_PreviewMouseMove(object sender, MouseEventArgs e)
{
Border border = (Border)sender;
if (e.LeftButton == MouseButtonState.Pressed)
{
DragDropEffects dropEffect = DragDrop.DoDragDrop(border, border.Child, DragDropEffects.Move);
}
}

Any object you want to drop another object inside needs to have the 'AllowDrop' property set to true. When that's done you add a handler to handle the drop event. Inside you should check the type of the data being dropped and if it is what you expect then you can deal with it accordingly. In this case the Border object had an Image object set as its child.

     private void grdPdf_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Image)))
{
Image image = (Image)e.Data.GetData(typeof(Image));
}
}

OCR with Microsoft Office

If you have Microsoft Office available on the platform where you're developing (for) you can accomplish OCR functionality by taking advantage of the Office dll's. All you need to do for the following code to work is to add a reference to the Microsoft Office Document Imaging Library in the COM tab.

Be aware that this library might not have been installed along with the Office apps, but you can modify your installation in the control panel to include this library.

All you have to do here is create a document from the image file you wish to analyze and select a language. You can then loop through the recognized words in the layout object of the image.

              MODI.Document doc = new MODI.Document();
doc.Create(filename);

doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

MODI.Image image = (MODI.Image)doc.Images[0];
MODI.Layout layout = image.Layout;

string text = "";
for (int j = 0; j < layout.Words.Count; j++)
{
MODI.Word word = (MODI.Word)layout.Words[j];
text += " " + word.Text;
}
doc.Close(false);

Convert images to pdf

Using the Open Source library PDFsharp converting images to a PDF document becomes child's play. Just create the document, add a page, import an image and save the document to disk.

Plus PDFsharp comes with a license free of any restrictions so you can reuse it in any program for whatever purpose you like!

                OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog().Value)
{
PdfDocument pdfDoc = new PdfDocument();
pdfDoc.Pages.Add(new PdfPage());
XGraphics xGraphics = XGraphics.FromPdfPage(pdfDoc.Pages[0]);
XImage xImage = XImage.FromFile(openFile.FileName);

xGraphics.DrawImage(xImage, 0, 0);
pdfDoc.Save(@"C:\test.pdf");
pdfDoc.Close();
}