【发布时间】: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