How to Convert Android View to PDF

In this blog post I will show you how to convert an Android View to PDF using iTextg library. In my last post, I showed how to create a PDF in Android from scratch. That is the preferred way, today I want to you how you can create PDF quicker by turning the Android view you already have to an image and then converting that image to a PDF, even though this is quicker, please be aware that it will not produce a high quality PDF.

If you need a high quality PDF in Android then you need to roll up your sleeve and dive deep into the PDF API, again this book iText in Action
will help you a lot. If you do not have the time to learn about all the intricacies of programmatic PDF then I will be glad to provide this service to you so you can focus on the rest of your app. Use the Contact Us button above to request a quote.

There are five steps involved in converting an Android View to a PDF and these are:

Create Android view

Optionally create a print optimized view

Take an image of the view

Convert the image to PDF using the iText library

Save, preview, share the image

Let ‘s take a look at each of this step:

Step 1: Create the Android View

This step is self explanatory, this is where you create the Android view that suits your app needs. This is your standard Android view which captures all the information that you need to save/show. Most times if you are going down the path of converting an Android view to Pdf it is because you already have a complex layered view in Android and you do have the time or desire to layout the same view in Pdf from scratch. Please be aware that you will have to take an image of you screen differently depending on whether your view is Linear Layout or Relative Layout and I will show you both in step 3.

Step 2: Create a Print Optimized View

I listed this step as optional but it could be very helpful. In this step, you create an identical layout to the one you want to convert to PDF and in this copy of the layout you remove anything that is not needed in a PDF version of your view and these includes the Action bar, any edit, delete button, etc. For example if your view contains a listview then it is natural that you include a button to delete or increment items in the listview. These are not needed in the PDF. This step is important because remember that I mentioned that the final output of the PDF does not look suberb, therefore removing any clutter will be helpful.

A strategy to accomplish this will be to contain all your display data in a class instance. For example if your app is an event registration app, and you have an Activity/Fragment for Customer registration. Then you can have a Customer.java class and after the user fills out the form: username, email, etc you can create a customer object with the data that the user entered. In the onCreate() or onCreateView method of your Activity or Fragment you will be inflating the layout that is optimized for data entry and when the user clicks on generate PDF then you can either start a Fragment Transaction where you now inflate the print optimized layout or start a new Activity, either way you are passing in the customer object that is now essentially a data dictionary holding the information the user entered and then you populate the print optimize view fields with the information you are holding in that customer object. Then in the onResume() of this Activity or Fragment you take the image of the screen which should now be pupolated.

Step 3: Take an Image of the View:

Like I mentioned there are two ways to take an image of view. If your rootView is a Linear Layout, use this code below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

//Assuming your rootView is called mRootView like so

privateView mRootView;

//First Check if the external storage is writable

Stringstate=Environment.getExternalStorageState();

if(!Environment.MEDIA_MOUNTED.equals(state)){

Toast.

}

//Create a directory for your PDF

File pdfDir=newFile(Environment.getExternalStoragePublicDirectory(

Environment.DIRECTORY_DOCUMENTS),"MyApp");

if(!pdfDir.exists()){

pdfDir.mkdir();

}

//Then take the screen shot

Bitmap screen;View v1=mRootView.getRootView();

v1.setDrawingCacheEnabled(true);

screen=Bitmap.createBitmap(v1.getDrawingCache());

v1.setDrawingCacheEnabled(false);

//Now create the name of your PDF file that you will generate

File pdfFile=newFile(pdfDir,"myPdfFile.pdf");

If your view is a Scrollview instead, you can take the screenshot like this:

Now that you have the screenshot of your view, you need to convert that into a PDF and you need the iTextG library. Please see Step 1 in this my blog for a walk-though on how to add iTextG library to your Android Studio project. With the library added, then you need to continue from where you left off above with this code below:

Create PDF from Image in Android

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

try{

Document document=newDocument();

PdfWriter.getInstance(document,newFileOutputStream(file));

document.open();

ByteArrayOutputStream stream=newByteArrayOutputStream();

screen.compress(Bitmap.CompressFormat.PNG,100,stream);

byte[]byteArray=stream.toByteArray();

addImage(document,byteArray);

document.close();

}

catch(Exceptione){

e.printStackTrace();

}

}

Notice the addimage() method above and here is that method

Add image to a itextG in Android

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

privatestaticvoidaddImage(Document document,byte[]byteArray)

{

Image image=null;

try

{

image=Image.getInstance(byteArray);

}

catch(BadElementExceptione)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

catch(MalformedURLExceptione)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

catch(IOExceptione)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

// image.scaleAbsolute(150f, 150f);

try

{

document.add(image);

}catch(DocumentExceptione){

// TODO Auto-generated catch block

e.printStackTrace();

}

}

Step 5: Save, preview, share the image

That is it, you now have your PDF created from an image of your Android view. Obviously you will want to see it or email it. That also is simple, these are accomplished by identical intents. Here is the Intent to view the PDF you just created

Intent to send email

1

2

3

4

5

Intent intent=newIntent(Intent.ACTION_VIEW);

Uri uri=Uri.fromFile(newFile(pdfDir,"pdfFileName"));

intent.setDataAndType(uri,"application/pdf");

intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

startActivity(intent);

And here is the intent to send an email with the generated PDF as an attachment

Android intent to send email

1

2

3

4

5

6

7

8

9

Intent email=newIntent(Intent.ACTION_SEND);

email.putExtra(Intent.EXTRA_EMAIL,"receiver_email_address");

email.putExtra(Intent.EXTRA_SUBJECT,"subject");

email.putExtra(Intent.EXTRA_TEXT,"email body");

Uri uri=Uri.fromFile(newFile(pdfDir,"pdfFileName"));

email.putExtra(Intent.EXTRA_STREAM,uri);

email.setType("application/pdf");

email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

getActivity().startActivity(email);

Summary

That is it, you have now created a PDF of your Android view in 5 simple steps. Please take note of the following:

I used a Fragment for the above code snippets hence you see getActivity() for the context

It is still a good idea to create a print optimized layout that is full screen because the Action bar does not look good when printed

You do not have to create different print optimized layouts for tablet and phone because PDF documents are fixed size

Once again as you might have seen the generated output is not of high quality, I offer programmatic PDF form creation in native Android(Java) and C# (Xamarin) is interested please use the Contact form to request a quote.