Develop--Training (14)--Print content

Source: Internet
Author: User
Tags drawtext

Android users often see the full content on their devices, but sometimes it is not possible to completely display some information on a single screen. be able to print information from your Android app to users to see larger content from your app or share other people's apps, but not use your app. Printing also allows them to create a snapshot information without relying on a device, enough battery power, or a wireless network connection.

On Android 4.4 or higher, the framework provides services for printing pictures and documents directly from Android applications. This training describes how to print applications, including printing images, HTML pages, and creating custom file prints.

Print a picture

Taking photos and sharing pictures is one of the most popular mobile devices to use. If your app takes pictures, displays them, or allows users to share pictures, you should consider printing those pictures on your app. The Android support Library provides a handy function to be able to print pictures using very little code and simple layouts.

The Printhelper class is in support V4 and provides a print image.

1. Print a picture

The Printhelper class provides an easy way to print a picture. This class has a layout selection, Setscalemode () method that allows you to choose one of two:

Scale_mode_fit--The entire image is displayed in the print area of the page
Scale_mode_fill-fills the print area of the entire page. Selecting this setting means that the top and bottom part, or left and right edges of the image are not printed. If you do not set the mode, Scale_mode_fill is the default value.

Two zoom options The Setscalemode () method keeps the existing image's aspect ratio constant. The following code example shows creating the Printhelper class, setting the extension options, and starting the printing process.

private void doPhotoPrint() {    PrintHelper photoPrinter = new PrintHelper(getActivity());    photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),            R.drawable.droids);    photoPrinter.printBitmap("droids.jpg - test print", bitmap);}

This method can be adjusted from the menu item. Note that the operation of the menu item is not always supported (such as printing), so it should be placed in the overflow menu. For more information, see the Design Guide for Action Bar.

The Printbitmap () method is not an action within your application, allowing the user to select the printer and print options feature when the Android user print interface appears. The user is able to determine the print image and cancel the print operation. If the user chooses to print a picture, a print job is created and the print notification appears in the system's notification bar.

If you want to include some additional content, print out more than just a picture, you have to construct a printed document.

Print an HTML document

Printing content is not just a simple picture, Android requires the combination of text and charts in a printed document. The Android framework provides a way to compose documents using HTML groups and print with minimal code.

On Android 4.4 or higher, the WebView class was updated to support the printing of HTML content. This class allows you to load a local HTML resource, or download a page from a webpage, create a print job, and pass it to the Android Print service.

1. Loading an HTML document

Print an HTML document from the WebView contains the load HTML resource or constructs an HTML document as a String. This section describes how to build an HTML string, load it into WebView, and print it.

This View object acts as part of an active layout. However, if your application does not use WebView, you can create an instance of a class specifically for printing purposes. The main steps to creating a custom print view are.

1. Create a webviewclient, start a print job, and then load the HTML resource
2. Load the HTML resource into the WebView object.

The following code example, how to create a simple webviewclient and dynamically create an HTML document.

