【问题标题】:Save PDF to file将 PDF 保存到文件
【发布时间】:2014-10-30 04:31:58
【问题描述】:

我正在开发适用于 Windows 8.1 的 Windows 应用商店应用程序,但找不到任何可以解决我需要做的事情的内容。我正在尝试将 pdf 页面的图像保存到我的本地应用程序数据存储中。我有以下内容:

private async void GetFirstPage()
    {
        // Retrieve file from FutureAccessList
        StorageFile file = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(token);

        // Truncate last 4 chars; ex: '.pdf'
        FileName = file.Name.Substring(0, file.Name.Length - 4);

        // Get access to pdf functionality from file
        PdfDocument doc = await PdfDocument.LoadFromFileAsync(file);

        // Get a copy of the first page
        PdfPage page = doc.GetPage(0);

        // Below could be used to tweak render options for optimizations later
        //PdfPageRenderOptions options = new PdfPageRenderOptions();

        // Render the first page to the BitmapImage
        InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
        await page.RenderToStreamAsync(stream);

        // Common code
        Cover.SetSource(stream);

        // Convert the active BitmapImage Cover to a storage file to be stored locally
        // ???

    }

变量 Cover 是一个绑定在 XAML 中的 BitmapImage,用于向用户显示图像。我想将此图像保存到我的本地应用程序数据中,这样每次我的应用程序打开时我都不必通过 PDF 库重新渲染它!问题是我无法从流中保存 Windows 应用商店应用程序中的任何内容,除非它是据我所知的文本(对我来说没有文件流或文件输出流),并且 Cover 的 URI 源为空,因为它来自流,使得很难将我的 BitmapImage、Cover 保存到 StorageFile 以正确保存 Windows Store。

目前一切都对我有用,我只是对每次打开我的应用程序时从头开始将 pdf 页面重新渲染到我的位图图像感到不安。提前感谢您的任何意见!

【问题讨论】:

    标签: c# pdf windows-store-apps windows-8.1


    【解决方案1】:

    您需要直接从 PdfPage 而非 BitmapImage 中保存图像,因为您无法从 BitmapImage 中获取数据。 PdfPage.RenderToStreamAsync 已经将流编码为位图,因此除了将其发送到文件之外,您无需进行任何操作。这与您保存到 InMemoryRandomAccessStream 的操作基本相同,除了基于文件的流:

    //We need a StorageFile to save into.
    StorageFile saveFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("safedPdf.png",CreationCollisionOption.GenerateUniqueName);
    
    using (var saveStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
    {
        await page.RenderToStreamAsync(saveStream);
    }
    

    【讨论】:

    • 这就像一个魅力,现在真的很有意义!我一定很密集>。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2019-04-09
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多