【问题标题】:Release lock on image file after using section.AddImage() in MigraDoc-WPF在 MigraDoc-WPF 中使用 section.AddImage() 后释放图像文件的锁定
【发布时间】:2014-11-05 15:06:41
【问题描述】:

我有以下代码生成报告PDF,上传然后删除生成时使用的临时图片:

// Generate document and then add a section with an image
var document = new Document {Info = {Title = "Results"}};
var section = document.AddSection();
var logo = section.AddImage(logoPath);

// Render the PDF
const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument(); // This is the line which locks the files

// Save the PDF to a memory stream and upload it to azure blob storage
var reportPath = "";
using (var stream = new MemoryStream())
{
    pdfRenderer.Save(stream, false);
    reportPath = UploadBlob("reports", "Report.pdf", stream);
}

// Delete the local copy of the logo - this is where the exception occurs
Directory.Delete(Directory.GetParent(logoPath).ToString(), true);

当我尝试删除图片所在目录时,出现以下异常:

 An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code

 Additional information: The process cannot access the file 'Capture.PNG' because it is being used by another process.

我已经通过代码进行了调试,以确保在调用 pdfRenderer.RenderDocument() 之前可以访问该文件,如代码 cmets 中所述。

PdfDocumentRenderer 类没有 close 或 dispose 方法,它没有实现 IDisposable,所以我不能使用 using 块。

如何解除对文件的锁定?

【问题讨论】:

  • 你有没有试过先google? BitmapCacheOption.OnLoad 声称是here 的解决方案(仅供参考:我不知道什么是 Migradoc)。
  • 我已经彻底谷歌了,是的。 MigraDoc 是一个(我相信)与 PDFSharp 一起生成 PDF 的库。我使用 nuget 包管理器掌握了它,所以我认为我无法深入研究源代码来更改任何构造函数。对位图缓存的更改无济于事,因为我无法控制位图,AddImage() 函数仅接受图像的路径,因此该函数中发生的事情目前对我来说是一个黑匣子。

标签: c# wpf asp.net-mvc-4 pdfsharp migradoc


【解决方案1】:

我修复了修改 PdfSharp.Drawing\XImage.cs 的“BitmapImage lock file”错误,如下所示: 替换第 114 行:

  this.wpfImage = new BitmapImage(new Uri(path));  // AGHACK

  BitmapImage imgTemp = new BitmapImage();
  imgTemp.BeginInit();
  imgTemp.CacheOption = BitmapCacheOption.OnLoad;
  imgTemp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
  imgTemp.UriSource = new Uri(path);
  imgTemp.EndInit();
  this.wpfImage = imgTemp;

它对我有用。

【讨论】:

    【解决方案2】:

    尝试使用“PDFsharp-MigraDoc-GDI”包而不是“PDFsharp-MigraDoc-WPF”包。

    顺便说一句:如果您想在“黑匣子”中进行更改,您可以下载完整的源代码。
    http://pdfsharp.codeplex.com/releases

    【讨论】:

    • 我无法使用 GDI 包,因为我的应用程序在 Azure 云上运行,我收到以下错误:“内部错误。无法检索字体数据。”。看起来我唯一的解决方案可能是对源代码进行自己的更改?如果这是一个简单的更改,为什么在 GDI 版本中没有修复它?
    • @Starky:这不是 GDI 构建的问题,而是 WPF 的问题。我们尚未在 Nuget 上发布 WPF 版本,但我们目前计划在今年晚些时候在那里发布它 - 并且将包含修复程序。如需快速修复,请自行进行更改。
    猜你喜欢
    • 2011-09-28
    • 2011-10-30
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多