'How to display pdf offline in Xamarin.Forms apps?

Using PDFJS for displaying PDF files in a Xamarin.Forms apps. Copied the PDFJS folder and PDF files to the android assets folder. I am able to view/display PDFs on Android and iOS when online (connected to internet or mobile service). But when I am offline I get following error:

"Access to XMLHttpRequest at 'file:///android_asset/abcd.pdf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, https.", source: file:///android_asset/pdfjs/web/viewer.js

Code for Android and iOS:

<WebView
    x:Name="webView"
    BackgroundColor="White"
    HorizontalOptions="FillAndExpand"
    VerticalOptions="FillAndExpand"
    Margin="20">            
</WebView>

if (Device.RuntimePlatform == Device.Android)  {
    string localPath = "file:///android_asset/abcd.pdf";
    webView.Source = $"file:///android_asset/pdfjs/web/viewer.html?file={WebUtility.UrlEncode(localPath)}"; 
}  
else {
    webView.Source = Path.Combine(DependencyService.Get<IBaseUrl>().Get(), "abcd.pdf"); 
}

How to resolve this error or display PDF offline in Xamarin.Forms apps?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source