How can I show an pdf file in xamarin pcl uwp that is outside my instal folder?

后端 未结 1 1996
萌比男神i
萌比男神i 2020-12-19 19:47

Hy, I\'m working in a Xamarin PCL project with the platforms Android and UWP. As a feature the user should be able to open

1条回答
  •  感情败类
    2020-12-19 20:24

    I know now why. Because I'm developing a UWP application and I want to access a file outside my instal folder. This location is

    You have use ms-appx-web: uri scheme as your pdf file access path. Actually, your pdf path is C:\Users\User\AppData\Local\Packages\PDFTest.UWP_v4j5n0js0cwst\LocalState\ that stored in the app's local folder. So the file will not be accessed.

    I have also tested with "ms-appdata:///local/" uri scheme to access the pdf file base on your project. Unfortunately, It can't be recognised by viewer.js.

    And then, I tried to convert pdf file into Base64String then opening it by calling the openPdfAsBase64 JS function in the viewer.js.

    private async Task OpenAndConvert(string FileName) 
    {
        var folder = ApplicationData.Current.LocalFolder;
        var file = await folder.GetFileAsync(FileName);
        var filebuffer = await file.OpenAsync(FileAccessMode.Read);
        var reader = new DataReader(filebuffer.GetInputStreamAt(0));
        var bytes = new byte[filebuffer.Size];
        await reader.LoadAsync((uint)filebuffer.Size);
        reader.ReadBytes(bytes);
        return Convert.ToBase64String(bytes);  
    }
    

    Usage

    protected  override void OnElementChanged(ElementChangedEventArgs e)
    {
        base.OnElementChanged(e);
        if (e.NewElement != null)
        {   
            Control.Source = new Uri("ms-appx-web:///Assets/pdfjs3/web/viewer.html");
            Control.LoadCompleted += Control_LoadCompleted;
        }
    }
    
    private async void Control_LoadCompleted(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
    {
        CustomWebView pdfView = Element as CustomWebView;
        if (string.IsNullOrEmpty(pdfView?.Filename)) return;
    
        var ret = await OpenAndConvert(pdfView?.Filename);       
    
        var obj = await Control.InvokeScriptAsync("openPdfAsBase64", new[] { ret });
    }
    

    You could use this viewer.js that was added openPdfAsBase64 method.

    Got hints following: How to embed the PDFjs into your C# Project.

    0 讨论(0)
提交回复
热议问题