Ala*_*ark 4 c# wpf pdfsharp migradoc asp.net-mvc-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);
Run Code Online (Sandbox Code Playgroud)
当我尝试删除图像的目录时,会引发以下异常:
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.
Run Code Online (Sandbox Code Playgroud)
我已经通过代码进行了调试,以确保在调用pdfRenderer.RenderDocument()之前可以访问该文件,如代码注释中所述.
PdfDocumentRenderer类没有close或dispose方法,它没有实现IDisposable,所以我不能使用using块.
如何释放文件上的锁?
我修复了修改PdfSharp.Drawing\XImage.cs的"BitmapImage锁定文件"错误,如下所示:替换第114行:
this.wpfImage = new BitmapImage(new Uri(path)); // AGHACK
Run Code Online (Sandbox Code Playgroud)
同
BitmapImage imgTemp = new BitmapImage();
imgTemp.BeginInit();
imgTemp.CacheOption = BitmapCacheOption.OnLoad;
imgTemp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
imgTemp.UriSource = new Uri(path);
imgTemp.EndInit();
this.wpfImage = imgTemp;
Run Code Online (Sandbox Code Playgroud)
它对我有用.