【问题标题】:c# files used by another process during convert tiff to pdfc#将tiff转换为pdf期间另一个进程使用的文件
【发布时间】:2013-07-29 05:15:51
【问题描述】:

我没有。 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();

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

【问题讨论】:

    标签: c# pdf converter tiff


    【解决方案1】:

    这应该在循环中而不是外部:

    bm.Dispose();
    

    【讨论】:

    • 为避免这些错误,您可以使用using 语句,这样您的实例将在使用后自动处理。
    【解决方案2】:

    看起来我以前也遇到过同样的问题。原因是当您加载用于创建 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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      相关资源
      最近更新 更多