Xamarin.Android: Render PDF to a Bitmap

None
9/6/2016

Downloads

This code sample shows how to draw a PDF page in a Xamarin.Android app by converting a PDF page to a bitmap and assigning that bitmap to an ImageView. To keep the code sample simple, the PDF document itself is embedded as a resource. In a more realistic code sample it would be selected from the device or cloud storage.

We will show the relevant code snippets. You can download the full code sample above.

android-tiger

The main layout of the application only has an ImageView and looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

</LinearLayout>

The main activity overrides the OnCreate and performs the following tasks:

  • create a PDF Page object from "tiger.pdf" that is embedded as a resource
  • render the PDF Page object to a Bitmap
  • assign the Bitmap to the ImageView that is part of the main layout

It looks as follows:

protected async override void OnCreate(Bundle savedInstanceState)
{
   base.OnCreate(savedInstanceState);
   SetContentView(Resource.Layout.Main);

   // create a PDF Page object from "tiger.pdf" that is embedded as a resource
   var assembly = Assembly.GetExecutingAssembly();
   var stream = new MemoryStream();
   using (Stream resourceStream = assembly.GetManifestResourceStream("DrawPdf.Android.tiger.pdf"))
   {
      resourceStream.CopyTo(stream);
   }
   Page page = new Page(stream, 0);

   // render PDF Page object to a Bitmap
   byte[] bytes = null;
   await Task.Run(() =>
   {
      bytes = page.AsPNG(72);
   });
   Bitmap bmp = global::Android.Graphics.BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);

   // assign the Bitmap to the ImageView
   ImageView imageView = FindViewById<ImageView>(Resource.Id.imageView);
   imageView.SetImageBitmap(bmp);
}