Is there any way to open pdf url in web view

Mane, PRASHANT GORAKH 106 Reputation points
2023-12-01T08:41:19.9333333+00:00

Hi, I was trying to open pdf url in webview in .NET MAUI but it was showing blank screen.

 <WebView
        x:Name="web_view"
        Source="https://s29.q4cdn.com/175625835/files/doc_downloads/test.pdf"
        />
Developer technologies .NET .NET MAUI
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-12-04T05:24:40.22+00:00

    Hello,

    You can open pdf URL by WebView in the iOS and windows platform directly.

    For android, you can do this by enabling the JavaScript and adding URL prefix before you open the URL.

    Firstly, you can create control that extend the WebView Control.

    public class PDFViewForUrl : WebView{  }
    

    Then use it in your xaml layout.

    
    <ContentPage 
    ...
                 xmlns:local="clr-namespace:yourProjectName"
                 >
      <local:PDFViewForUrl
             WidthRequest="500"
             HeightRequest="500"
             Source="https://s29.q4cdn.com/175625835/files/doc_downloads/test.pdf"
         />
    

    In the end, you can enable the JS and add pre-fix before your pdf URL by Handler.

    Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
                {
    #if ANDROID
                    if (view is PDFViewForUrl)
                    {
                        handler.PlatformView.Settings.JavaScriptEnabled = true;
                        string res = "";
                        if (view != null)
                        {
                            WebView webView = view as WebView;
                            if (webView.Source.GetType().Equals(typeof(UrlWebViewSource)))
                            {
                                UrlWebViewSource uriwebviewSource = webView.Source as UrlWebViewSource;
                                res = string.Format("https://drive.google.com/viewerng/viewer?url={0}", uriwebviewSource.Url.ToString());
                            }
                        }
                        handler.PlatformView.LoadUrl(res);
                    }
    #endif
                });
    

    Best Regards,

    Leon Lu


    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.


0 additional answers

Sort by: Most helpful

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.