将PDF从内存加载到telerik:RadPdfViewer

Joe*_*oel 5 c# database pdf wpf telerik

我有一个PDF文件存储在数据库中作为字节数组.我正在从我的数据库中读取PDF字节数组回到我的应用程序中.

现在,我正在尝试使用RadPdfViewer显示PDF但它无法正常工作.

这是我的代码:

    byte[] pdfAsByteArray= File.ReadAllBytes(@"C:\Users\Username\Desktop\Testfile.pdf");

    //Save "pdfAsByteArray" into database
    //...
    //Load pdf from database into byte[] variable "pdfAsByteArray"

    using (var memoryStream = new MemoryStream(pdfAsByteArray))
    {
        this.PdfViewer.DocumentSource = new PdfDocumentSource(memoryStream);
    }
Run Code Online (Sandbox Code Playgroud)

当我执行应用程序时,我得到一个空的PdfViewer.

问题:如何以正确的方式设置DocumentSource?

问题:如何处理流?(注意using不起作用)

注意:我不想避免将临时文件写入磁盘


编辑:

我想通了,但我对这个解决方案并不完全满意:

不工作:

using (var memoryStream = new MemoryStream(pdfAsByteArray))
{
    this.PdfViewer.DocumentSource = new PdfDocumentSource(memoryStream);
}
Run Code Online (Sandbox Code Playgroud)

工作:

var memoryStream = new MemoryStream(pdfAsByteArray);
this.PdfViewer.DocumentSource = new PdfDocumentSource(memoryStream);
Run Code Online (Sandbox Code Playgroud)

我不知道teleriks RadPdfViewer组件是如何工作的,但我不想处理Stream.

Sve*_*sen 7

从Telerik 文档(特别是关于"注意"表示此加载是异步完成的),我相信这应该工作,同时仍然提供一种关闭流的方法(不像你能够使用using块一样干净利落,但仍然比开放更好):

//class variable
private MemoryStream _stream;

_stream = new MemoryStream(pdfAsByteArray);
var docSource = new PdfDocumentSource(memoryStream);
docSource.Loaded += (sender, args) => { if (_stream != null) _stream.Dispose();};
this.PdfViewer.DocumentSource = docSource;
Run Code Online (Sandbox Code Playgroud)

我是徒手做到的,无法访问Telerik API,所以我无法获得Loaded事件的确切细节.

编辑
这是我发现的文件中的相关细节(强调我的):

PdfDocumentSource异步加载文档.如果要在导入文档后获取对DocumentSource的引用,则应使用PdfDocumentSource对象的Loaded事件来获取已加载的文档.如果从流中加载PDF,这也是一种方便的方法,可用于关闭流.

  • @DavidKhaykin我看到了你原来的答案,做了一点挖掘,发现了关于`Loaded`事件的小窍,写了/提交了我的例子,看到你提出了同样的建议.英雄所见略同. (2认同)