且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[UWP]在UWP应用程序中打开.docx和.PDF

更新时间:2022-10-21 10:28:18

你好Leonid Yudin,


在uwp中,您可以使用  Windows.System.Launcher.LaunchFileAsync  到
使用与指定文件关联的默认应用程序打开文件。因此,

 var file = await ApplicationData.Current.LocalFolder.GetFileAsync(" My.docx"); 

if(file!= null)
{
//启动检索到的文件
等待Windows.System.Launcher.LaunchFileAsync(file);
}

目前没有正式的API可以在您自己的UWP应用程序中打开Docx文件,您可以使用三方API。但是,如果您希望在我们的UWP应用程序内部呈现PDF文件的内容,您可以使用  Pdf文档
分类并在
图像
控件。以下是 PdfDocument 示例。


PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(file);
for(uint i = 0; i< pdfDocument.PageCount; i ++)
{
BitmapImage image = new BitmapImage();
var page = pdfDocument.GetPage(i);
using(InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await page.RenderToStreamAsync(stream);
await image.SetSourceAsync(stream);
}
}

祝你好运,


Breeze


Hello, the Internet is full of information about how to open Word documents in WPF and Windows Forms using OpenXML SDK and others. However, there is no information about the UWP. Is it really impossible? I don't believe it! However, the only real bit of information was to use a WebView to display documents from the Internet using Google Docs, I'm interested in is StorageFile. May be someone faced with similar?

Hi Leonid Yudin,

In uwp, you can use the Windows.System.Launcher.LaunchFileAsync to open the file using the default app associated with the specified file. As this,

    var file = await ApplicationData.Current.LocalFolder.GetFileAsync("My.docx");

    if (file != null)
    {
        // Launch the retrieved file
        await Windows.System.Launcher.LaunchFileAsync(file);
    }

Currently there is no official API to open the Docx file in your own UWP app itself, you can use some three parties API. But if you want the content of the PDF file to be rendered inside our UWP app itself, you can use the Pdf​Document Class and show the content in the Image control. Here is the PdfDocument sample.

PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(file);
for (uint i = 0; i < pdfDocument.PageCount; i++)
    {
        BitmapImage image = new BitmapImage();
        var page = pdfDocument.GetPage(i); 
        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            await page.RenderToStreamAsync(stream);
            await image.SetSourceAsync(stream);
        }
    }

Best regards,

Breeze