Click here to Skip to main content
13,150,471 members (34,053 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

23.1K views
5 bookmarked
Posted 7 May 2015

How to Convert Android View to PDF

, 7 May 2015
Rate this:
Please Sign up or sign in to vote.
In this blog post, I discuss 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 show 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:

  1. Create Android view
  2. Optionally create a print optimized view
  3. Take an image of the view
  4. Convert the image to PDF using the iText library
  5. Save, preview, share the image

Let‘s take a look at each of these steps.

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 superb, 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 populated.

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:

//Assuming your rootView is called mRootView like so
private View mRootView;

//First Check if the external storage is writable
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
    Toast.
}

//Create a directory for your PDF
File pdfDir = new File(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 = new File(pdfDir, "myPdfFile.pdf");

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

LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout root = (RelativeLayout) inflater.inflate
(R.layout.activity_main, null); //RelativeLayout is root view of my UI(xml) file.
root.setDrawingCacheEnabled(true);
Bitmap screen= getBitmapFromView(this.getWindow().findViewById
(R.id.relativelayout)); // here give id of our root layout (here its my RelativeLayout's id)

Step 4: Convert the Image to PDF

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:

try {
            Document  document = new Document();

            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            screen.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            addImage(document,byteArray);
            document.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

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

private static void addImage(Document document,byte[] byteArray)
    {
        Image image = null;
        try
        {
           image = Image.getInstance(byteArray);
        }
        catch (BadElementException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // image.scaleAbsolute(150f, 150f);
        try
        {
            document.add(image);
        } catch (DocumentException e) {
            // 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 intent = new Intent(Intent.ACTION_VIEW);
 Uri uri = Uri.fromFile(new File(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

Intent email = new Intent(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(new File(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:

  1. I used a Fragment for the above code snippets, hence you see getActivity() for the context.
  2. 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.
  3. You do not have to create different print optimized layouts for tablet and phone because PDF documents are fixed size.
  4. 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).

Happy coding and thanks.

The post How to Convert Android View to PDF appeared first on Val Okafor.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Val Okafor
Software Developer (Senior) ValOkafor.com
United States United States
My name is Val Okafor, I am a Senior Software Engineer with specialization in Android Development. Learning and problem solving is my passion and I share my Android development knowledge through my blog ValOkafor.com.

My Android courses are the courses I wish I had when I started. I teach Android development in the context of a fully developed Android app. I believe that new Android concepts are better understood if they are presented in the context of creating an app from scratch to finish.

I focus on creating Productivity Android apps and besides Android development I have 7 years’ experience as System Administrator supporting Enterprise applications and 2 years’ experience as a Web Developer building websites using PHP and ASP.Net.

I have worked for corporations such as The Home Depot, American Council on Exercise, Legend3D and HD Supply, Inc. I have a bachelor's degree in Information Technology from National University San Diego, California and a master's degree in Software Engineering from Regis University Denver, Colorado.

I enjoy sharing my extensive work experience through my blog, social media.

You may also be interested in...

Comments and Discussions

 
GeneralUsing actvity with scrollview how to get entire screen into pdf file? Pin
Thirulokalai4-Feb-17 2:10
memberThirulokalai4-Feb-17 2:10 
QuestionHow to write data on pdf which is not visible from webview android? Pin
Member 117112481-Jun-15 1:27
memberMember 117112481-Jun-15 1:27 
Generaluseful information Pin
MayurDighe7-May-15 19:57
professionalMayurDighe7-May-15 19:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170924.2 | Last Updated 7 May 2015
Article Copyright 2015 by Val Okafor
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid