MASA MAUI 预览Office文件

发布时间 2023-10-16 11:38:44作者: MASA技术团队

背景

接到一个在Maui中预览Office文件的需求,包含excel、word、PDF三种常见的文件,经过技术选型,最后选择了微软原生支持的office在线预览Api,原因是此技术方案简单、跨平台。在开发过程中碰到了不少问题,所以在此分享在MAUI中预览Offic文件的经验,也希望大家少踩坑。

介绍

微软提供了一个浏览器在线预览Office的Api:在线预览Office文件Api,拼接自己的office文件地址参数后在浏览器中访问即可达到预览效果。

https://view.officeapps.live.com/op/view.aspx?src=

image.png

接下来我们按照这个思路在Maui中实现这个效果。

1、新建MAUI Blazor项目

OfficeViewerDemo
企业微信截图_1696840312740.png

企业微信截图_16969010278681.png

2、创建OfficeViewer.razor组件

在Index.razor页面写上demo视图
企业微信截图_16969018241364.png

<iframe src="@($"https://view.officeapps.live.com/op/view.aspx?src={Url}")" frameborder="0" style="height:100vh;width:100%;" />

@code {
    [Parameter]
    [EditorRequired]
    public string Url { get; set; }
}

image.png

@page "/"

<OfficeViewer Url="@_url" />

@code{
    string _url = "your_excel_url";
}

3、使用安卓模拟器运行

image.png

看似大功告成了,满心欢喜,然而在尝试浏览word文件时发现异常,无法正常访问

企业微信截图_16969038169158.png

通过用浏览器模拟移动设备调试后,发现微软这个Api会检测设备,这个Api在移动端下不适用。经过在网络上一番查找,最后发现微软有一个移动端设备使用的Api:在线预览Office文件Api,我们将OfficeViewer.razor组件代码中的Api替换后运行

https://view.officeapps.live.com/op/embed.aspx?src==

企业微信截图_16969046046389.png

<iframe src="@($"https://view.officeapps.live.com/op/embed.aspx?src={Url}")" frameborder="0" style="height:100vh;width:100%;" />

@code {
    [Parameter]
    [EditorRequired]
    public string Url { get; set; }
}

一切似乎完美,然而现实很残酷,在打包给测试后,发现Iphone进入此页面会出现跳转浏览器的现象,在网上查阅资料后得知,这是苹果的安全策略,就是不允许App里直接使用iframe。最后尝试在webview中使用iframe,解决了此问题。

4、兼容iOS

关于MAUI WebView的内容请参考下面官方文档

https://learn.microsoft.com/zh-cn/dotnet/maui/user-interface/controls/webview?pivots=devices-ios

新建WebViewer.xaml文件,使用WebView组件

企业微信截图_16969086735360.png

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="OfficeViewrDemo.WebViewer"
             Title="WebViewer">
    <StackLayout>
        <WebView  x:Name="webView"  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
        </WebView>
    </StackLayout>
</ContentPage>

image-20231010113216729.png

namespace OfficeViewrDemo;

public partial class WebViewer : ContentPage
{
    public WebViewer()
    {
        InitializeComponent();
    }

    public void Open(string url)
    {
        this.webView.Source = url;
    }
}

修改OfficeViewer.razor组件代码

image-20231010113319754.png

@code {
    [Parameter]
    [EditorRequired]
    public string Url { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            WebViewer webView = new WebViewer();
            webView.Open($"https://view.officeapps.live.com/op/embed.aspx?src={Url}");
            await Microsoft.Maui.Controls.Application.Current.MainPage.Navigation.PushModalAsync(webView);
        }
    }
}

如此这般就兼容解决了iOS。

总结

本文主要介绍了如何在Maui下预览Office文件,并分享开发过程正踩过的坑以及对应的解决方案。希望能帮助到遇到同样需求问题的朋友。