繁体   English   中英

转换tiff到pdf期间另一个进程使用的c#文件

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

我没有。 tiff文件/图像,现在我想转换单个PDF ...

我为这个编写了代码并且工作正常。 但问题是,我将图像存储在临时文件夹中。 并希望在PDF生成后删除这些文件。它给了我错误。 “文件被另一个进程使用”

我的代码是:

 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();

请告诉我,我做错了什么....谢谢

这应该在循环而不是在外面:

bm.Dispose();

看起来我之前遇到过同样的问题。 原因是当您加载图像以创建pdf时,您不会在使用后释放资源。 使用以下代码加载使用图像。

private static BitmapImage GetBitmapImage(string imageFilePath)
{
    BitmapImage bmpImage = new BitmapImage();
    bmpImage.BeginInit();
    Uri uri = new Uri(imageFilePath);
    bmpImage.UriSource = uri;
    bmpImage.CacheOption = BitmapCacheOption.OnLoad;
    bmpImage.EndInit();
    return bmpImage;
}

这将自动释放您使用后使用的资源(图像).. :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM