Thursday 30 June 2011

Scanning to PDF using .NET

I had a request recently to modify a .NET application I wrote years ago. The application was scanning letters and store them in SQL database linked with specific record. The new requirement was to allow saving these scanned documents as Acrobat Reader (.pdf) files.

First time I used iText API - http://www.itextpdf.com/itext.php

After I scan the document I save it as pdf like this:

public static bool SavePDFAs(string picname, IntPtr bminfo, IntPtr pixdat)
        {
            SaveFileDialog sd = new SaveFileDialog();

            sd.FileName = picname;
            sd.Title = "Save file as...";
            sd.Filter = "PDF file (*.pdf)|*.pdf";
            sd.FilterIndex = 1;
            if (sd.ShowDialog() != DialogResult.OK)
                return false;
            
            Document doc = new Document(PageSize.A4);

            try
            {
                FileStream PDFfs = new FileStream(sd.FileName, FileMode.Create); 

                PdfWriter.GetInstance(doc, PDFfs);

                doc.Open();

                Bitmap bmp = BitmapFromDIB(bminfo, pixdat);
                
                bmp.SetResolution(300, 300);

                byte[] imageBytes;

                using (MemoryStream ms = new MemoryStream())
                {
                    // Convert Image to byte[]
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    imageBytes = ms.ToArray();
                }

                bmp.Dispose();

                iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(imageBytes);
                
                png.ScalePercent(24f);
                png.SetAbsolutePosition(0, 0);

                doc.Add(png);
            }
            catch (DocumentException dex)
            {
                MessageBox.Show(dex.Message);
            }
            catch (IOException ioex)
            {
                MessageBox.Show(ioex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                doc.Close();
            }

            return true;
        }

No comments: