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:
- 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 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:
private View mRootView;
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Toast.
}
File pdfDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), "MyApp");
if (!pdfDir.exists()){
pdfDir.mkdir();
}
Bitmap screen; View v1 = mRootView.getRootView();
v1.setDrawingCacheEnabled(true);
screen = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
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);
root.setDrawingCacheEnabled(true);
Bitmap screen= getBitmapFromView(this.getWindow().findViewById
(R.id.relativelayout));
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)
{
e.printStackTrace();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
document.add(image);
} catch (DocumentException e) {
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 intent
s. 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:
- 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).
Happy coding and thanks.
The post How to Convert Android View to PDF appeared first on Val Okafor.