Click here to Skip to main content
11,432,427 members (67,454 online)
Click here to Skip to main content
Technical Blog

Tagged as

How to Convert Android View to PDF

, 4 May 2015 CPOL
Rate this:
Please Sign up or sign in to vote.
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 [&hellipThe post How to C

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:

  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 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.

//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) is interested please use the Contact form to request a quote.

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 ProntoApps.com
United States United States
I am a Freelance Android developer based in San Diego, CA. Prior to becoming an Android developer I was an eCommerce Web Developer for 2 years and prior to that I was a Systems Administrator and IT Support Technician for 7 years. I have worked in large Enterprise supporting enterprise Applications and also worked in medium sized company building and supporting eCommerce websites and Android app.

I have an Under-graduate degree in Information Technology and a Masters degree in Software Engineering. I enjoy writing and sharing my extensive work experience through my blog. Besides family my passion is learning and growing my technology and personal development skills.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150428.2 | Last Updated 5 May 2015
Article Copyright 2015 by Val Okafor
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid