这是我用来扫描文档的方法:
internal static string EscanearDocumento(string path, PdfDocument doc)
{
int cont = 0;
WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
try
{
ImageFile imageFile = wiaDiag.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.TextIntent, WiaImageBias.MaximizeQuality, "{00000000-0000-0000-0000-000000000000}", true, true, false);
while (File.Exists(path + cont + ".pdf"))
{
cont++;
}
path = path + cont + ".pdf";
try
{
byte[] imagenEnBytes = (byte[])imageFile.FileData.get_BinaryData();
using (MemoryStream ms = new MemoryStream(imagenEnBytes))
{
XImage imagen = XImage.FromStream(ms);
PdfPage page = doc.AddPage();
page.Orientation = PageOrientation.Portrait;
XGraphics graficos = XGraphics.FromPdfPage(page);
graficos.DrawImage(imagen, 0, 0);
}
} catch(NullReferenceException)
{
MessageBox.Show("Error");
}
} catch (COMException er) {
excepciones(er);
}
return path;
}
我在我的主类中使用它,通过这种方法将文档插入数据库:
private void AgregarDocumentos_Click(object sender, EventArgs e)
{
string text1= TextBox1.Text;
string text2= TextBox2.Text;
string query = "SELECT * FROM tableName WHERE p ='" + text1 + "'AND n ='" + text2+ "'AND documento is not null";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count == 0)
{
Boolean found = false;
try
{
DeviceManager manejadorDisp = new DeviceManager();
DeviceInfo escanerDisponible = null;
for (int i = 1; i <= manejadorDisp.DeviceInfos.Count; i++)
{
if (manejadorDisp.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType)
{
continue;
}
else
{
found = true;
string path = @"C:";
escanerDisponible = manejadorDisp.DeviceInfos[i];
Device dispositivo = escanerDisponible.Connect();
Item objetoEscaneado = dispositivo.Items[1];
PdfDocument doc = new PdfDocument();
try
{
path = Escaner.EscanearDocumento(path, doc);
try
{
DialogResult dialogResult = DialogResult.Yes;
while (dialogResult == DialogResult.Yes)
{
dialogResult = MessageBox.Show("¿Quiere escanear un documento?", "", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Escaner.EscanearDocumento(path, doc);
doc.Close();
}
else if (dialogResult == DialogResult.No)
{
doc.Save(path);
continue;
}
}
var leer = File.ReadAllBytes(path);
SqlCommand inserta = new SqlCommand("UPDATE tableName SET n = n, p = p, ni = ni, documento = @documento WHERE p ='" + text1 + "'AND n ='" + text2 + "';", con);
inserta.Parameters.AddWithValue("@documento", read);
con.Open();
inserta.ExecuteNonQuery();
con.Close();
Process proceso = new Process();
proceso.StartInfo = new ProcessStartInfo(path)
{
UseShellExecute = true
};
proceso.Start();
MessageBox.Show("Inserted");
break;
}
catch (InvalidOperationException)
{
MessageBox.Show("Cannot save the file");
}
}
catch (FileNotFoundException)
{
MessageBox.Show("Not found");
}
}
}
}
catch (COMException er)
{
Escaner.excepciones(er);
}
if(!found)
{
MessageBox.Show("Not found");
}
}
else
{
MessageBox.Show("");
}
}