我正在使用以下命令将 TIFF 文件插入 PDF 中 PDFSharp. 。该过程工作正常,但它在 TIFF 文件上留下了锁。TIFF 文件位于 SMB 共享上。我使用 WPF 版本,因为 GDI 版本不支持 CMYK TIFF。

var output = new PdfDocument();
var input = PdfReader.Open(template_path, PdfDocumentOpenMode.Import);

var page = input.Pages[0];
output.AddPage(page);
page = output.Pages[0];

var gfx = XGraphics.FromPdfPage(page);

var image = XImage.FromFile(tiff_path);

gfx.DrawImage(image, 500, 200, 400, 400);

output.Save(destination_path);
output.Close();

更新:只需执行此操作即可锁定 TIFF。没有打开任何文档或 XGraphics 或任何东西。

 using (var image = XImage.FromFile(path))
 {}

更新:这是可行的,也是我现在要做的。

using (var fsImage = File.Open(tiffPath, FileMode.Open, FileAccess.Read, FileShare.None))
{
    var bitmapSource = new BitmapImage();
    bitmapSource.BeginInit();
    bitmapSource.StreamSource = fsImage;
    bitmapSource.EndInit();

    using (var image = XImage.FromBitmapSource(bitmapSource))
    {

    }
}

不雅的是,这段令人讨厌的代码也有效:-)

using (var image = XImage.FromFile(tiffPath))
{

}
GC.Collect();
有帮助吗?

解决方案

与WPF BitmapSource, ,对底层流没有确定性的处理,因此只要有引用,您就可能最终得到锁。

You --> XImage --> BitmapSource --> Stream

如果您调用 dispose XImage, ,它将在 BitmapSource, ,这将允许它在 GC 需要时完成。

您可以通过提供流代替路径并显式关闭文件来控制何时关闭文件。过早这样做会导致异常 BitmapSource, 但是,请确保您没有使用 BitmapSource 关闭流后。

using (var fsImage = File.Open(tiff_path, FileMode.Open, FileAccess.Read, FileShare.None))
{
    var output = new PdfDocument();
    var input = PdfReader.Open(template_path, PdfDocumentOpenMode.Import);

    var page = input.Pages[0];
    output.AddPage(page);
    page = output.Pages[0];

    var gfx = XGraphics.FromPdfPage(page);

    var bitmapSource = new BitmapImage();
    bitmapSource.BeginInit();
    bitmapSource.StreamSource = fsImage;
    bitmapSource.EndInit();
    using (var image = XImage.FromBitmapSource(bitmapSource))
    {
        gfx.DrawImage(image, 500, 200, 400, 400);
    }

    output.Save(destination_path);
    output.Close();
}

如果您的图像足够小,您可以跳过流并仅使用 BitmapCacheOptionOnLoad 打开后关闭源,但这会导致整个图像被加载到内存中。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top