Articles in this section
Category / Section

How to share the PDF document in Xamarin.iOS application?

5 mins read

PDF documents can be shared by saving the loaded PDF to the file system using the SaveDocument API and share the saved PDF. Refer to the following code snippets.

Portable

Add an interface to the PCL project which defines a method that shares the saved PDF document.

C#

public interface IShare
{
    Task Show(string title, string message, string filePath);
}

 

Add another interface to save the loaded PDF to the file system.

C#

public interface ISave
{
    string Save(MemoryStream fileStream);
}

 

Get the saved file path using the Save method defined in ISave and use this as an argument to share the file using Show method of IShare interface. 

C#

private void OnShareButtonClicked(object sender, EventArgs e)
{
    string filePath = DependencyService.Get<ISave>().Save(pdfViewerControl.SaveDocument() as MemoryStream);
    DependencyService.Get<IShare>().Show("Share", "Sharing PDF", filePath);
}

 

Android

Implement IShare with file sharing options available in Android platform.

C#

//Register the Android implementation of IShare with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.Droid.ShareAndroid))]
 
namespace GettingStarted_PDFViewer.Droid
{
    class ShareAndroid : IShare
    {
        private readonly Context context;
        public ShareAndroid()
        {
            context = Android.App.Application.Context;
        }
        public Task Show(string title, string message, string filePath)
        {
            var uri = Android.Net.Uri.Parse("file://" + filePath);
            var contentType = "application/pdf";
            var intent = new Intent(Intent.ActionSend);
            intent.PutExtra(Intent.ExtraStream, uri);
            intent.PutExtra(Intent.ExtraText, string.Empty);
            intent.PutExtra(Intent.ExtraSubject, message ?? string.Empty);
            intent.SetType(contentType);
            var chooserIntent = Intent.CreateChooser(intent, title ?? string.Empty);
            chooserIntent.SetFlags(ActivityFlags.ClearTop);
            chooserIntent.SetFlags(ActivityFlags.NewTask);
            context.StartActivity(chooserIntent);
 
            return Task.FromResult(true);
        }
    }
}

 

Implement ISave with file write options available in Android platform.

C#

//Register the Android implementation of ISave with DependencyService
[assembly:Dependency(typeof(GettingStarted_PDFViewer.Droid.SaveAndroid))]
 
namespace GettingStarted_PDFViewer.Droid
{
    public class SaveAndroid : ISave
    {
        public string Save(MemoryStream stream)
        {
            string root = null;
            string fileName = "SavedDocument.pdf";
            //Get the root folder of the application
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            //Create a new folder with name Syncfusion
            Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
            myDir.Mkdir();
            //Create a new file with the name fileName in the folder Syncfusion
            Java.IO.File file = new Java.IO.File(myDir, fileName);
            string filePath = file.Path;
            //If the file already exists delete it
            if (file.Exists()) file.Delete();
            Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file);
            //Save the input stream to the created file
            outs.Write(stream.ToArray());
            var ab = file.Path;
            outs.Flush();
            outs.Close();
            return filePath;
        }
    }
}

 

iOS

Implement IShare with file sharing options available in iOS platform.

C#

//Register the iOS implementation of IShare with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.iOS.ShareiOS))]
 
namespace GettingStarted_PDFViewer.iOS
{
    public class ShareiOS : IShare
    {
        // MUST BE CALLED FROM THE UI THREAD
        public async Task Show(string title, string message, string filePath)
        {
           
 
            var items = new NSObject[] { NSObject.FromObject(title), NSUrl.FromFilename(filePath) };
            var activityController = new UIActivityViewController(items, null);
            var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;
 
 
            NSString[] excludedActivityTypes = null;
            excludedActivityTypes = new NSString[] { UIActivityType.AssignToContact, UIActivityType.AddToReadingList, UIActivityType.CopyToPasteboard, UIActivityType.SaveToCameraRoll };
 
            if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
                activityController.ExcludedActivityTypes = excludedActivityTypes;
 
            await rootController.PresentViewControllerAsync(activityController, true);
        }
    }
}

 

