我有以下代码生成报告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块。
如何解除对文件的锁定?
答案 0 :(得分: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;
它对我有用。
答案 1 :(得分:0)
尝试使用" PDFsharp-MigraDoc-GDI"包而不是" PDFsharp-MigraDoc-WPF"封装
顺便说一句:如果您想在"黑框"中进行更改,可以下载完整的来源。
http://pdfsharp.codeplex.com/releases