3

私は全くない。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();

plzは私に教えてください、私が作った何が間違っているのか....ありがとう

4

2 に答える 2

2

これは、外側ではなくループ内にある必要があります。

bm.Dispose();
于 2013-07-29T12:15:36.887 に答える
0

以前も同じ問題があったようです。その理由は、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;
}

これにより、使用後に使用しているリソース (画像) が自動的に解放されます..:)

于 2013-07-29T12:15:33.027 に答える