Syncfusion AI Assistant

How can I help you?

Create or Generate PDF file in Xamarin

18 Jun 20267 minutes to read

The Syncfusion® Xamarin PDF library is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files.

To include the Syncfusion® Xamarin PDF library into your Xamarin application, please refer to the NuGet Package Required or Assemblies Required documentation.

Steps to create PDF document in Xamarin

Step 1: Create a new C# Xamarin.Forms application project.
Xamarin project creation

Step 2: Select a project template and required platforms to deploy the application. In this application, the portable assemblies to be shared across multiple platforms, so the .NET Standard code sharing strategy has been selected. For more details about code sharing, refer here.

NOTE

If .NET Standard is not available in the code sharing strategy, the Portable Class Library (PCL) can be selected.

Xamarin project creation step2

Step 3: Install the Syncfusion.Xamarin.PDF NuGet package as a reference to your Xamarin.Forms applications from NuGet.org.
Install Xamarin PDF NuGet package

NOTE

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add the Syncfusion.Licensing assembly reference and include a license key in your projects. Please refer to this link to learn about registering the Syncfusion® license key in your application to use our components.

Step 4: Add new Forms XAML page in portable project if there is no XAML page is defined in the App class. Otherwise, proceed to the next step.

a. To add the new XAML page, right-click the project and select Add > New Item and add a Forms XAML Page from the list. Name it as MainXamlPage.

b. In App class of portable project (App.cs), replace the existing constructor of App class with the following code example, which invokes the MainXamlPage.

public App()
{
  //The root page of your application.
  MainPage = new MainXamlPage();
}

Step 5: In the MainXamlPage.xaml, add new button as follows.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GettingStarted.MainXamlPage">
  <StackLayout VerticalOptions="Center">
    <Button Text="Generate Document" Clicked="OnButtonClicked" HorizontalOptions="Center"/>
  </StackLayout>
</ContentPage>

Step 6: Include the following namespace in the MainXamlPage.xaml.cs file.

using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;

Step 7: Include the following code example in the click event of the button in MainXamlPage.xaml.cs, to create a PDF document and save it in a stream. In this code example, the PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The text has been added in PDF by using the DrawString method of PdfGraphics class.

//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
//Save the document to the stream.
MemoryStream stream = new MemoryStream();
document.Save(stream);
//Close the document.
document.Close(true);
//Save the stream as a file in the device and invoke it for viewing.
Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("Output.pdf", "application/pdf", stream);

Step 8: Download the helper files from this link and add them into the mentioned project. These helper files allow you to save the stream as a physical file and open the file for viewing.

Project File Name Summary
portable project ISave.cs Represent the base interface for save operation
iOS Project SaveIOS.cs Represent the base interface for save operation
PreviewControllerDS.cs Helper class for viewing the PDF file in iOS device
Android project SaveAndroid.cs Save implementation for Android device
WinPhone project SaveWinPhone.cs Save implementation for Windows Phone device
UWP project SaveWindows.cs Save implementation for UWP device.
Windows(8.1) project SaveWindows81.cs Save implementation for WinRT device.

NOTE

Android introduced a new runtime permission model for SDK version 23 and above. Include the following code to enable the Android file provider to save and view the generated PDF document.

Step 9(i): Create a new XML file with the name of provider_paths.xml under the Android project Resources folder and add the following code in it.
Eg: Resources/xml/provider_paths.xml

<?xml version="1.0" encoding="UTF-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

Step 9(ii): Add the following code to the AndroidManifest.xml file located under Properties/AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          android:versionCode="1"
          android:versionName="1.0"
          package="com.companyname. GettingStarted ">
    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="27" />
    <application
        android:label=" GettingStarted.Android"
        android:requestLegacyExternalStorage="true">
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </application>
</manifest>

Include the following changes when deploying the application on Android 11:

  • Enable the android:requestLegacyExternalStorage attribute in the AndroidManifest.xml file when required.
<application android:label=" PDFXamarinSample.Android" android:requestLegacyExternalStorage="true">
  • User permission for read or write external storage.Add the following code to the AndroidManifest.xml file located under Properties/AndroidManifest.xml.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 10: Compile and execute the application. This will create a simple PDF document.

You can download a complete working sample from GitHub.

By executing the program, you will get the PDF document as follows.
Xamarin output PDF document

Click here to explore the rich set of Syncfusion® PDF library features.

An online sample link to create PDF document.