我在使用某些用 C# 编写的 Windows 应用商店应用程序时遇到问题。
应用程序加载在数据库中以字节数组形式存储的 PDF 文件,并尝试在其自己的 XAML View 中呈现 Image 对象中的第一页。代码如下:
PdfDocument _pdf = null;
#region Load PDF
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) {
await ms.WriteAsync(getPdfByteArrayFromDB().AsBuffer());
_pdf = await PdfDocument.LoadFromStreamAsync(ms);
}
#endregion
if (_pdf != null && _pdf.PageCount > 0)
{
PdfPage _page = _pdf.GetPage(0);
if (_page != null)
{
#region Render page
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) {
await _page.RenderToStreamAsync(ms);
BitmapImage bmi = new BitmapImage();
ms.Seek(0);
await bmi.SetSourceAsync(ms);
this.PdfPageImage.Source = bm;
}
#endregion
}
}
不幸的是,它呈现白色图像。我尝试通过编写一个临时文件将页面渲染为图像并读取它来执行相同的操作。
#region Render page
StorageFile cachedPage = await ApplicationData.Current.TemporaryFolder
.CreateFileAsync("page.png", CreationCollisionOption.ReplaceExisting);
if (cachedPage != null)
{
IRandomAccessStream randomStream
= await cachedPage.OpenAsync(FileAccessMode.ReadWrite);
await _page.RenderToStreamAsync(randomStream);
await randomStream.FlushAsync();
randomStream.Dispose();
_page.Dispose();
BitmapImage bmi = new BitmapImage();
bmi.SetSource(await cachedPage.OpenAsync(FileAccessMode.Read));
this.PdfPageImage.Source = bmi;
}
#endregion
浏览临时文件夹,有与原始 PDF 大小相同的临时图像,它们只是白色图像。所以我尝试将存储的 PDF 写入临时文件中。
#region Load PDF
StorageFile cachedPDF = await ApplicationData.Current.TemporaryFolder
.CreateFileAsync("myPdf.pdf", CreationCollisionOption.ReplaceExisting);
if (cachedPDF != null)
{
IRandomAccessStream randomStream = await cachedPDF.OpenAsync(FileAccessMode.ReadWrite);
await randomStream.WriteAsync(getPdfByteArrayFromDB().AsBuffer());
await randomStream.FlushAsync();
randomStream.Dispose();
_pdf = await PdfDocument.LoadFromFileAsync(cachedPDF);
}
#endregion
两种渲染页面的方式都工作得很好,因此存储的 PDF 很好,但尝试直接从内存流中读取字节数组会遇到麻烦。有没有一种方法可以在不写入任何临时文件的情况下渲染 PDF 页面?
非常感谢!
最佳答案
您必须倒带您的MemoryStream
。
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) {
await ms.WriteAsync(getPdfByteArrayFromDB().AsBuffer());
// The current position is at the end. Rewind to 0.
ms.Seek(0);
_pdf = await PdfDocument.LoadFromStreamAsync(ms);
}
我应该注意,通过将其写入临时文件,您将创建一个不需要回绕的新流,这就是它起作用的原因。
关于c# - WPF : PdfDocument not rendering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22347771/