Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# files used by another process during convert tiff to pdf

i have no. of tiff files/images, now i want to convert on single PDF...

i wrote code for this one and it's work fine. but issue is, i am storing images on temp folder. and want to delete those files after PDF generate.and it's giving me error. "Files is used by another process"

my code is:

 string RootDirPath = ConfigurationManager.AppSettings["RootDirPath"].ToString();
            string PDFDirPath = ConfigurationManager.AppSettings["PDFDirPath"].ToString();
            string TmpFolderpath = System.DateTime.Now.ToString("d").Replace('/', '_');


            // creation of the document with a certain size and certain margins
            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

            // creation of the different writers
            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream((PDFDirPath + PDFName + ".pdf"), System.IO.FileMode.Create));

            // load the tiff image and count the total images

            DirectoryInfo RootDir = new DirectoryInfo(RootDirPath + TmpFolderpath);
            FileInfo[] files = RootDir.GetFiles();

            System.Drawing.Bitmap bm = null;

            document.Open();
            for (int i = 0; i < files.Count(); i++)
            {
                bm = new System.Drawing.Bitmap(RootDirPath + TmpFolderpath + "/" + files[i].Name);

                iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);

                img.ScalePercent(72f / img.DpiX * 100);
                img.SetAbsolutePosition(0, 0);
                cb.AddImage(img);


            }
            document.Close();
            writer.Close();

            bm.Dispose();

plz let me know, what's wrong i made....Thanks

like image 872
Kvadiyatar Avatar asked Jan 27 '26 11:01

Kvadiyatar


1 Answers

This should be in the loop and not outside:

bm.Dispose();
like image 56
glautrou Avatar answered Jan 30 '26 01:01

glautrou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!