Coding android-print

Published on January 9th, 2014 | by Guest

0

How to print a custom document from an Android phone

Android users often store up a number of photos, documents, emails and much more in their Android powered device. Besides, there are some Android users who have a library of e-books that they usually love to read in their spare time. But, there are times when a user wants to share some content; however, showing a screen on their device isn’t the adequate way to share the information. A viable alternative to this is to be able to print the content from your Android app. This gives users the privilege to see a larger version of the information from their Android application and even let them share it with any other person even though he or she is not using their application.

Simply put, printing in Android device allows you to create a snapshot of information, without the need to have a wireless network connection. When talking about Android 4.4 and higher, you can directly print images and documents via Android apps. In this post I will summarize how to enable printing a custom document in your Android application.

Let’s Get Started!

Printing a custom document

The scope of this post is to make you learn about the three essential steps that are a part of printing a custom document:

  • Connect to the Android print manager
  • Create a print adapter
  • Build content for printing

For Android applications, for instance page layout apps, drawing apps and others that essentially focus on producing the graphic output, to develop highly attractive printed pages is the main characteristic indeed. And thus, merely printing an image or an html document is not enough. Rather for these types of applications you need to print output that possess a good control of everything that your page includes – be it fonts, header, footer, text or any other graphic elements.
But to create customized print output for your application entails good investment in programming. Here’s a list of steps that you’ll need to follow:

Connect to the print manager

If your application is directly managing the printing process, then once you have received a print request from the user, then the initial step requires you to connect to the Android print framework and to get hold of an instance of the PrintManager class (this class lets you begin with your printing task and commence the printing lifecycle). Below is an example of a code that illustrates how you can obtain the print manager and begin the printing process.

private void doPrint() {
    // Get a PrintManager instance
    PrintManager printManager = (PrintManager) getActivity()
            .getSystemService(Context.PRINT_SERVICE);

    // Set job name, which will be displayed in the print queue
    String jobName = getActivity().getString(R.string.app_name) + " Document";

    // Start a print job, passing in a PrintDocumentAdapter implementation
    // to handle the generation of a print document
    printManager.print(jobName, new MyPrintDocumentAdapter(getActivity()),
            null); //
}

Create print adapter

In order to handle the step-by-step process of printing, you need a Print Adapter in order to interact with the Android print framework. This method demands users to choose the printers and the print options prior to creating a custom document that they want to print. Remember, these choices can impact the final output when the user selects printers with diverse output capabilities, and different page orientations and sizes. Once you are done with these selections, the print framework will inquire your print adapter to design and produce a print document, in the process of preparing for final output. As soon as a user presses the print button, the framework captures the final print document and forwards it to a print provider for generating the output. In the course of the printing process, users can opt for cancelling the print action, consequently your print adapter has to take notice and respond to the cancellation requests.
The PrintDocumentAdapter is an abstract class that is created with an aim to handle the steps of the printing lifecycle, which comprises of four main callback methods. If you intend to interact accurately with the print framework, then it is recommended that you must implement the callback methods in your print adapter:

onStart() –To begin the print process, you need to call onStart() method at least once.
onLayout() – If a user want to change a print setting that affect the output resulting in different page orientation , or size,  onLayout() method is called. This helps to estimate the layout of the pages that are required to be printed.
onWrite() – This method, in general, is called once or more after every onLayout() call, so as to put printed pages into a file chosen to be printed.
onFinish() – To end the print process, this method is called.

Implementing the layout and the aforementioned write methods plays a crucial role in the functioning of the print adapter. Below are the two sections that explain the ways to implement the layout and the write methods.

Compute print document info

Within the PrintDocumentAdapter class implementation, it is essential for your application to lay down the kind of document that it is creating and also compute the number of pages that needs to be print, in totality. onLayout() method needs to be implemented in the print adapter, as it makes the necessary calculations and further provides information regarding the anticipated output of the print job in a PrintDocumentInfo class, together with the number of pages and content type.

Write a print document file

During the time of writing the print output to a file, onWrite() method of your application’s PrintDocumentAdapter class is called by the Android print framework. OnWrite() parameters state which pages ought to be written and which output file needs to be used. Implementing this method should then put each requested content page to a multi-page PDF document file. Once you are done with this process, you are required to call the onWriteFinished() method of the callback object.

Building PDF page content

Once your application gets printed, it must produce a PDF document and move it onward to the Android print framework used for printing the document. Below is an example of a code that demonstrates how to make use of the PrintedPdfDocument class, to produce PDF pages from your content.
In order to draw the elements on a PDF page, the PrintedPdfDocument class utilizes a Canvas object, which is very much alike to drawing on an activity layout. In addition to this, you can use the Canvas draw methods for drawing elements on the printed page. Let’s have a look at the below given example code that shows how you can build a number of simple elements on a PDF document page using the Canvas draw methods:

private void drawPage(PdfDocument.Page page) {
    Canvas canvas = page.getCanvas();

    // units are in points (1/72 of an inch)
    int titleBaseLine = 72;
    int leftMargin = 54;

    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(36);
    canvas.drawText("Test Title", leftMargin, titleBaseLine, paint);

    paint.setTextSize(11);
    canvas.drawText("Test paragraph", leftMargin, titleBaseLine + 25, paint);

    paint.setColor(Color.BLUE);
    canvas.drawRect(100, 100, 172, 172, paint);
}

When you make use of Canvas object to draw on a PDF page, the elements are detailed in points, which is 1/72 of an inch. Ensure to use this unit of measure for determining the size of elements on the page.

Conclusion

This post helps you learn how to enable custom printing of a document in your Android application by connecting to the Android print manager, creating a print adapter, and finally by building content for printing.

Author bio

Lucie Kruger is a tech savvy writer who works for a leading Android App Development Agency – Mobiers. You can also contact her, if you are looking forward to Hire Android App Developers.

Like this post? Share with your friends.
Share on Facebook0Tweet about this on TwitterShare on Google+0Email this to someone

Tags: , , ,


About the Author

Guest

Contribution of guest authors towards Techno FAQ blog



Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top ↑
  • Latest posts

  • Advertisement

  • Browse by category

  • Recent comments

  • Advertisement

  • Subscribe to updates

    You can get the latest posts from Techno FAQ delivered to you via Email or RSS.

    Enter your email address:

  • Subscribe to our RSS feed
  • Forum activity

  • Find us on Facebook

  • Latest tweets

  • Advertisement