Some test text!

menu
search

Show a document in a Fragment

This tutorial only applies to Xamarin.Android.
PdfViewCtrlTabHostFragment requires the full version of the PDFTron library. See PDFTron full or standard?

All actions related to the PDF viewer are handled through the PdfViewCtrlTabHostFragment. This fragment extends android.support.v4.app.Fragment and is responsible for showing documents in tabs.

Host Fragment

linkPrerequisites

  • Integrated PDFTron into your project and added the PDFTron.Android.Tools NuGet package into your project.
  • Minimum API: 16 (using Android Support Libraries)
  • Recommended target API: 28

For trial purposes PDFTron is available without the need for a license key, however a valid license key is required to use PDFTron in a production app. If you do not have a valid license key, please contact sales for a commercial license key.

Your license key is confidential. Please make sure that it is not publicly available (e.g. in your public GitHub).

linkStep 1: Update AndroidManifest.xml

  1. In order to support all the features in PdfViewCtrlTabHostFragment, we will need to add the Android permissions listed in this table. However if you would like to disable certain features and customize your document viewer, you should leave out unnecessary permissions.
Storage permission
Please note that from Android 6.0 (API 23) and up, applications need to request storage permission at runtime before accessing any files on device.
  1. Enable largeHeap and usesClearTextTraffic:

    <application
      ...
      android:largeHeap="true"
      android:usesCleartextTraffic="true">
    </application>
If your app is targeting Android SDK version 28 or higher, you will need to add the android:usesCleartextTraffic="true" attribute in your application tag.
  1. Define your Activity to extend AppCompatActivity and use an AppCompat theme:

    [Activity(Label = "MyReaderActivity",
      ConfigurationChanges = Android.Content.PM.ConfigChanges.ScreenSize | Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.KeyboardHidden,
      Theme = "@style/CustomAppTheme", 
      WindowSoftInputMode = SoftInput.AdjustPan)]
    public class MyReaderActivity : Android.Support.V7.App.AppCompatActivity
    {
    ...
    }
  1. If you have not done so already, add your license in the AndroidManifest.xml file. The final AndroidManifest.xml file should look something like this:

    <manifest ...>
        <!-- Required permissions are added here -->
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
    
        <!-- Add enable largeHeap and usesCleartextTraffic -->
        <application 
            ...
            android:largeHeap="true"
            android:usesCleartextTraffic="true">    
    
            <!-- Add license key in meta-data tag here. This should be inside the application tag. -->
            <meta-data
                android:name="pdftron_license_key"
                android:value="your_license_key_goes_here"/>
    
        </application>
    </manifest>

linkStep 2: Launch the viewer

Use ViewerBuilder to create an instance of PdfViewCtrlTabHostFragment, and add it to your activity layout. To add a document viewer fragment for a given password-protected file, call the following method in your activity:

// Add a viewer fragment to the layout container in the specified activity, 
// and returns the added fragment
public PdfViewCtrlTabHostFragment addViewerFragment(int fragmentContainer, 
    Android.Support.V7.App.AppCompatActivity activity, Uri fileUri, String password)
{
    // Create the viewer fragment
    PdfViewCtrlTabHostFragment fragment = 
        (PdfViewCtrlTabHostFragment) ViewerBuilder.WithUri(fileUri, password).Build(this);

    // Add the fragment to the layout fragment container
    activity.SupportFragmentManager.BeginTransaction()
        .Replace(fragmentContainer, fragment, null)
        .Commit();

    return fragment;
}

where fragmentContainer is the resource id of a layout in your activity that will contain your fragment:

For example:

<?xml version="1.0" encoding="utf-8"?>
<!-- This FrameLayout will contain our viewer fragment-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Alternatively if you have extended PdfViewCtrlTabFragment or PdfViewCtrlTabHostFragment, you can specify your custom classes using the ViewerBuilder.usingTabClass() method and the ViewerBuilder.build() method as follows:

// Add a viewer fragment to the layout container in the specified activity, 
// and returns the added fragment
public MyCustomTabHostFragment addViewerFragment(int fragmentContainer, 
    Android.Support.V7.App.AppCompatActivity activity, Uri fileUri, String password)
{
    // Create the viewer fragment with a custom 
    // PdfViewCtrlTabFragment and PdfViewCtrlTabHostFragment
    PdfViewCtrlTabHostFragment fragment = 
        (PdfViewCtrlTabHostFragment) ViewerBuilder.WithUri(fileUri, password)
                    .UsingTabClass(Java.Lang.Class.FromType(typeof(MyCustomTabFragment)))
                    .Build(activity, Java.Lang.Class.FromType(typeof(MyCustomTabHostFragment)));

    // Add the fragment to the layout fragment container
    activity.SupportFragmentManager.BeginTransaction()
        .Replace(fragmentContainer, fragment, null)
        .Commit();
        
    return fragment;
}
Since PDFTron uses the Fragment class from the Support Library, your activity must extend AppCompatActivityand call getSupportFragmentManager() to get the FragmentManager.

