Hello,
I want to load the pdf by url.
You can use webview to view the pdf.
<WebView x:Name="webView" WidthRequest="500" HeightRequest="500"/>
Then, you can set the webviewsource wiht google docs url and your pdf url.
webView.Source = "https://docs.google.com/viewer?url=http://yourpdfurl.pdf";
Next, please enable javascript for your webview. After that, you can load the pdf by url in the android.
Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
{
#if ANDROID
handler.PlatformView.Settings.JavaScriptEnabled=true;
#endif
});
I need simple code.
=======================Update========================= If you want to download pdf file to the external download folder, you can use ContentResolver to save it.
Here are code about downloading pdf file by HttpContent.ReadAsStreamAsync
and save pdf file to the external download folder.
private async void Button_Clicked(object sender, EventArgs e)
{
string url = "https://www.africau.edu/images/default/sample.pdf";
//your stored pdf path
string fileName = FileSystem.Current.AppDataDirectory + "Temp.pdf";
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
//If we get the success status code, we can download it to the app data directory.
var stream = await response.Content.ReadAsStreamAsync();
#if ANDROID
ContentResolver resolver = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.ContentResolver;
ContentValues contentValues = new ContentValues();
contentValues.Put(MediaStore.IMediaColumns.DisplayName, "Temp.pdf");
contentValues.Put(MediaStore.IMediaColumns.MimeType, "application/pdf");
contentValues.Put(MediaStore.IMediaColumns.RelativePath, Android.OS.Environment.DirectoryDownloads);
Android.Net.Uri uri = resolver.Insert(MediaStore.Downloads.ExternalContentUri, contentValues);
Stream outputStream = resolver.OpenOutputStream(uri);
await stream.CopyToAsync(outputStream);
#endif
}
else
{
throw new Exception("File not found");
}
}
}
Do not forget to add these references for android platform.
#if ANDROID
using Android.Content;
using Android.Provider;
#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.