[Solved] How to open PDF file in xamarin forms


how could I save it on download folder?

For android, you can save pdf file in download folder by following path.

  string rootPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);

For ios, use this directory to store user documents and application data files.

var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);

About open pdf in Anaroid, you can use the following code:

 public void openpdf()
    {
        string path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, "file.pdf");        
        // Get the uri for the saved file
        Android.Net.Uri file = Android.Support.V4.Content.FileProvider.GetUriForFile(MainActivity.mactivity, MainActivity.mactivity.PackageName + ".fileprovider", new Java.IO.File(path));
        Intent intent = new Intent(Intent.ActionView);
        intent.SetDataAndType(file, "application/pdf");
        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask|ActivityFlags.NoHistory);
       
        try
        {
            MainActivity.mactivity.ApplicationContext.StartActivity(intent);              
        }
        catch (Exception)
        {
            Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View PDF", ToastLength.Short).Show();
        }
    }

you need to add permission WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in AndroidMainfeast.xml, then you also need to Runtime Permission Checks in Android 6.0.

private void checkpermission()
    {
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
        {
            // We have permission, go ahead and use the writeexternalstorage.
        }
        else
        {
            // writeexternalstorage permission is not granted. If necessary display rationale & request.
            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
        }
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
        {
            // We have permission, go ahead and use the ReadExternalStorage.
        }
        else
        {
            // ReadExternalStorage permission is not granted. If necessary display rationale & request.
            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
        }
    }

Also add a provider in the AndroidManifest.xml file:

    <application android:label="PdfSample.Android">
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.fileprovider" android:exported="false" android:grantUriPermissions="true">
  <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
</provider>
</application>

And add an external path in Resources/xml/file_paths.xml

<external-path name="external_files" path="."/>

MainActivity.mactivity is static property in MainActivity.cs:

 public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    public static MainActivity mactivity;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        mactivity = this;

About open pdf in ios, you can take a look:

How to view PDF file using Xamarin Forms

Update:

My answer is also using DependencyService, you can create iterface in shared project.

public interface Iopenpdf
{
     void openpdf();
}

In Android platform, implement this interface.

[assembly: Xamarin.Forms.Dependency(typeof(openpdfhandle))]
namespace PdfSample.Droid
{
class openpdfhandle : Iopenpdf
{
    public void openpdf()
    {
        string path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, "file.pdf");
        //string path = Path.Combine(Android.App.Application.Context.GetExternalFilesDir(Environment.DirectoryDownloads).ToString(), "file.pdf");          
        // Get the uri for the saved file
        Android.Net.Uri file = Android.Support.V4.Content.FileProvider.GetUriForFile(MainActivity.mactivity, MainActivity.mactivity.PackageName + ".fileprovider", new Java.IO.File(path));
        Intent intent = new Intent(Intent.ActionView);
        intent.SetDataAndType(file, "application/pdf");
        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask|ActivityFlags.NoHistory);
       
        try
        {
            MainActivity.mactivity.ApplicationContext.StartActivity(intent);              
        }
        catch (Exception)
        {
            Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View PDF", ToastLength.Short).Show();
        }
    }
}
}

In shared code project, open pdf in button.click

 private void btnopen_Clicked(object sender, EventArgs e)
    {
        DependencyService.Get<Iopenpdf>().openpdf();
    }

6

solved How to open PDF file in xamarin forms