private void Import()
        {
            var ofd = new OpenFileDialog
            {
                Multiselect     = true,
                CheckFileExists = true,
                DefaultExt      = "jpg"
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                foreach (var fileName in ofd.FileNames.OrderBy(x => x))
                {
                    // TODO: Run in thread, and show a dialog (just like exporting)
                    // Need to provide count somehow (progress callback). count = # files or # pages
                    try
                    {
                        Bitmap aImportar;
                        try
                        {
                            aImportar = new Bitmap(fileName);
                        }
                        catch (Exception e)
                        {
                            //Log.ErrorException("Error importing image: " + filePath, e);
                            // Handle and notify the user outside the method so that errors importing multiple files can be aggregated
                            throw;
                        }
                        using (aImportar)
                        {
                            for (int i = 0; i < aImportar.GetFrameCount(FrameDimension.Page); ++i)
                            {
                                aImportar.SelectActiveFrame(FrameDimension.Page, i);

                                Scan.Images.IScannedImage imagen = new Scan.Images.ScannedImage((Bitmap)aImportar.Clone(), ScanBitDepth.C24Bit, false);
                                imagenesCapturadas[iActualTipoDocumento].Images.Add(imagen);
                                Application.DoEvents();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            tblImagenes.UpdateImages(imagenesCapturadas[iActualTipoDocumento].Images);
        }
        private void desdePDFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                Multiselect     = false,
                CheckFileExists = true,
                DefaultExt      = "pdf",
                Filter          = "Archivos PDF (*.pdf)|*.pdf",
                Title           = "Abrir Archvivo PDF"
            };

            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            frmPreview = new ScanPreview();
            frmPreview.StartPosition = FormStartPosition.CenterScreen;
            frmPreview.tblPreview.changeSizeThumb(new Size(96, 96));
            frmPreview.Show();

            PdfiumViewer.IPdfDocument documento;

            documento = PdfiumViewer.PdfDocument.Load(ofd.FileName);

            frmPrincipal.Instance.TSPBGeneral.Visible = true;

            for (int i = 0; i < documento.PageCount; i++)
            {
                using (var image = documento.Render(i, (int)(documento.PageSizes[i].Width * 2.5), (int)(documento.PageSizes[i].Height * 2.5), 150, 150, true))
                {
                    Scan.Images.IScannedImage imagen1 = new Scan.Images.ScannedImage(new Bitmap(image), ScanBitDepth.C24Bit, false);
                    imagenesCapturadas[iActualTipoDocumento].Images.Add(imagen1);
                    frmPreview.tblPreview.AppendImage(imagen1);
                    Application.DoEvents();
                }
            }

            tblImagenes.UpdateImages(imagenesCapturadas[iActualTipoDocumento].Images);
            frmPrincipal.Instance.TSPBGeneral.Visible = false;

            if (frmPreview != null)
            {
                frmPreview.Close();
                frmPreview.Dispose();
            }
        }
        void cargarImagenes(String idExpediente, String idDocumento)
        {
            Cursor            = System.Windows.Forms.Cursors.AppStarting;
            PBGeneral.Visible = true;

            parametros = "|V2=" + idExpediente + "|V6=" + idDocumento + "|PA=" + txtPage.Text.ToString() + "|RP=" + cboRecords.SelectedItem.ToString() + "|";
            validar    = "41";
            Datos      = Acceso.ivkProcedimiento("sp_Datos_Documentos", validar, parametros, Clases.vGlobales.conexion, null);

            if (Datos.bOk)
            {
                if (Datos.ds.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show("No existen imagenes");
                    if (Convert.ToInt16(txtPage.Text) > 1)
                    {
                        this.txtPage.TextChanged -= this.txtPage_TextChanged;
                        this.txtPage.Text         = (Convert.ToInt16(txtPage.Text) - 1).ToString();
                        this.txtPage.TextChanged += this.txtPage_TextChanged;
                    }
                    Cursor            = System.Windows.Forms.Cursors.Default;
                    PBGeneral.Visible = false;
                    return;
                }

                this.totalPag = Convert.ToInt16(Datos.ds.Tables[1].Rows[0][0].ToString());

                //Borrar imagenes actuales
                tblImagenes.Clear();
                imagenesDB.Images.Clear();

                //Se Cargan las Imagenes
                foreach (DataRow r in Datos.ds.Tables[0].Rows)
                {
                    this.BeginInvoke(new Action <DataRow>((rr) =>
                    {
                        IScannedImage imagen = new Scan.Images.ScannedImage(rr["Imagen"].ToString(), ScanBitDepth.C24Bit, false);
                        imagen.Tag           = rr["idUnicoDocumento"].ToString();
                        imagenesDB.Images.Add(imagen);
                        tblImagenes.AppendImage(imagen);
                    }), r);

                    Application.DoEvents();
                }
            }

            if (Datos.ds.Tables[0].Rows.Count > 0)
            {
                ((frmPrincipal)this.MdiParent).PanelExportar.Enabled = true;
            }
            else
            {
                ((frmPrincipal)this.MdiParent).PanelExportar.Enabled = false;
            }

            updateToolBar();

            Cursor            = System.Windows.Forms.Cursors.Default;
            PBGeneral.Visible = false;

            this.ShowNotify("Proceso finalizado", "Carga de imagenes completada", ToolTipIcon.Info, 2000);
        }
        private void SetupTwain()
        {
            var appId = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetEntryAssembly());

            _twain = new TwainSession(appId);
            _twain.StateChanged += (s, e) =>
            {
                PlatformInfo.Current.Log.Info("State changed to " + _twain.State + " on thread " + Thread.CurrentThread.ManagedThreadId);
            };
            _twain.TransferError += (s, e) =>
            {
                PlatformInfo.Current.Log.Info("Got xfer error on thread " + Thread.CurrentThread.ManagedThreadId);
            };

            _twain.DataTransferred += (s, e) =>
            {
                PlatformInfo.Current.Log.Info("Transferred data event on thread " + Thread.CurrentThread.ManagedThreadId);

                // example on getting ext image info
                var infos = e.GetExtImageInfo(ExtendedImageInfo.Camera).Where(it => it.ReturnCode == ReturnCode.Success);
                foreach (var it in infos)
                {
                    var values = it.ReadValues();
                    PlatformInfo.Current.Log.Info(string.Format("{0} = {1}", it.InfoID, values.FirstOrDefault()));
                    break;
                }

                // handle image data
                Image img = null;
                if (e.NativeData != IntPtr.Zero)
                {
                    var stream = e.GetNativeImageStream();
                    if (stream != null)
                    {
                        img = Image.FromStream(stream);
                    }
                }
                else if (!string.IsNullOrEmpty(e.FileDataPath))
                {
                    img = new Bitmap(e.FileDataPath);
                }
                if (img != null)
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        Scan.Images.IScannedImage imagen = new Scan.Images.ScannedImage(new Bitmap(img), ScanBitDepth.C24Bit, false);
                        imagenesCapturadas.Images.Add(imagen);
                        frmPreview.tblPreview.AppendImage(imagen);
                    }));
                }
            };

            _twain.SourceDisabled += (s, e) =>
            {
                PlatformInfo.Current.Log.Info("Source disabled event on thread " + Thread.CurrentThread.ManagedThreadId);
                this.BeginInvoke(new Action(() =>
                {
                    //Se detuvo el proceso de Digitalizacion.
                    //Poner controles para digitalizar de nuevo.

                    btnDigitalizar.Enabled = true;

                    if (frmPreview != null)
                    {
                        frmPreview.Close();
                        frmPreview.Dispose();
                    }

                    tblImagenes.UpdateImages(imagenesCapturadas.Images);
                    LoadSourceCaps();
                }));
            };
            _twain.TransferReady += (s, e) =>
            {
                PlatformInfo.Current.Log.Info("Transferr ready event on thread " + Thread.CurrentThread.ManagedThreadId);
                e.CancelAll = _stopScan;
            };

            // either set sync context and don't worry about threads during events,
            // or don't and use control.invoke during the events yourself
            PlatformInfo.Current.Log.Info("Setup thread = " + Thread.CurrentThread.ManagedThreadId);
            _twain.SynchronizationContext = SynchronizationContext.Current;
            if (_twain.State < 3)
            {
                // use this for internal msg loop
                _twain.Open();
                // use this to hook into current app loop
                //_twain.Open(new WindowsFormsMessageLoopHook(this.Handle));
            }
        }