private void btnSacnToPDF_Click(object sender, EventArgs e)
{
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
try
{
List<string> devices = YGH.WIAScanner.GetDevices();
if (devices.Count == 0)
{
throw new Exception("devices == 0");
}
List<System.Drawing.Image> images = YGH.WIAScanner.Scan(devices[0].Split('|')[0]);
if (images.Count == 0)
{
throw new Exception("images == 0");
}
string fileName;
// 方法1: 寫死暫存檔案名
fileName = @"C:\temp\scan.pdf";
// 方法2: 利用 System.IO.Path.GetTempPath() 及 Guid.NewGuid() 取得暫存檔案名
//fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";
// 方法3: 使用 System.IO.Path.GetTempFileName() 建立暫存檔案(副檔名為 .TMP)
//fileName = System.IO.Path.GetTempFileName();
PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
document.Open();
foreach (System.Drawing.Image image in images)
{
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageToByteArray(image));
// 方法1: 跟 HP 內建掃瞄程式相比有明顯差異
//img.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
// 方法2: 跟 HP 內建掃瞄程式相比差異較小
img.SetAbsolutePosition(0, 0);
img.ScalePercent(72.0F / img.DpiX * 100);
// 方法3: 跟 HP 內建掃瞄程式相比有明顯差異
//img.SetAbsolutePosition(0, 0);
//img.ScaleAbsoluteWidth(document.PageSize.Width);
//img.ScaleAbsoluteHeight(document.PageSize.Height);
document.Add(img);
document.NewPage();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
document.Close();
}
}
/// <summary>
/// C# Image to Byte Array and Byte Array to Image Converter Class
/// http://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
/// </summary>
/// <param name="imageIn"></param>
/// <returns></returns>
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
/// <summary>
/// C# Image to Byte Array and Byte Array to Image Converter Class
/// http://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
/// </summary>
/// <param name="byteArrayIn"></param>
/// <returns></returns>
public System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
return returnImage;
}
參考資料[1] WIA Scanner in C# Windows Forms
[2] C# Image to Byte Array and Byte Array to Image Converter Class
沒有留言:
張貼留言