Implement ISave with file write options available in iOS platform.

C#

//Register the iOS implementation of ISave with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.iOS.SaveiOS))]
 
namespace GettingStarted_PDFViewer.iOS
{
    public class SaveiOS : ISave
    {
        public string Save(MemoryStream fileStream)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //The path to which the file is to be saved
            string filepath = Path.Combine(path, "SavedDocument.pdf");
 
            FileStream outputFileStream = File.Open(filepath, FileMode.Create);
            fileStream.Position = 0;
            //Save the input stream of the PDF to the file
            fileStream.CopyTo(outputFileStream);
            outputFileStream.Close();
            return filepath;
        }
    }
}

 

UWP

Implement IShare with file sharing options available in UWP platform.

C#

//Register the UWP implementation of IShare with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.UWP.ShareUWP))]
 
namespace GettingStarted_PDFViewer.UWP
{
    class ShareUWP : IShare
    {
        private DataTransferManager dataTransferManager;
        private string filePath;
        private string title;
        private string message;
        public ShareUWP()
        {
            dataTransferManager = DataTransferManager.GetForCurrentView();
            dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(ShareTextHandler);
        }
        public async Task Show(string title, string message, string filePath)
        {
            this.title = title ?? string.Empty;
            this.filePath = filePath;
            message = message ?? string.Empty;
 
            DataTransferManager.ShowShareUI();
        }
        private async void ShareTextHandler(DataTransferManager sender, DataRequestedEventArgs e)
        {
            DataRequest request = e.Request;
 
            // Title is mandatory
            request.Data.Properties.Title = string.IsNullOrEmpty(title) ? Windows.ApplicationModel.Package.Current.DisplayName : title;
 
            DataRequestDeferral deferral = request.GetDeferral();
 
            try
            {
                if (!string.IsNullOrWhiteSpace(filePath))
                {
                    StorageFile attachment = await StorageFile.GetFileFromPathAsync(filePath);
                    List<IStorageItem> storageItems = new List<IStorageItem>();
                    storageItems.Add(attachment);
                    request.Data.SetStorageItems(storageItems);
                }
                request.Data.SetText(message ?? string.Empty);
            }
            finally
            {
                deferral.Complete();
            }
        }
 
    }
}

 

Implement ISave with file write options available in UWP platform.

C#

//Register the UWP implementation of ISave with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.UWP.SaveWindows))]
 
namespace GettingStarted_PDFViewer.UWP
{
    public class SaveWindows : ISave
    {
        MemoryStream stream;
        StorageFolder folder;
        StorageFile file;
        public string Save(MemoryStream documentStream)
        {
            documentStream.Position = 0;
            stream = documentStream;
            SaveAsync();
            return Path.Combine(ApplicationData.Current.LocalFolder.Path, "SavedDocument.pdf");
        }
 
        private async void SaveAsync()
        {
            folder = ApplicationData.Current.LocalFolder;
            file = await folder.CreateFileAsync("SavedDocument.pdf", CreationCollisionOption.ReplaceExisting);
            if (file != null)
            {
                Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
                Stream st = fileStream.AsStreamForWrite();
                st.SetLength(0);
                st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
                st.Flush();
                st.Dispose();
                fileStream.Dispose();
            }
        }
    }
}
 

 

Sample link:

http://www.syncfusion.com/downloads/support/directtrac/general/ze/GettingStarted_PDFViewer-1659303577https://www.syncfusion.com/downloads/support/directtrac/general/ze/GettingStarted_PDFViewer-1659303577

 

Conclusion

I hope you enjoyed learning about how to share the PDF document in Xamarin.Forms platform.

You can refer to our Xamarin.iOS PDFViewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our  Xamarin.iOS PDFViewer example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied