在使用MigraDoc-WPF中的section.AddImage()后释放图像文件锁定

4
我有以下代码用于生成报告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()之前,我已经通过代码进行了调试,以确保文件是可访问的,正如代码注释中所述。

PdfDocumentRenderer类没有close或dispose方法,也没有实现IDisposable接口,因此我无法使用using块。

我该如何释放文件上的锁定?


你有先尝试过谷歌搜索吗?在这里提到了 BitmapCacheOption.OnLoad 可能是一个解决方案(顺便说一下:我不知道什么是 Migradoc)。 - Sinatr
我已经彻底谷歌过了。MigraDoc是一个库,它(我相信)与PDFSharp一起工作以生成PDF。我使用nuget包管理器获得了它,因此我认为我无法深入源代码更改任何构造函数。位图缓存的更改没有帮助,因为我无法控制位图,AddImage()函数仅接受图像路径,因此该函数内部发生的情况对我来说是一个黑盒子。 - Alasdair Stark
2个回答

6
我已经修复了“BitmapImage锁文件”错误,修改PdfSharp.Drawing\XImage.cs如下: 替换第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;

它对我起作用了。


0

尝试使用“PDFsharp-MigraDoc-GDI”包代替“PDFsharp-MigraDoc-WPF”包。

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


1
我无法使用GDI包,因为我的应用程序正在Azure云上运行,并且出现以下错误:“内部错误。无法检索字体数据。”看起来我的唯一解决方案可能是对源代码进行自己的更改?如果这是一个简单的更改,为什么GDI版本没有修复这个问题呢? - Alasdair Stark
@Starky:这不是GDI构建的问题,而是WPF的问题。我们还没有在Nuget上发布WPF构建版本,但我们计划在今年晚些时候发布它,并且修复将被包含在其中。如果需要快速修复,请自行进行更改。 - I liked the old Stack Overflow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接