Use pdfkit5 with a Xamarin.Forms app

Use PDFKit.NET 5.0 with a Xamarin.Forms app

This article demonstrates a simple Xamrin.Forms app that runs on Android, iOS and UWP. The app downloads a PDF from a given URL and displays basic information about the PDF using the .NET Standard 1.5 build of PDFKit.NET 5.0.

Here is the end result (UWP):

Xamarin Uwp App

This code sample is included in the evaluation download. Path: <var>\samples\CS\Xamarin_DocumentInfo\DocumentInfo.sln</var>.

Prerequisites

It is assumed that you have Visual Studio 2017 installed with Workloads Universal Windows Platform development and Mobile development with .NET

Xamarin Workloads

Create a new project

Create a new project of type Cross Platform App (Xamarin) Visual C#:

Xamarin Project Settings

Next, select Blank App, Xamarin.Forms and Shared Project:

Xamarin Project Settings

You will now have a solution with three platform specific projects for Android, iOS and UWP and a shared project:

Xamarin Solution

We will change the shared project DocumentInfo only. The three platform specific projects will be left unchanged.

Create the UI

Change MainPage.xaml as follows:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DocumentInfo"
             x:Class="DocumentInfo.MainPage">
    <StackLayout Margin="20">
        <Label Text="Welcome to the PDFKit5 DocumentInfo code sample!" Font="Medium" Margin="0, 0, 0, 20"/>
        <ScrollView>
            <StackLayout Margin="0, 0, 20, 0">
                <Entry Text="http://www.orimi.com/pdf-test.pdf" x:Name="urlField"/>
                <Button Text="Fetch PDF from the URL..." Clicked="OnFetchButtonClicked" HorizontalOptions="Start"/>
                <StackLayout x:Name="infoStack" Margin="0, 20, 0, 0">
                </StackLayout>
            </StackLayout>
        </ScrollView>
    </StackLayout>
</ContentPage>

Fetch PDF and show info

The Clicked handler of the ‘Fetch PDF from the URL…’ is implemented by method OnFetchButtonClicked as follows (error handling omitted):

void OnFetchButtonClicked(object sender, EventArgs args)
{ 
  infoStack.Children.Clear();

  Uri uri = new Uri(urlField.Text);

  using (WebClient client = new WebClient())
  {
    using (var fileStream = new MemoryStream(client.DownloadData(uri)))
    {
      Document doc = new Document(fileStream);
      showDocumentInfo(Path.GetFileName(uri.LocalPath), doc.DocumentInfo);
    }
  }
}

For the full code sample, we refer to the evaluation download.

no data is available for encoding 1252

You may get the error: no data is available for encoding 1252. This issue is discussed on Stack Overflow.

To solve this problem, go to Project Properties of the iOS project, select iOS Build and check west:

Codepage West