How to view the PDF file in webview MAUI android

Amose Kumar R 5 Reputation points
2024-02-01T08:06:48.2066667+00:00

I have a pdf file that is storage in android local storage, how to display this pdf file in MAUI android through webview.

I am using pdf js and i have provided webview source as
$"file:///android_asset/pdfjs/web/viewer.html?file={my pdf path}".

It is throwing file not found error in webview android.

Developer technologies .NET .NET MAUI
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2024-02-02T02:43:34.8+00:00

    Hello,

    There are four reasons for this problem.

    • The pdfjs version used is incorrect.
    • The MAUI file URL is not converted to an Android-specific URI.
    • Javascript is not enabled for webview.
    • The file path of pdfjs is incorrect.

    You could follow the steps below to display your local files in MAUI.

    Step 1. Enable JavaScript for webview, which you can do in the page's constructor.

    public MainPage()
            {
                InitializeComponent();
                Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
                {
    #if ANDROID
                    handler.PlatformView.Settings.JavaScriptEnabled = true;
                    handler.PlatformView.Settings.AllowFileAccess = true;
                    handler.PlatformView.Settings.AllowFileAccessFromFileURLs = true;
                    handler.PlatformView.Settings.AllowUniversalAccessFromFileURLs = true;
    
    #endif
                });
            }
    

    Step 2. Download the PDF.js file for version 2.14.305. After testing, the latest version of PDF.js will have an error that the PDF file cannot be displayed.

    Step 3. Check that your pdfjs path is correct. For example, if you move the build and web folder directly to the Raw folder, pdfjs is not needed in the path. file:///android_asset/web/viewer.html?

    Step 4. Change the URL to the URI of the Android platform.

    #if ANDROID
                Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(path));
                string pdfpath = string.Format("file:///android_asset/pdfjs/web/viewer.html?file={0}", uri);
                pdfviewer.Source = new UrlWebViewSource { Url = pdfpath };
    #endif
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.