Monday, May 9, 2011

TIFFtoPDF conversion - Image Bitmap File Lock Problem - Resolved



   string[] files = Directory.GetFiles(faxpath, "*.tif");
            foreach (string infilename in files)
            {
                PdfDocument document = new PdfDocument();                
                StreamReader imgstreamer = new StreamReader(infilename);                
                Bitmap bm = new Bitmap(imgstreamer.BaseStream);
                int total = bm.GetFrameCount(FrameDimension.Page);                
                _logger.Log("TIFtoPDFConversion", LogEntryType.Debug, "Converting TIF File: " + infilename);
                for (Int32 k = 0; k < total; k++)
                {
                    Bitmap bm2 = new Bitmap(infilename);
                    bm2.SelectActiveFrame(FrameDimension.Page, k);
                    XImage image = XImage.FromGdiPlusImage(bm2);
                    PdfPage page1 = document.AddPage();

                    // Get Image width, Height and Resolution and Set output document Width and Height in Inches
                    page1.Width = XUnit.FromInch(image.PixelWidth / image.HorizontalResolution);
                    page1.Height = XUnit.FromInch(image.PixelHeight / image.VerticalResolution);
                    XGraphics gfx = XGraphics.FromPdfPage(page1, XGraphicsPdfPageOptions.Append);
                    gfx.DrawImage(image, 0, 0);
                    gfx.Dispose();
                    image.Dispose();
                    page1.Close();
                    bm2.Dispose();
                }
                string pdffilename = infilename.Substring(0, infilename.ToLower().LastIndexOf(".tif") - 1) + ".pdf";
                _logger.Log("TIFtoPDFConversion", LogEntryType.Debug, "Completed Converting TIF File: " + infilename);
                // Save the PDF
                document.Save(pdffilename);
                imgstreamer.Close();
            }       


So Simple as that. Add pdfsharp in the reference nothing else to install.
Pdfsharp can be obtained from PDFSharp.

No comments: