left-icon

Real-World Xamarin.Forms Succinctly®
by Alessandro Del Sole

Previous
Chapter

of
A
A
A

CHAPTER 9

Displaying and Sharing Documents

Displaying and Sharing Documents


Mobile apps offer the great benefit of bringing our documents everywhere with us, no matter if they are stored locally on the device or on a cloud service. This is a great possibility because you might need to receive, send, or share documents with other people, even when you are not at your desk working on a computer. The most popular file format for sharing documents is PDF, so the focus of this chapter is going to be on this file format, but at least for the sharing part, you will be able to reuse the described techniques with any format.

In terms of mobile app development with Xamarin.Forms, there is no built-in view that allows for displaying PDF documents, but luckily, there are third-party controls that make this easy. Sharing files is instead provided by the Xamarin.Essentials library, which simplifies development with yet another scenario. In the next paragraphs, you will learn how to display PDF documents in your mobile apps using Syncfusion’s PDF viewer, and how to share PDF documents by leveraging the Xamarin.Essentials API.

Note: A valid subscription for Syncfusion’s Essential Studio for Xamarin is required. Actually, you can use a trial version of the libraries described in this chapter by simply downloading the NuGet packages, and the app will show a message about the trial status. If you are an individual developer or work for a small business, you can also consider the Community License. Make sure you read the linked page to see if you are eligible.

Chapter focus and sample project setup

The goal of this chapter is explaining how to display PDF documents in your mobile apps built with Xamarin.Forms, and how to share them using the operating system’s built-in sharing mechanism, invoked by the Xamarin.Essentials cross-platform API. To provide you with an example that is working locally, I have included a sample PDF document as an embedded resource of the companion project. In your real project, you will be free to choose where the documents will be opened from, and you will be able to use the techniques described in the “Working with files” section of Chapter 1 and usual Xamarin.Forms file handling techniques.

Create a new blank project. Displaying PDF documents is achieved using the SfPdfViewer control by Syncfusion, which is part of their Essential Studio for Xamarin suite available as a NuGet package.

Note: You need to add the following URL to the NuGet Package Manager’s sources to be able to download Syncfusion’s packages for Xamarin: http://nuget.syncfusion.com/nuget_xamarin/nuget/getsyncfusionpackages/xamarin.

When you’re ready, browse NuGet for the Syncfusion.Xamarin.SfPdfViewer package (see Figure 29) and install it to all the projects in the solution.

Installing the Syncfusion.Xamarin.SfPdfViewer package

Figure 29: Installing the Syncfusion.Xamarin.SfPdfViewer package

When the package has been installed, you need an additional step for iOS. In the AppDelegate.cs file, add the following lines of code to the FinishedLaunching method right before the invocation to the LoadApplication method:

Syncfusion.SfPdfViewer.XForms.iOS.SfPdfDocumentViewRenderer.Init();

Syncfusion.SfRangeSlider.XForms.iOS.SfRangeSliderRenderer.Init();

These are required to initialize the PDF viewer.

The user interface for the main page is very simple. It includes the PDF viewer and two buttons: one for loading a document, and one for sharing the document. Code Listing 22 contains the XAML code for this.

Code Listing 22

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             x:Class="WorkingWithDocuments.MainPage"

             xmlns:syncfusion="clr-

                   namespace:Syncfusion.SfPdfViewer.XForms;

                   assembly=Syncfusion.SfPdfViewer.XForms">

    <Grid x:Name="pdfViewGrid">

        <Grid.RowDefinitions>

            <RowDefinition />

            <RowDefinition Height="40" />

        </Grid.RowDefinitions>

        <syncfusion:SfPdfViewer 

            x:Name="PdfViewerControl" 

            IsToolbarVisible="True" />

        <StackLayout Grid.Row="1" Orientation="Horizontal">

            <Button x:Name="OpenButton" 

                    Text="Open" 

                    Clicked="OpenButton_Clicked" />

            <Button x:Name="ShareButton" 

                    Text="Share" 

                    Clicked="ShareButton_Clicked" />

        </StackLayout>

    </Grid>

</ContentPage>

For now, only focus on the XML namespace added to use the SfPdfViewer control. Specific considerations are coming in the next section, together with the C# code that enables the two buttons. As I mentioned previously, I added a sample PDF document in the companion solution, but if you are working on a brand new one, add a PDF file to the root folder of the .NET Standard project and set its Build Action as EmbeddedResource.

The last step for setup is specifying the Syncfusion license key, which you specify by adding the following line of code in the constructor of the App.Xaml.cs file, before the assignment of the MainPage object:

Syncfusion.Licensing.SyncfusionLicenseProvider.

           RegisterLicense("YOUR-LICENSE-KEY-GOES-HERE");

If you don’t add the license key, libraries will work in trial mode (which is fine for the current example, but not for production purposes).

Introducing the SfPdfViewer control

Syncfusion’s SfPdfViewer is a very powerful and versatile control that can display, annotate, and edit PDF documents. In Code Listing 22, it is declared as follows:

<syncfusion:SfPdfViewer x:Name="PdfViewerControl" IsToolbarVisible="True" />

The IsToolbarVisible property assigned with true enables a built-in toolbar that allows for performing many common operations on documents, such as navigating pages, searching for text, annotating text with highlights and comments, printing, and saving a copy. Because the SfPdfViewer exposes a lot of bindable properties, you can certainly create your own toolbar and bind your own commands to properties, but I can assure you that most of the time it’s not needed. You load PDF documents into the SfPdfViewer via its LoadDocument method, which receives the file to open as a Stream object. You can also invoke the LoadDocumentAsync method for asynchronous loading. Both methods can optionally receive a string argument representing the document password, if the PDF is protected. With this in mind, the event handler for the OpenButton will look like the following:

private void OpenButton_Clicked(object sender, EventArgs e)

{

    var fileStream = typeof(App).GetTypeInfo().Assembly.

        GetManifestResourceStream("WorkingWithDocuments.SampleDoc.pdf");

    PdfViewerControl.LoadDocument(fileStream);

}

The first line of code reads a file from the embedded resources and returns a Stream, and the name has the following structure: ProjectName.FileName.FileExtension. If the file was placed in a project subfolder, the structure would be ProjectName.FolderName.FileName.FileExtension. In my case, the project is called WorkingWithDocuments (and so is the companion project). The second line loads the stream into the SfPdfViewer control. If you run the app as it is, you will see the result shown in Figure 30.

Displaying a PDF document in Xamarin.Forms

Figure 30: Displaying a PDF document in Xamarin.Forms

As you can see, the PDF document is shown in the user interface in a convenient way. The built-in toolbar is designed to be consistent with the operating system and offers everything you need to work with this kind of document. In particular:

  • The navigation button (first from the left) allows for switching between single-page and multiple-page navigation.
  • The Bookmarks button allows for managing bookmarks in the document.
  • The Search tool makes it possible to search for specified text.
  • Shortcuts for undoing and redoing actions, and saving and printing the document are accessible via the last button on the right.
  • You can browse pages by writing the page number in the box at the bottom.
  • You can add annotations and even digital signatures to the document by accessing the annotation tools with the button at the far right of the bottom bar.

Figure 31 shows an example of annotations added to the PDF document using only the built-in tools of the SfPdfViewer control.

Annotating a PDF document with built-in tools

Figure 31: Annotating a PDF document with built-in tools

You can now probably imagine why I suggested you avoid too many customizations on the control. Its user interface is designed to be simple and easy to access, but powerful at the same time, and these features are what you would expect from a PDF viewer in a mobile app. Make sure you visit the official documentation for further information on the control’s customization, localization, and other features.

Sharing files and documents

Sharing content in mobile apps is one of the most important features in terms of app usability, and goes beyond the concept of sharing on social media. For example, if you receive a PDF document via email and you want to open it inside a PDF viewer app like Adobe Reader, you are actually sharing the document from the mail client with the PDF viewer. Similarly, you can share files on your device, such as pictures and videos, in a WhatsApp chat. What you are doing is asking the operating system to open another app, which is open enough to receive contents from other apps. In a mobile app that works with data, a common scenario is to receive a document via web API, display the document in-app, and have the option to send it via email to some recipients. So, at a higher level, by sharing, we generally mean sharing content with another app.

Sharing content in Xamarin.Forms is made easy by the Share class exposed by the Xamarin.Essentials library. This class exposes a static method called RequestAsync, which receives an argument that can be of the following types:

  • string, for sharing plain text.
  • ShareTextRequest, for sharing URIs or text.
  • ShareFileRequest, for sharing files.

Working with the first two is not covered in this chapter, but we will focus on the third one. The ShareFileRequest class points to the local pathname of a file. In the current example, the PDF document is stored as an embedded resource, so an additional step is required to get the file from the resources, copy it into the app’s directory, and then point to the obtained pathname. This is accomplished by the following method, called ShareAsync:

private async Task ShareAsync()

{

    var fileStream = typeof(App).GetTypeInfo().Assembly.

        GetManifestResourceStream("WorkingWithDocuments.SampleDoc.pdf");

   

    var cacheFile = Path.Combine(FileSystem.CacheDirectory,

        "SampleDoc.pdf");

using (var file = new FileStream(cacheFile, FileMode.Create,

                  FileAccess.Write))

    {

        fileStream.CopyTo(file);

    }

    var request = new ShareFileRequest();

    request.Title = "Share document";

    request.File = new ShareFile(cacheFile);

    await Share.RequestAsync(request);           

}

As in the first example about loading the document, the first line gets the file stored inside the embedded resources as a Stream. The cacheFile variable combines the path for the app’s cache directory with the file name into one pathname. The using block creates an instance of the FileStream class pointing to the original file’s stream, creating a copy in the target directory. The using block ensures the stream resources are disposed after usage. The ShareFileRequest object can point to the local pathname via the File property. The Title property allows for specifying the title for the sharing user interface, if supported by the OS. The ShareAsync method is invoked by the Clicked event handler for the ShareButton as follows:

private async void ShareButton_Clicked(object sender, EventArgs e)

{

    await ShareAsync();

}

If you now run the app and click Share after opening the document, you will get a result similar to Figure 32.

Sharing a document

Figure 32: Sharing a document

The result will almost certainly vary on your device because it depends on how many and what apps you have installed to support PDF documents. (In my case, for iOS I’m using the simulator, which has no PDF apps installed, and therefore, it only shows device options.) You will just need to select an app enabled to receive PDF documents, and the file will be shared using the system interface, without the need to write platform-specific code—which is an incredible benefit.

The app that receives the document will then know how to handle it. For example, if you select an email client for sharing, the document will be automatically added as an attachment to a new email message. Actually, you could share multiple files at the same time with a similar approach, using the ShareMultipleFilesRequest class. This is not covered here, but the documentation provides an appropriate description.

Chapter summary

Mobile apps might need to work with PDF documents for several reasons, such as displaying reports, forms, or simply documentation. Xamarin.Forms does not have a built-in view to display PDF documents, but Syncfusion provides the SfPdfViewer control, which is simple to use and includes a toolbar with all the commands and tools required to annotate, comment, and sign documents.

When it comes to sharing, the Share class from the Xamarin.Essentials library makes it easy to send files to other apps by simply invoking the RequestAsync method. Usually an in-app PDF viewer takes all the space possible on a page, and actually this is something that many other views do. However, especially if you work with iPhone devices, there is something you need to know about handling space with iPhone X and later: the safe area. This is discussed in the next chapter.


Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.