PrivateWebView Mwebview;Private void Dowebviewprint() {//Create a WebView object specifically for printingWebView WebView =NewWebView (Getactivity ()); Webview.setwebviewclient (NewWebviewclient () { Public Boolean shouldoverrideurlloading(WebView view, String URL) {return false; }@Override             Public void onpagefinished(WebView view, String URL) {LOG.I (TAG,"page finished loading"+ URL);                Createwebprintjob (view); Mwebview =NULL; }    });//Generate an HTML document on the fly:String HTMLDocument ="+"Testing, testing...</p></body>; Webview.loaddatawithbaseurl (NULL, HTMLDocument,"Text/html","UTF-8",NULL);//Keep a reference to WebView object until you pass the Printdocumentadapter    // to the PrintManagerMwebview = WebView;}

Note: Make sure that you generate a print job that occurs in the onpagefinished () method, Webviewclient is created before this. If you do not wait until the page loads, the printout may be incomplete or blank, or it may fail completely.

Note: the example code above retains an instance of an instance of the WebView object, which is not garbage collected when the print job is created. Make sure you do the same thing in your own implementation, otherwise, printing may fail.

If you want to print a chart on the page, the chart file is placed in the assest/directory of your project, specifying the base URL as the first parameter of the Loaddatawithbaseurl () method.

webView.loadDataWithBaseURL("file:///android_asset/images/", htmlBody,        "text/HTML""UTF-8"null);

You can also load a Web page and print and replace the Loaddatawithbaseurl () method with Loadurl ().

// Print an existing web page (remember to request INTERNET permission!):webView.loadUrl("");

When using WebView to create a print file, you should be aware of the following limitations.

1. You cannot add headers or footers, page numbers, and other documents.

The printing options for 2.HTML documents do not include the ability to print pages, for example, a 10-page HTML document does not support printing 2 to 4 pages.

3. An instance of a WebView can only process one print job at a time.

4. An HTML document that contains CSS print properties, such as the landscape property, is not supported.

5. You cannot use JavaScript in an HTML document to trigger printing.

Note: This print content WebView object contained in the layout can also be printed once the document is loaded.

2. Create a print job

Create a WebView, load the HTML content, the application almost finished the printing part. The next step is to access PrintManager, create a print adapter, and finally create a print job. The following example shows how to perform these steps.

private  void  createwebprintjob  (WebView WebView) {//Get a PrintManager Instance  PrintManager PrintManager = (PrintManager) getactivity (). Getsystemservice (Context.print_ser VICE); //Get a print adapter instance  Printdocumentadapter printadapter = Webview.createprintdocumentadapter (); //Create a print job with name and adapter instance  String jobName = getString (R.string . App_name) + ; PrintJob PrintJob = Printmanager.print (JobName, Printadapter, new  printattrib Utes. Builder (). build ()); //Save the Job object for later status checking  mprintjobs.add (PRINTJOB);} 

This example saves an instance of PrintJob in the application, which is not required. Your application can use this object's process to track the processing of print jobs. This method is useful when you want to monitor the print status of your print job when it finishes, fails, or the user cancels. Creating an in-app notification is not required because the print framework automatically creates a print job for system notifications.

Print a custom file

For some applications, like Paint app, page layout app and other apps, focus on graphics output, creating a nice printed page is very important. In such cases, it is not enough to print a picture or an HTML file. These types of applications require the printout to precisely control everything, entering a page that includes fonts, text streams, page breaks, page headers, footers, and graphic elements.

Create a fully customizable printout, and your application requires more programmatic processing. You have to build these components, print the frame of communication, adjust the print settings, draw the printed elements of the page, and manage multi-page printing.

Lesson shows you how to link the Print Manager to create a print adapter and build content to print.

1. Connect to Print Manager

When your reference program directly manages the printing process, the first step is to receive a print request from the user connected to the Android print frame, after binding the PrintManager instance. This class allows you to initialize the print job and start the print life cycle. The following code example shows how to get the Print Manager and start the printing process.

private   void  doprint  () {//Get a PrintManager instance
      PrintManager PrintManager = (PrintManager) getactivity (). Getsystemservice (Context.print_service);    //Set job name, which'll be displayed in the print queue  String jobName = getactivity (). getString (R.string . App_name) + ; //Start a print job, passing in a printdocumentadapter implementation  //to handle the generation of a print document  printmanager.print (jobName, new  Myprintdocumentadapter (getactivity ()), null ); //}  

The example code above demonstrates how to name a print job and set an instance of the Printdocumentadapter class to handle the print life cycle steps.

2. Create a print adapter

The print adapter interacts with the Android print frame to process the printing. This process requires the user to select Printer and print options before creating a document to print. These choices can affect the final output, the user selects the printer, the printer has different output capabilities, different page sizes, or different page orientations. With these choices, the print framework asks the adapter and generates a printed document to prepare for the final output. Once the user presses the Print button, the print frame takes away the final printed document and passes it to the output print Provider. During the printing process, the user can choose to cancel the print operation, so your print adapter must also listen and process the canceled request.

The Printdocumentadapter abstract class is designed to handle printing cycles, with four main callback methods. You must implement these methods in your print adapter in response to some actions of the print framework.

OnStart ()--called once at the beginning of the printing process. If your application has any one-time tasks to prepare for execution, such as to print a snapshot of the data, execute them here. is not a method that must be implemented.

OnLayout ()--called every time the user changes the print settings, affecting the printed output. such as different page sizes, page orientation, gives the application a chance to calculate the layout of the page to be printed. At a minimum, this method must return the estimated number of pages in the printed document.

Onwrite ()-Called when a printed page is rendered to a file to be printed. This method can be called once or more after each onlayout ().

OnFinish ()--called once at the end of the printing process. If your application has any one-time destroy tasks to execute, execute them. is not a method that must be implemented.

Note: The methods of these adapters are in the main thread of the application. If you expect the implementation of these methods to take a lot of time to implement in a separate thread to execute. For example, you can encapsulate a layout or print a document that is written to work in a Asynctask object.

3. Calculate the information of the printed file

In an implemented Printdocumentadapter class, your application must be able to specify the type of document created and the number of pages that calculate the total print job, giving information about the size of the printed page. Implement the OnLayout () method in the adapter to make these calculations and provide the expected output information for the print job in the Printdocumentinfo class, including the number of pages and the content type. The following code example shows a basic implementation of the OnLayout () method in Printdocumentadapter.

@Override Public void OnLayout(Printattributes oldattributes, printattributes newattributes, cancellationsignal Cancellationsignal, Layoutresultcallback callback, Bundle metadata) {//Create a new pdfdocument with the requested page attributesMpdfdocument =NewPrintedpdfdocument (Getactivity (), newattributes);//Respond to cancellation request    if(Cancellationsignal.iscancelled ()) {callback.onlayoutcancelled ();return; }//Compute The expected number of printed pages    intPages = Computepagecount (newattributes);if(Pages >0) {//Return print information to print frameworkPrintdocumentinfo info =NewPrintdocumentinfo. Builder ("Print_output.pdf"). setContentType (printdocumentinfo.content_type_document). Setpagecount (pages); . build ();//Content layout reflow is completeCallback.onlayoutfinished (Info,true); }Else{//Otherwise report a error to the print frameworkCallback.onlayoutfailed ("page count calculation failed."); }}//Calculate the number of printed pagesPrivate int Computepagecount(Printattributes printattributes) {intItemsPerPage =4;//Default item count for portrait modeMediasize pageSize = Printattributes.getmediasize ();if(!pagesize.isportrait ()) {//Six items per page in landscape orientationItemsPerPage =6; }//Determine number of print items    intPrintitemcount = Getprintitemcount ();return(int) Math.ceil (printitemcount/itemsperpage);}

Note: the onlayoutfinished () method of the Boolean parameter shows whether the layout content has changed since the last request. Setting this parameter correctly allows the print framework to avoid unnecessary calls to the Onwrite () method, essentially caching previously written printed documents for improved performance.

4. Write a printed document file

It is time to write the print output to a file, the Android print framework calls the Onwrite () method in the application's Printdocumentadapter class. The parameter of this method specifies which page is written to the output file to be used. Implementing this method must provide the content of the requested page to a multi-page PDF document file. When this process is complete, the callback onwritefinished () object.

Note: The Android print framework may callback the Onwrite () method one or more times, at each call to OnLayout (). For this reason, it is important to set the Onlayoutfinished () method Boolean parameter to False when the layout of the print content does not change. To avoid unnecessary rewriting of printed documents.

The following example demonstrates this process using the basic structure of the Printedpdfdocument class to create a PDF file.

@Override Public void Onwrite(FinalPagerange[] Pageranges,FinalParcelfiledescriptor destination,FinalCancellationsignal Cancellationsignal,FinalWriteresultcallback callback) {//Iterate over each page of the document,    //Check if it's in the output range.     for(inti =0; i < totalpages; i++) {//Check to see if this page was in the output range.        if(Containspage (Pageranges, i)) {//If So, add it to Writtenpagesarray. Writtenpagesarray.size ()            //is used to compute the next Output page index.Writtenpagesarray.append (Writtenpagesarray.size (), i); Page = Mpdfdocument.startpage (i);//Check for cancellation            if(Cancellationsignal.iscancelled ())                {callback.onwritecancelled ();                Mpdfdocument.close (); Mpdfdocument =NULL;return; }//Draw page content for printingDrawpage (page);//Rendering is complete and so page can be finalized.Mpdfdocument.finishpage (page); }    }//Write PDF document to file    Try{Mpdfdocument.writeto (NewFileOutputStream (Destination.getfiledescriptor ())); }Catch(IOException e) {callback.onwritefailed (e.tostring ());return; }finally{Mpdfdocument.close (); Mpdfdocument =NULL; } pagerange[] Writtenpages = Computewrittenpages ();//Signal The print framework the document is completeCallback.onwritefinished (writtenpages); ...}

A time-consuming operation when creating a document should be placed in a child thread to execute.

5. Draw the contents of the PDF page

When the application prints, your application must generate a PDF document and pass it to the Android print frame for printing. You can use any PDF build library to generate the destination file. This lesson shows you how to use the Printedpdfdocument class to generate PDF pages from your content.

The Printedpdfdocument class uses a Canvas object element to draw a PDF page, similar to drawing an activity's layout. You can draw elements on a printed page using the Canvas drawing method. The following sample code demonstrates how to draw some simple elements on a PDF document page using these methods.

private void Drawpage (pdfdocument. Pagepage) {Canvas canvas = page. Getcanvas();Units isinchPoints (1/ theof an inch) int titlebaseline = the;int leftMargin = Wu;Paint paint = new paint ();Paint. SetColor(Color. BLACK);Paint. Settextsize( $);Canvas. DrawText("Test Title", LeftMargin, Titlebaseline, paint);Paint. Settextsize( One);Canvas. DrawText("Test paragraph", LeftMargin, Titlebaseline + -, paint);Paint. SetColor(Color. BLUE);Canvas. DrawRect( -, -,172,172, paint);}

Develop--Training (14)--Print content

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.