Android Official Development Document Training Series Course Chinese version: Print custom document printing of content

Source: Internet
Author: User
Tags drawtext

Original address: http://android.xsoftlab.net/training/printing/custom-docs.html

For some applications, such as drawing apps, layout apps, and other apps, these apps focus on graphics output, and having a nice print page is a key feature of them. In this case, it's not just about printing a picture or an HTML document. These programs have a special fine-grained control over everything in the page for this type of printing, including fonts, text flow, page spacing, headers, footers, and graphic elements.

Creating printouts is completely customizable for the program, which requires more design input, as discussed above. You have to build some components that you can communicate with the print frame, and you can also use it to adjust print settings, draw page elements, and manage the printing of multiple pages.

This lesson shows you how to connect with a Print Manager, create a print adapter, and build your print content.

Connecting print managers

When the program needs to manage the print process directly, the first step is to connect to the Android print frame and manipulate instances of the PrintManager class after receiving the user's print request. This class allows you to instantiate a print job and start printing the life process. The following code shows how to get a Print manager and start the printing process.

private  void  doprint  () {//Get A PrintManager instance  PrintManager PrintManager = (PrintManager) getactivity (). Getsystemservice (Cont Ext.    Print_service);    //Set job name, which'll 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 ); //}  

The code above shows how to name a print job and set up an instance of Printdocumentadapter that can handle every step of the printing process. The implementation of the print adapter is discussed in the following sections.

Note: The last parameter of the print () method requires a Printattributes object. You can use this parameter to provide some hints to the print frame and pre-set some options for the previous print cycle, which can improve the user experience. You can also use this parameter to set options that are more suitable for printing content, such as when printing a photo, you can set the orientation of the print to the direction of the photo itself.

Create a print adapter

The print adapter is connected to the Android print frame and handles every step of the printing process. This process requires the user to select a printer and related printing options before creating a document to print. These processes affect the final output, just as the user chooses different print capabilities, different page sizes, and different page orientations. As these options are set, the print framework requires the adapter to present and generate a printed document that prepares for final printing. Once the user presses the Print button, the print frame gets the final printed document and then delivers it to the print provider for printing. During printing, the user can choose to cancel the printing behavior, so the print adapter must listen and respond to the cancellation request.

Abstract class Printdocumentadapter is designed to handle the life cycle of the printing process, which has 4 main callback methods. You must implement these methods in the print adapter so that you can interact with the print framework appropriately:

    • OnStart ()-will be called once at the beginning of the printing process, if the application has any single preprocessing task for the task, such as getting the data segment to be printed, it can be executed here. Implementation of this method is not required.
    • OnLayout ()-will be called once each time the user changes the print settings, which can affect the final output, such as different page sizes or page orientations, giving the program an opportunity to estimate the layout of the page. At a minimum, this method must return the number of pages of the document that will be printed.
    • Onwrite ()-the method is used to work the page to be printed into a file before it is printed. This method may be called one or more times after each invocation of the OnLayout () method.
    • OnFinish ()-this method is called once at the end of the printing process. If the program requires any destruction of the print job, it can be executed here. This method is not required to be implemented.

The following sections describe how to implement the layout and write methods, both of which implement the defining function of the print adapter.

Note: The adapter method is called in the main thread of the program. If you think that executing these methods takes a lot of time, you can implement them in a separate thread. For example, you can put the writing work of a layout or a printed document into a separate Asynctask object.

Calculate Document Information

In the implementation of Printdocumentadapter, the program must specify the type of document, and it also needs to create and calculate the total number of pages of the print work to obtain the dimension information of the printed page. The OnLayout () method should perform these calculations and put the document information that will be output into a Printdocumentinfo object, including the number of pages and the type of content. The following code shows the most basic implementation of the OnLayout () method:

@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."); }}

The execution of OnLayout () will have three results: complete, cancel or fail, the failure is to say that the layout of the calculation can not be completed. You must specify one of the results by calling the appropriate method of the Printdocumentadapter.layoutresultcallback object.

Note: The Boolean parameter of the Onlayoutfinished () method indicates whether the contents of the layout from the last request have been substantially changed. Setting this parameter appropriately allows the print framework to avoid making unnecessary calls to the Onwrite () method, essentially caching the original printed document and improving performance.

The main task of OnLayout () is to calculate the page number, which is used as the output property of the printer. As for how to calculate page numbers this highly dependent program how to typeset printed pages. The following code shows an implementation where the page number depends on the direction of the print:

privateintcomputePageCount(PrintAttributes printAttributes) {    int4// default item count for portrait mode    MediaSize pageSize = printAttributes.getMediaSize();    if (!pageSize.isPortrait()) {        // Six items per page in landscape orientation        6;    }    // Determine number of print items    int printItemCount = getPrintItemCount();    return (int) Math.ceil(printItemCount / itemsPerPage);}
Writing to a printed document file

When the print results are written to a file, the Android print framework calls the Onwrite () method. The parameters of this method indicate which page needs to be written and the output file to be used. Your implementation must render each request content page into a multi-page PDF document file. After this process is complete, you need to invoke the onwritefinished () method of the callback object.

Note: because the Android print framework may call several Onwrite () methods after each call to the OnLayout () method, the onlayoutfinished () is set when the printed page does not change substantially It is important that the Boolean parameter of the method be false, which avoids unnecessary repeated writes to the printed document.

Note: The Boolean parameter of the Onlayoutfinished () method indicates whether the contents of the layout from the last request have been substantially changed. Setting this parameter appropriately allows the print framework to avoid making unnecessary calls to the Onwrite () method, essentially caching the original printed document and improving performance.

The following is a brief demonstration of the basic technical details of the process of creating PDF files using the Printedpdfdocument class:

@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); Pdfdocument.page 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); ...}

This example delegates the contents of the PDF page to the Drawpage () method, which is discussed in the following sections.

As with layout, the execution of Onwrite () has three results: complete, cancel, or fail. The content cannot be written again in case of failure. You must specify the result by Printdocumentadapter.writeresultcallback the appropriate method of the object.

Note: The process of document printing is a resource-intensive operation. To avoid blocking the UI thread, you should consider doing these things in a separate thread, such as in Asynctask. For more information about work execution threads such as asynchronous tasks, see Processes and Threads.

Draw PDF Page Content

When the program is going to print, the program must be a PDF document, and then deliver the document to the Android print frame for printing. You can use any of the PDF generation libraries to accomplish this goal. This lesson shows how to use the Printedpdfdocument class to generate PDF pages.

The Printedpdfdocument class uses a Canvas object to draw elements onto a PDF page, which is similar to the activity's layout drawing. You can use the canvas's drawing method to draw page elements. The following code demonstrates how to use these methods to draw some simple elements onto a PDF document page:

Private void Drawpage(Pdfdocument.page Page) {Canvas canvas = Page.getcanvas ();//units is in points (1/72 of an inch)    intTitlebaseline = the;intLeftMargin = Wu; Paint paint =NewPaint ();    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);}

When you use canvas to draw a PDF page, the element is assigned a position by some point, which is one of the 72 points in inches. Be sure to use this unit of measure to indicate the dimensions of the element. For the positioning of the drawing element, the coordinate system starts at 0, 0 o'clock in the upper-left corner of the page.

TIP: Although canvas objects allow you to place printed elements on the edge of a PDF document, many printers do not have the ability to print elements on the edge to the paper. Make sure that you keep a certain margin of the page when you use this class to build a printed document.

Android Official Development Document Training Series Course Chinese version: Print custom document printing of 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: info-contact@alibabacloud.com 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.