linkStep 3: Customize the viewer

linkCustomize document viewer style

  • If you would like to customize the appearance of the viewer activity, define CustomAppTheme in styles.xml:

    <style name="CustomAppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
      <item name="colorPrimary">@color/app_color_primary_day</item>
      <item name="colorPrimaryDark">@color/app_color_primary_dark_day</item>
      <item name="colorAccent">@color/app_color_accent</item>
      <!-- Action bar -->
      <item name="actionModeBackground">?attr/colorPrimary</item>
      <item name="windowActionModeOverlay">true</item>
    </style>
    PdfViewCtrlTabHostFragment uses the AppCompat theme for material colors. Make sure that the value of android:theme in your activity tag also extends the AppCompat theme.

linkCustomize using ViewerConfig

  • If you would like to customize certain viewer settings or the UI of PdfViewCtrlTabHostFragment, you can use ViewerConfig.Builder. For example:

    public PdfViewCtrlTabHostFragment createUsingViewerConfig(Context context, Uri fileUri, String password)
    {
        // Create a ViewerConfig object with custom settings
        var config = new ViewerConfig.Builder()
            .FullscreenModeEnabled(true)
            .MultiTabEnabled(true)
            .DocumentEditingEnabled(true)
            .LongPressQuickMenuEnabled(true)
            .ToolbarTitle("Host Fragment")
            .ShowSearchView(true)
            .Build();
    
        // Pass in the ViewerConfig object into the ViewerBuilder
        return (PdfViewCtrlTabHostFragment) ViewerBuilder.WithUri(fileUri, password)
            .UsingConfig(config).Build(context);
    }
For details on customizing the UI and using ViewerConfig.Builder, check out the configuration tutorial.

linkCustomize the options toolbar

Default toolbar

The default toolbar menu consists of the following buttons:

  • App navigation
  • Document text search
  • Document sharing
  • View Mode configuration
  • Showing/hiding annotation toolbar
  • Overflow menu

You can fully customize the toolbar menu and the navigation icon by calling the following in ViewerBuilder, with custom menu resource and drawable resource files:

public PdfViewCtrlTabHostFragment createUsingCustomToolbar(Context context, Uri fileUri, int navIcon, int[] menuRes)
{
    return ViewerBuilder.WithUri(fileUri)
            .UsingCustomToolbar(menuRes)// Specify a custom toolbar
            .UsingNavIcon(navIcon)      // Specify a custom navigation component
            .Build(context);
}

To change the icon color and overflow icon color, in styles.xml:

<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="colorControlNormal">@color/red</item>
    <item name="iconTint">@color/red</item>
</style>

To change the navigation icon color, in styles.xml (assume MyTheme is used as the app theme):

<style name="MyTheme" parent="CustomAppTheme">
    <item name="toolbarNavigationButtonStyle">@style/ToolbarButtonNavigationStyle</item>
</style>

<style name="ToolbarButtonNavigationStyle" parent="Widget.AppCompat.Toolbar.Button.Navigation">
    <item name="android:tint">@color/red</item>
</style>

linkStep 4: Interact with the fragment

If you would like to interact with the host fragment you can override the methods that you are interested in through events. For example, you may want to override ToolbarOptionsItemSelected when you add a new menu item, so when the item is clicked you can get a callback. As another example, you can get the callback when the navigation icon is clicked if you override NavButtonPressed.

Here's an example that replaces the default navigation icon and uses a custom toolbar:

var pdfViewCtrlTabHostFragment =
    (PdfViewCtrlTabHostFragment) ViewerBuilder.WithUri(fileUri)
        // Specify a custom toolbar
        .UsingCustomToolbar(new int[] { Resource.Menu.my_custom_toolbar })
        // Specify a custom navigation component
        .UsingNavIcon(Resource.Drawable.ic_arrow_back_white_24dp)      
        .Build(context);

pdfViewCtrlTabHostFragment.ToolbarOptionsItemSelected += (sender, e) =>
{
    // Called when toolbar option item is selected
};

pdfViewCtrlTabHostFragment.NavButtonPressed += (sender, e) =>
{
    // Called when navigation button has been clicked
};

where ic_arrow_back_white_24dp.xml is a drawable resource file for a back arrow icon, and my_custom_toolbar.xml is a menu resource file that contains:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_annotation_toolbar"
        android:icon="@drawable/ic_mode_edit_white"
        android:title="@string/action_annotation_toolbar"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/action_show_toast"
        android:title="Show toast"
        app:showAsAction="never" />
</menu>

This sample replaces the navigation icon, removes all toolbar buttons except the annotation toolbar button, and adds a new Show Toast button:

Host Fragment

Get the answers you need: Support

close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

PDFTron Receives USD$71 Million Growth Investment Led By Silversmith Capital Partners

Learn more
close