We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: November 16, 2018).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to save loaded PDF document in application level?

Platform: Xamarin.Forms |
Control: PdfViewer |
Published Date: July 27, 2018 |
Last Revised Date: June 4, 2019

How to save loaded PDF document in application level?


The PDF document in the PDF viewer is saved in the application level. PDF viewer returns the PDF document along with the changes made (annotations addition and modification) as stream when tapping the save button in the default toolbar as an event argument of the DocumentSaveInitiated event. This stream is saved as a file locally in Xamarin Forms Android, iOS, and UWP platforms by using DependencyService in Xamarin.Forms. These platform specific saving options are used by defining an interface in the portable project. Refer to the following code snippets.

 

Portable

Define the following interface.

 

C#

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

 

Load the PDF to PdfViewer and invoke save method with the stream obtained from the DocumentSaveInitiated event using DependencyService. Then, give the name of the interface as type parameter to the method DependencyService.Get<T>().

 

C#

public MainPage()
{
     InitializeComponent();
     m_pdfDocumentStream =        typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SavePDFUsingNative.Assets.GIS Succinctly.pdf");
     pdfViewerControl.LoadDocument(m_pdfDocumentStream);
     pdfViewerControl.DocumentSaveInitiated +=         PdfViewerControl_DocumentSaveInitiated;
}
 
private void PdfViewerControl_DocumentSaveInitiated(object sender, Syncfusion.SfPdfViewer.XForms.DocumentSaveInitiatedEventArgs args)
        {
            string filePath = DependencyService.Get<ISave>().Save(args.SaveStream as MemoryStream);
            string message = "The PDF has been saved to " + filePath;
            DependencyService.Get<IAlertView>().Show(message);
        }
 

 

Implement the interface in the platform projects with the available platform specific saving options.

 

Android

 

C#

[assembly:Dependency(typeof(SavePDFUsingNative.Droid.SaveAndroid))]
 
namespace SavePDFUsingNative.Droid
{
    public class SaveAndroid : ISave
    {
        public string Save(MemoryStream stream)
        {
            string root = null;
            string fileName = "SavedDocument.pdf";
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
            myDir.Mkdir();
            Java.IO.File file = new Java.IO.File(myDir, fileName);
            string filePath = file.Path;
            if (file.Exists()) file.Delete();
            Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file);
            outs.Write(stream.ToArray());
            var ab = file.Path;
            outs.Flush();
            outs.Close();
            return filePath;
        }
    }
}

 

iOS

 

C#

[assembly: Dependency(typeof(SavePDFUsingNative.iOS.SaveiOS))]
 
namespace SavePDFUsingNative.iOS
{
    public class SaveiOS : ISave
    {
        public string Save(MemoryStream fileStream)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string filepath = Path.Combine(path, "SavedDocument.pdf");
 
            FileStream outputFileStream = File.Open(filepath, FileMode.Create);
            fileStream.Position = 0;
            fileStream.CopyTo(outputFileStream);
            outputFileStream.Close();
            return filepath;
        }
    }
}

 

UWP

 

C#

[assembly: Dependency(typeof(SavePDFUsingNative.UWP.SaveWindows))]
namespace SavePDFUsingNative.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/SavePDFUsingNative18258816

 

2X faster development

The ultimate Xamarin UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment
Comments
Jordan Capa
Apr 23, 2019

this is very helpful information! for beginners and want to save time, I found zetpdf.com i heard a lot of this from my co workers. i tried using it nad it's really convenient and easy to use!

Reply
white wabbit
May 31, 2019

The sample crashes when I click save on android.

Reply
Sathish Sivakumar [Syncfusion]
Jun 03, 2019

Hi White,

We need to provide the storage access permission to the save the PDF document in local storage of your device running on Android M or greater. Please find the modified sample in the below link for your reference.

http://www.syncfusion.com/downloads/support/directtrac/general/ze/SavePDFUsingNative18258816

Regards,

Sathish

white wabbit
Jul 15, 2019

It so happened when [assembly:Dependency(typeof(SavePDFUsingNative.Droid.SaveAndroid))]

namespace SavePDFUsingNative.Droid { public class SaveAndroid : ISave { public string Save(MemoryStream stream) { string root = null; string fileName = "SavedDocument.pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); string filePath = file.Path; if (file.Exists()) file.Delete(); Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(stream.ToArray()); var ab = file.Path; outs.Flush(); outs.Close(); return filePath; } } }

in "if (file.Exists()) file.Delete();" crash because I need to manually allow the my APP to access storage. Idk. but it happened there..

Gayathri Ramalingam [Syncfusion]
Jul 25, 2019

Hi white,

We tried to reproduce the issue “Application crashes while saving the PDF document using PDF Viewer in Xamarin.Forms.Android” , but it is working fine as expected. Kindly share the following details to analyze more on this issue and it will be helpful for us to analyze more on this issue.

  1. Replication procedure to reproduce the issue or screen shot illustrating the issue.
  2. Android device specification with the OS version.
  3. PDF document with which the issue could be reproduced.

With Regards, Gayathri R

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon